COSC 3430 · Artificial Intelligence

Feature Scaling, Side by Side

Three experiments with the California housing districts from class: why scales matter to an algorithm that measures distances, how min-max scaling and standardization react to one bad value, and what scaling cannot do that a transformation can. The districts are a sample of 2,000 from the training set; panel 2 uses all 16,512.

1Who is my nearest neighbor?

Click any district. Its 5 nearest neighbors light up, measured by the ordinary (Euclidean) distance on total_rooms and median_income, as kNN would measure it. The shaded shape is the neighborhood: every district inside it is at least as close as the 5th neighbor.

Distance computed on
districttotal_roomsmedian_incomedistanceshare of distance²: rooms | income

The plot always shows the original units, so you can compare the three modes. Districts with more than 10,000 rooms are drawn at the right edge. Statistics for scaling (min, max, mean, standard deviation) come from these 2,000 districts, as fit() would compute them.

2One bad value, two scalers

All 16,512 training districts have a median_income between 0.5 and 15 (tens of thousands of dollars). Add one more district whose income was typed in wrong, and move it up.

Income of the extra district
—

Min-max scaling

Standardization

min-max
the 16,512 others lie in—
income 3.5 becomes—
standardized
mean | std—
income 3.5 becomes—

3Scaling vs. transforming

Pick a feature and a treatment. Watch the numbers on the x-axis, and watch the shape. Square root, x^0.25 and log are steps on one ladder: each shrinks large values harder than the one before.

Feature
Treatment
mean—
standard deviation—
range—
skewness (0 = symmetric)—

Bonus: a new feature, similarity to age 35

The Gaussian RBF exp(-γ (age − 35)²) is 1 at age 35 and falls toward 0 away from it. Its values lie between 0 and 1, while the histogram counts run into the hundreds: on one y-axis, the curve disappears.

γ (gamma)
—
Y-axes

The same in scikit-learn

# fit on the training set only, then transform any set
from sklearn.preprocessing import MinMaxScaler, StandardScaler
min_max_scaler = MinMaxScaler(feature_range=(0, 1))
housing_num_min_max_scaled = min_max_scaler.fit_transform(housing_num)
std_scaler = StandardScaler()
housing_num_std_scaled = std_scaler.fit_transform(housing_num)

# a transformation changes the shape
np.log(housing_num["population"])

# similarity to age 35 as a new feature
from sklearn.metrics.pairwise import rbf_kernel
age_simil_35 = rbf_kernel(housing[["housing_median_age"]], [[35]], gamma=0.1)

Reading the panels

Built to accompany COSC 3430 (Artificial Intelligence), end-to-end ML project, part 6 (feature scaling and transformation). Data: the California housing training set from class (stratified split, random_state=42); panels 1 and 3 use a random sample of 2,000 of its 16,512 districts, panel 2 uses the income of all of them.