Unit 1, lesson 8

Feature Scaling and Categorical Encoding

How feature scaling, standardization with the mean and standard deviation, and min-max scaling are fitted on training data only, and how one-hot encoding handles ordinal and unknown categories.

  • Video 8
  • Data Quality and Feature Preparation

A query parcel is compared with two others by weight in kilograms and delivery distance in kilometers. Writing the distance in meters instead changes no parcel at all, yet it can change which parcel a distance-based model calls the most similar. Categories such as service type raise the same question, because turning names into numbers decides which categories count as close. This lesson builds numerical and categorical features whose centers, scales and vocabularies are learned from training data only and then applied unchanged to every later record.

Key terms

Feature scaling

Definition Feature scaling replaces a numerical feature xjx_j by

x~j=xj−cjsj\tilde{x}_j = \frac{x_j - c_j}{s_j}

where the center cjc_j and the scale sj>0s_j > 0 are numbers learned from the training values of that feature. Standardization and min-max scaling are the most common choices, and robust scaling uses the median and the interquartile range. Each such map is increasing, so the order of the values within a column stays the same. What changes is how much each feature counts when features are combined. The centers cancel in differences, so for two records x\mathbf{x} and z\mathbf{z} in Rp\mathbb{R}^p the squared Euclidean distance after scaling is

∥x~−z~∥22=∑j=1p(xj−zj)2sj2,\begin{aligned} &\lVert \tilde{\mathbf{x}} - \tilde{\mathbf{z}} \rVert_2^2 \\[0.4em] &\quad = \sum_{j=1}^{p} \frac{(x_j - z_j)^2}{s_j^2}, \end{aligned}

and feature jj is weighted by 1/sj21/s_j^2. Models that compare records through distances, such as k-nearest neighbors, can give different answers under different scalings.

In plain words Raw numbers carry their units. A sum of squared differences that adds kilograms to kilometers is a chosen numerical recipe, not a physical length, and the feature with the largest numerical differences dominates it. Scaling sets those weights on purpose instead of leaving them to the choice of units.

Example The query weighs 2 kilograms and travels 5 kilometers. Parcel A weighs 3 kilograms and travels 7 kilometers, and parcel B weighs 5 kilograms and travels 5.1 kilometers. Their differences from the query are 1 and 2 for A and 3 and 0.1 for B, so the unscaled sums of squares are 1+4=51 + 4 = 5 for A and 9+0.01=9.019 + 0.01 = 9.01 for B, and A is closer. With the distance in meters the differences become 2000 and 100, the sums become 1+20002=4,000,0011 + 2000^2 = 4{,}000{,}001 for A and 9+1002=10,0099 + 100^2 = 10{,}009 for B, and B is now closer, although no parcel changed.

Standardization and standard deviation

Definition Let x1,…,xnx_1, \dots, x_n be the training values of one numerical feature, with n≥1n \ge 1. Their mean and standard deviation are

xˉ=1n∑i=1nxi,s=1n∑i=1n(xi−xˉ)2,\begin{gathered} \bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i, \\[0.4em] s = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2}, \end{gathered}

so the standard deviation is the square root of the average squared deviation from the mean, in the units of the feature. Standardization maps a value xx to

z=x−xˉs,z = \frac{x - \bar{x}}{s},

using the saved training values of xˉ\bar{x} and ss. This page divides by nn, the convention of many scaling routines. The sample standard deviation divides by n−1n - 1 instead, which needs n≥2n \ge 2 and gives a larger value whenever s>0s > 0, so a fitted scaler should record its divisor. When s>0s > 0, the standardized training values have mean 0 and standard deviation 1 under the same divisor. Multiplying a feature by a constant a>0a > 0, as a change of units does, multiplies its mean and standard deviation by aa too, so the standardized values do not change. If every training value is the same, then s=0s = 0 and the division is undefined. A documented convention uses the scale 1 after centering, so every training entry becomes 0. Standardization moves and rescales a distribution without changing its shape, so it does not make data normally distributed, and a single extreme value can move both the mean and the standard deviation a great deal.

In plain words A standardized value counts how many training standard deviations a value lies above or below the training mean. The standard deviation is a typical distance from the center, the root of the mean squared deviation, and it comes back in the original units.

Example Four constructed training parcels weigh 2, 4, 6 and 8 kilograms and travel 10, 10, 30 and 30 kilometers. The weights add to 20, so their mean is 5 kilograms. The deviations −3,−1,1,3-3, -1, 1, 3 have squares 9, 1, 1 and 9 with total 20, so

s=20/4=5≈2.236 kg.\begin{aligned} s &= \sqrt{20/4} = \sqrt{5} \\[0.4em] &\approx 2.236 \ \text{kg}. \end{aligned}

The distances have mean 20 kilometers and deviations of ±10\pm 10, so their standard deviation is 10 kilometers. The standardized training weights are (−3,−1,1,3)/5≈(−1.342,−0.447,0.447,1.342)(-3, -1, 1, 3)/\sqrt{5} \approx (-1.342, -0.447, 0.447, 1.342) and the standardized distances are −1,−1,1,1-1, -1, 1, 1. With the divisor n−1n - 1 the weight standard deviation would be 20/3≈2.582\sqrt{20/3} \approx 2.582 kilograms. A constant training column 5, 5, 5 has s=0s = 0 and becomes 0, 0, 0 under the stated convention.

Min-max scaling

Definition Let mm and MM be the smallest and largest training values of a feature, with M>mM > m. Min-max scaling maps a value xx to

x−mM−m.\frac{x - m}{M - m}.

Training values land in the interval [0,1][0, 1], and a later value outside [m,M][m, M] lands outside it. If M=mM = m, the formula divides by zero and needs a declared convention. Clipping the results to [0,1][0, 1] would be an extra modeling decision that hides how far a new value lies beyond the training range. The name normalization is used for min-max scaling, for standardization and for row normalization, which divides a whole record vector x≠0\mathbf{x} \neq \mathbf{0} by its length ∥x∥2\lVert \mathbf{x} \rVert_2, so a pipeline should state its formula rather than the name.

In plain words Min-max scaling stretches the training range onto 0 to 1. It depends only on the two extreme training values, so one unusual training value sets the scale for every record.

Example The training weights run from 2 to 8 kilograms. A weight of 7 maps to (7−2)/(8−2)=5/6≈0.833(7 - 2)/(8 - 2) = 5/6 \approx 0.833, and a future weight of 10 maps to 8/6=4/38/6 = 4/3, above 1. Row normalization of the vector (3,4)(3, 4), whose length is 9+16=5\sqrt{9 + 16} = 5, gives (0.6,0.8)(0.6, 0.8). That vector has length 1 and the same direction, but it no longer records the original size, which matters whenever the total amount carries information.

Train-only fit

Definition A train-only fit computes every quantity a preprocessing step learns from data, such as means, standard deviations, minima and maxima, medians, category vocabularies and column orders, from the training data alone. The fitted values are saved and applied unchanged to training, validation, test and future records. In cross-validation each fold fits on its own training part. Fitting on all the data, or refitting on a held-out batch, lets held-out information into the representation and makes the input given to one record depend on which other records arrived with it.

In plain words The scaler and the encoder are part of the model. They are learned once from training data and travel with the model, so a parcel receives the same inputs whether it arrives alone or in a large batch.

Example A held-out parcel weighs 5 kilograms and travels 40 kilometers. With the saved means 5 and 20 and standard deviations 5\sqrt{5} and 10, its standardized features are

5−55=0,40−2010=2.\begin{gathered} \frac{5 - 5}{\sqrt{5}} = 0, \\[0.4em] \frac{40 - 20}{10} = 2. \end{gathered}

Its distance lies two training standard deviations above the training mean. Refitting on this parcel alone would give a standard deviation of 0, and refitting on a held-out batch would replace the saved values with statistics of data meant for evaluation.

One-hot encoding and ordinal categories

Definition Let a categorical feature have the vocabulary c1,…,cKc_1, \dots, c_K, learned from training data and stored in a fixed order. One-hot encoding represents a value by KK indicator columns, where column kk equals 1 if the value is ckc_k and 0 otherwise, so each known category has exactly one entry equal to 1. Any two distinct known categories are then at Euclidean distance 2\sqrt{2}, so the encoding puts no order on the categories and makes no pair closer than another. An ordinal category is a categorical feature whose values have a meaningful order, such as small, medium and large. Integer codes 0, 1 and 2 keep that order, but when a model uses them as numbers they also assert equal gaps, which is an extra assumption. Integer codes for categories without an order, such as service types or colors, invent both an order and distances.

In plain words Names are not numbers. One-hot encoding lets a model learn a separate effect for each category without claiming that one service is twice another. For ordered categories, decide whether equal steps are justified for the model at hand, instead of choosing a code just because the column contains words.

Example Service type has the training vocabulary economy, express and pickup. The codes 0, 1 and 2 would put economy twice as far from pickup as from express. One-hot encoding in the saved order gives economy (1,0,0)(1, 0, 0), express (0,1,0)(0, 1, 0) and pickup (0,0,1)(0, 0, 1). Every pair differs in two coordinates, so every distance is 1+1=2\sqrt{1 + 1} = \sqrt{2}. A capacity class with the values small, medium and large coded 0, 1 and 2 keeps its order, but it also asserts that medium lies exactly halfway between the other two.

Unknown category

Definition An unknown category is a value of a categorical feature that does not appear in the vocabulary fitted on the training data. The encoder needs a declared rule for it. Common rules raise an error, set all the known indicator columns to 0, or set a dedicated unknown column to 1. The training data contain no record of the new value, so they hold no evidence about how it behaves, and detecting it does not supply that evidence. The vocabulary is learned inside each training fold like any fitted quantity, so a category that appears only in a fold’s held-out part is unknown there as well.

In plain words New categories appear after deployment. A declared rule turns them into a visible, countable event instead of a silent error, and counting how often the rule fires shows when the vocabulary needs refitting on newer training data.

Example The saved columns are economy, express, pickup and unknown. An express parcel becomes (0,1,0,0)(0, 1, 0, 0), and a parcel with the new service drone, absent from training, becomes (0,0,0,1)(0, 0, 0, 1) instead of being dropped or confused with a known service. The unknown column equals 0 for every training record, so nothing in the training data tells the model how drone deliveries behave.

Check yourself

  1. A held-out parcel weighs 7 kilograms, travels 15 kilometers and uses the express service. Write its six-entry representation with the saved standardizer, whose means are 5 and 20 and whose standard deviations are 5\sqrt{5} and 10, followed by the four saved category columns.
Show the answer

The weight gives (7−5)/5=2/5≈0.894(7 - 5)/\sqrt{5} = 2/\sqrt{5} \approx 0.894, and the distance gives (15−20)/10=−0.5(15 - 20)/10 = -0.5. The express indicators in the saved order economy, express, pickup, unknown are (0,1,0,0)(0, 1, 0, 0). The representation is approximately

(0.894,−0.5,0,1,0,0),(0.894, -0.5, 0, 1, 0, 0),

two standardized numbers followed by four indicators. A scaler fitted with the divisor n−1n - 1 would give 2/20/3≈0.7752/\sqrt{20/3} \approx 0.775 for the weight instead, which is why the divisor is saved with the scaler.

  1. A color feature is coded red 0, blue 1 and green 2, and a nearest-neighbor model uses the code as a number. Compute the distances between the three colors, then recode them as red 0, green 1 and blue 2. What do you conclude, and what does one-hot encoding give?
Show the answer

Under the first coding red and blue are at distance 1, blue and green at distance 1, and red and green at distance 2, so red looks twice as far from green as from blue. Under the second coding red and green are at distance 1 and red and blue at distance 2, so the conclusion reverses. No color changed, only an arbitrary assignment of integers, so these gaps carry no information about the colors and they still steer which neighbors count as close. One-hot encoding gives red (1,0,0)(1, 0, 0), blue (0,1,0)(0, 1, 0) and green (0,0,1)(0, 0, 1), and every pair is at distance 2\sqrt{2} whatever the column order.

  1. A test batch has the weights 6, 8 and 10 kilograms. A colleague standardizes the batch with its own mean and standard deviation, dividing by nn. Which value does the 8-kilogram parcel receive, which value does the saved training scaler give, and why is the batch rule wrong?
Show the answer

The batch mean is 8, the deviations are −2,0,2-2, 0, 2 and the batch standard deviation is 8/3≈1.633\sqrt{8/3} \approx 1.633, so the parcel receives 0. The saved scaler gives (8−5)/5=3/5≈1.342(8 - 5)/\sqrt{5} = 3/\sqrt{5} \approx 1.342. In a batch with the weights 8, 9 and 10 the batch rule would give (8−9)/2/3≈−1.225(8 - 9)/\sqrt{2/3} \approx -1.225 for the same parcel. Under the batch rule the input depends on which other parcels arrived together, the model receives numbers on a scale it was not trained on, and the test data shape their own preprocessing. The fix is to apply the saved training mean and standard deviation to every later record.

How this lesson connects