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
fit_transformon the training set,transformon the test set.- Fitting the scaler on test data leaks information.
mean_andscale_are what it learned.
Keywords and builtins used here
print
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.
Step 1 of 4 in Preprocessing, step 4 of 25 in Machine learning with scikit-learn.