StandardScaler
- Machine Learning course
- Beginner
- Lesson 76/112
- 5 min
StandardScaler makes data mean 0 and standard deviation 1.
StandardScaler
StandardScaler transforms each feature with z = (x - mean) / std; as a result each column has mean 0 and standard deviation 1:
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
Z = sc.fit_transform(X)
print(Z.mean(axis=0).round(3), Z.std(axis=0)) # [0. 0.] [1. 1.]
print(sc.mean_, sc.scale_) # learned valuesThe values are unbounded; an outlier can get a large z-score like 4-5.
inverse_transform
Scaled values return to the original unit with inverse_transform. It is used to make the prediction of a model trained on a scaled target readable:
Z = sc.transform([[35, 5000]])
print(sc.inverse_transform(Z)) # [[ 35. 5000.]]sc.mean_ and sc.scale_ are learned in training; transform uses the same values on every call.
Practice Standardise
Transform X with StandardScaler and print the result with np.round(..., 3). Then print scale_ with np.round(..., 1).
Starter code
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[25, 3000], [35, 5000], [45, 10000]], dtype=float)
# buraya yazSample solution
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[25, 3000], [35, 5000], [45, 10000]], dtype=float)
sc = StandardScaler()
Z = sc.fit_transform(X)
print(np.round(Z, 3))
print(np.round(sc.scale_, 1))Expected output
[[-1.225 -1.019] [ 0. -0.34 ] [ 1.225 1.359]] [ 8.2 2943.9]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For a feature with mean 50 and std 10, what is the z-score of 70?
- 20
- -2.0
- 2.0 Correct answer
- 0.7
Explanation: (70 - 50) / 10 = 2.
2 Turn the scaled values back into the original unit.
X_geri = sc.____(Z)
X_geri = sc.inverse_transform(Z)
Explanation: inverse_transform computes x = z·std + mean.
3 Match the attributes.
| Term | Meaning |
|---|---|
mean_ |
Learned means |
scale_ |
Learned stds |
fit_transform |
Learn and transform |
inverse_transform |
Transform back |