typestar

Scaling features in Python

Models that measure distance need features on comparable scales.

from sklearn.preprocessing import StandardScaler

train = [[1.0, 100.0], [2.0, 300.0], [3.0, 500.0]]
test = [[2.5, 400.0]]

scaler = StandardScaler()
scaled_train = scaler.fit_transform(train)
scaled_test = scaler.transform(test)

print(scaler.mean_, scaler.scale_)
print(scaled_train.round(2))
print(scaled_test.round(2))

How it works

  1. fit_transform on the training set, transform on the test set.
  2. Fitting the scaler on test data leaks information.
  3. mean_ and scale_ are what it learned.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
322
Tokens
85
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 1 of 4 in Preprocessing, step 4 of 25 in Machine learning with scikit-learn.

← Previous Next →