Sub topic 9
Undoing scaling with inverse_transform
This chapter assumes you can fit a StandardScaler or MinMaxScaler and call transform. It also assumes you know why a scaler must be fitted on training data only. The chapter shows how to map scaled values back to their original units and where that is useful.
Why you need to go back
A scaled column is hard to read. A value of 1.3 after standardization means "1.3 standard deviations above the training mean". It does not tell you the temperature, price, or age. You often need the original units in these cases:
- You scaled the target
yto train a regressor, and you want predictions in dollars, not z-scores. - You want to report feature values for a flagged row, such as a cluster center or a misclassified sample.
- You modified data in scaled space (for example, generated synthetic points) and need real-world values.
How inverse_transform works
Each scaler learned statistics during fit. inverse_transform applies the opposite formula with those same statistics.
| Scaler | transform | inverse_transform |
|---|---|---|
| StandardScaler | `(x - mean_) / scale_` | `x * scale_ + mean_` |
| MinMaxScaler (range 0 to 1) | `(x - data_min_) / (data_max_ - data_min_)` | `x * (data_max_ - data_min_) + data_min_` |
The method does not look at the data you give it to compute anything new. It only reuses the stored statistics. This means you can pass any array with the same number of columns, not just output from transform.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[10.0], [20.0], [30.0]])
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
X_back = scaler.inverse_transform(X_scaled)
print(np.allclose(X, X_back))The output is True. Use np.allclose instead of ==, because floating-point arithmetic can leave tiny differences such as 20.000000000000004.
Worked example: scaling the target
Some regressors train more smoothly when y is scaled. After training, you must undo the scaling on the predictions. Scalers expect a 2D array, so reshape y into one column.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
y = 50000 + 12000 * X[:, 0] + rng.normal(scale=2000, size=200)
y_scaler = StandardScaler()
y_scaled = y_scaler.fit_transform(y.reshape(-1, 1)).ravel()
model = Ridge().fit(X, y_scaled)
pred_scaled = model.predict(X[:3])
pred = y_scaler.inverse_transform(pred_scaled.reshape(-1, 1)).ravel()
print(pred)
print(y[:3])The predictions in pred are close to the true prices in y[:3]. Without the inverse_transform call, pred_scaled would be values near -1 to 1, which would look like a broken model.
You can skip the manual steps with TransformedTargetRegressor. It scales y before fitting and inverts the scaling inside predict.
import numpy as np
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
y = 50000 + 12000 * X[:, 0] + rng.normal(scale=2000, size=200)
model = TransformedTargetRegressor(
regressor=Ridge(),
transformer=StandardScaler(),
)
model.fit(X, y)
print(model.predict(X[:3]))Common errors
- Using the wrong scaler object. Each scaler holds statistics for the columns it was fitted on. A scaler fitted on
Xcannot undo scaling ofy, and a scaler fitted on one column cannot invert a matrix with three columns. Keep one scaler per set of columns, and name them clearly (x_scaler,y_scaler). - Passing a 1D array.
inverse_transformexpects shape(n_samples, n_features). A model'spredictreturns shape(n_samples,), so reshape with.reshape(-1, 1)first. - Refitting before inverting. Calling
fitorfit_transformon new data replaces the stored statistics. Inverting afterward uses the new values and gives wrong results without raising an error. - Expecting clipped values to return. If you used
clip=TrueinMinMaxScaler, values outside the training range were cut to the range edges. The original values are lost, andinverse_transformreturns the clipped value.
Inverting inside a Pipeline
A Pipeline exposes inverse_transform only if every step supports it. A pipeline that ends in a classifier has no inverse_transform. To get back to original units for a feature matrix, pull out the scaler by name and use it directly.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pipe.fit(X, y)
scaler = pipe.named_steps["standardscaler"]
X_scaled = scaler.transform(X[:2])
print(scaler.inverse_transform(X_scaled)[:, :3])
print(X[:2, :3])Exercise
You fit MinMaxScaler() on a training column with minimum 10 and maximum 50. A model outputs the scaled value 0.25. What original value does inverse_transform return?
Show answer
0.25 * (50 - 10) + 10 = 20. The scaler multiplies by the range (40) and adds the minimum (10).
Exercise
A colleague scales y with a StandardScaler, trains a model, and calls y_scaler.inverse_transform(model.predict(X_test)). It raises a shape error. What is wrong, and how do you fix it?
Show answer
predict returns a 1D array, but inverse_transform needs 2D input. Use y_scaler.inverse_transform(model.predict(X_test).reshape(-1, 1)).ravel(), or use TransformedTargetRegressor to handle it automatically.