Sub topic 9
Undoing scaling with inverse_transform
This chapter assumes you can fit and apply StandardScaler and MinMaxScaler with fit, transform and fit_transform. It also assumes you know the formulas behind both scalers and why you fit only on training data. Here you learn how inverse_transform maps scaled values back to original units, where that matters, and where it silently gives you the wrong answer.
What inverse_transform does
A fitted scaler stores the numbers it needs to scale new data. StandardScaler stores mean_ and scale_, which is the standard deviation. MinMaxScaler stores data_min_, data_max_, data_range_, scale_ and min_. The inverse_transform method applies the scaling formula backwards using these stored values. It does not look at the data it receives to compute anything new.
| Scaler | Forward (`transform`) | Backward (`inverse_transform`) |
|---|---|---|
| `StandardScaler` | `z = (x - mean_) / scale_` | `x = z * scale_ + mean_` |
| `MinMaxScaler` (range 0 to 1) | `m = (x - data_min_) / (data_max_ - data_min_)` | `x = m * (data_max_ - data_min_) + data_min_` |
Internally, MinMaxScaler computes x * scale_ + min_ going forward, where scale_ = 1 / data_range_ and min_ = -data_min_ * scale_ for the default range. The inverse is (m - min_) / scale_. This is the same arithmetic written differently.
A round trip by hand and with the API
The next example runs the inverse formulas manually and compares them with inverse_transform.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[10.0, 1.0],
[20.0, 5.0],
[30.0, 9.0]])
std = StandardScaler().fit(X)
Z = std.transform(X)
manual_X = Z * std.scale_ + std.mean_
print(np.allclose(manual_X, std.inverse_transform(Z))) # True
print(np.allclose(manual_X, X)) # True
mm = MinMaxScaler().fit(X)
M = mm.transform(X)
manual_X = M * mm.data_range_ + mm.data_min_
print(np.allclose(manual_X, mm.inverse_transform(M))) # True
print(np.allclose(manual_X, X)) # TrueAlways compare with np.allclose, not ==. Floating-point arithmetic can leave differences around 1e-16, so a round trip is correct to rounding error but not always bit-for-bit identical.
The inverse also works on values the scaler never saw. Both scalers are linear, so inverse_transform accepts any numbers of the right shape. It does not check that they came from transform, and it does not limit them to the fitted range. This matters when the numbers are model outputs, as in the next sections.
Why you need it
The inverse is useful in four situations:
- Reading predictions when you scaled the target.
- Reporting error metrics in original units.
- Interpreting what a model learned, such as cluster centers or coefficients.
- Inspecting or plotting scaled data in terms people understand.
Scaling the target and recovering predictions
You usually scale features, not the target. Some models train better with a scaled target, such as neural networks or models trained by gradient descent with a regularization penalty. When you scale the target, the model predicts in scaled units, and you must invert those predictions before you report them.
The target scaler needs 2D input, so reshape a 1D target into one column. This is the most common source of shape errors with inverse_transform.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = make_regression(n_samples=200, n_features=3, noise=10, random_state=0)
y = y * 50 + 1000 # move the target to a large, offset scale
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
x_scaler = StandardScaler().fit(X_train)
y_scaler = StandardScaler().fit(y_train.reshape(-1, 1))
y_train_s = y_scaler.transform(y_train.reshape(-1, 1)).ravel()
model = LinearRegression().fit(x_scaler.transform(X_train), y_train_s)
pred_scaled = model.predict(x_scaler.transform(X_test))
pred = y_scaler.inverse_transform(pred_scaled.reshape(-1, 1)).ravel()
print(pred[:3])
print(y_test[:3])Only y_scaler can undo the target scaling. x_scaler was fitted on three columns and learned nothing about the target, so passing predictions through it raises an error or gives meaningless numbers.
Letting scikit-learn do it with TransformedTargetRegressor
Doing the reshape-and-invert steps by hand is easy to get wrong. TransformedTargetRegressor wraps a regressor, scales the target during fit, and inverts the prediction during predict.
import numpy as np
from sklearn.compose import TransformedTargetRegressor
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_regression(n_samples=200, n_features=3, noise=10, random_state=0)
y = y * 50 + 1000
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = TransformedTargetRegressor(
regressor=make_pipeline(StandardScaler(), LinearRegression()),
transformer=StandardScaler(),
)
model.fit(X_train, y_train)
pred = model.predict(X_test) # already in original units
print(pred[:3])
print(model.regressor_.named_steps["linearregression"].coef_)The fitted target scaler lives in model.transformer_. During cross-validation, the wrapper refits both the feature scaler and the target scaler on each training fold, so no information leaks from the validation folds. A hand-written version has to refit the target scaler inside every fold yourself.
Reporting errors in original units
Mean squared error on a scaled target is hard to interpret. An RMSE of 0.35 tells a stakeholder nothing. Invert the predictions, or use TransformedTargetRegressor, and then compute the metric against the original y_test. An RMSE of 17.4 dollars means something. Never compute a metric by mixing scaled predictions with unscaled truth.
Interpreting cluster centers
Distance-based models such as k-means need scaled features, but their fitted parameters live in scaled space. To describe each cluster in real units, invert the centers.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
low = rng.normal(loc=[25, 30000], scale=[3, 2000], size=(50, 2))
high = rng.normal(loc=[55, 90000], scale=[3, 2000], size=(50, 2))
X = np.vstack([low, high]) # columns: age, income
scaler = StandardScaler().fit(X)
km = KMeans(n_clusters=2, n_init=10, random_state=0)
km.fit(scaler.transform(X))
centers = scaler.inverse_transform(km.cluster_centers_)
print(centers) # one row per cluster: roughly [age, income]The centers come out near ages 25 and 55 and incomes near 30,000 and 90,000. In scaled space they would be small numbers around -1 and +1.
Converting coefficients back to original units
A linear model trained on standardized features has coefficients in units of "change in target per one standard deviation of the feature". These coefficients are comparable across features, which is a reason to standardize. To get coefficients per original unit, divide by scale_. The intercept needs a correction for the shift by mean_.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
X, y = make_regression(n_samples=200, n_features=3, noise=5, random_state=1)
X = X * [1, 10, 100] + [0, 50, 500] # put features on different scales
scaler = StandardScaler().fit(X)
scaled_model = LinearRegression().fit(scaler.transform(X), y)
coef_orig = scaled_model.coef_ / scaler.scale_
intercept_orig = scaled_model.intercept_ - np.sum(
scaled_model.coef_ * scaler.mean_ / scaler.scale_
)
raw_model = LinearRegression().fit(X, y)
print(np.allclose(coef_orig, raw_model.coef_)) # True
print(np.allclose(intercept_orig, raw_model.intercept_)) # TrueThis conversion is exact for ordinary least squares because the scaling is an invertible linear change of variables. It does not hold for regularized models such as Ridge or Lasso. Those models penalize the coefficients, so fitting in scaled space gives a different solution from fitting in original units, not just rescaled coefficients. The converted coefficients still describe the scaled-space model correctly in original units, but they are not what you would get by fitting on raw data.
Inverting a chain of steps
Pipeline.inverse_transform applies each step's inverse in reverse order. It is available when every step before the final estimator supports inversion, and a pipeline that ends in a scaler works directly.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
pipe = make_pipeline(StandardScaler(), MinMaxScaler())
X_out = pipe.fit_transform(X)
X_back = pipe.inverse_transform(X_out)
print(np.allclose(X, X_back)) # TrueTwo limits apply here:
ColumnTransformerdoes not provideinverse_transform. If you scale some columns with one scaler and others with another, invert each fitted scaler yourself, usingfitted_transformer.named_transformers_.- A pipeline that ends in a classifier or regressor cannot be inverted as a whole, because the model is not an invertible transformation. Invert only the scaling steps.
When the round trip is not exact
inverse_transform recovers the original input only when transform lost no information. Several cases break this.
Clipping is lossy
MinMaxScaler(clip=True) forces transformed values into the feature range. A test value outside the training range gets clamped, and the clamp cannot be undone.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[0.0], [10.0]])
new = np.array([[15.0]])
plain = MinMaxScaler().fit(train)
clipped = MinMaxScaler(clip=True).fit(train)
print(plain.transform(new)) # [[1.5]]
print(plain.inverse_transform(plain.transform(new))) # [[15.]]
print(clipped.transform(new)) # [[1.]]
print(clipped.inverse_transform(clipped.transform(new))) # [[10.]]With clip=True the value 15 comes back as 10. Use clipping to protect a model from out-of-range inputs, not when you need to recover the inputs afterward. Keep the raw data if you need it.
Constant columns
A column with zero variance has no meaningful scale. StandardScaler handles this by setting scale_ to 1 for that column. transform then gives 0 for every row, and inverse_transform of 0 returns the column's mean, which is the constant. The round trip works, but any value you pass in for that column is shifted by the mean without being stretched. MinMaxScaler treats a zero range the same way.
Wrong shape or wrong column count
The inverse expects the same number of columns that the scaler was fitted on, in the same order. Passing a different number raises a ValueError about the number of features. This often appears when you fitted a scaler on a whole feature matrix and then try to invert a single column of predictions. A scaler fitted on several columns can only invert arrays with that many columns. Fit a separate scaler on the target, or on that single column, when you want to invert one column alone.
Mixing up fitted scalers
Each scaler has its own statistics. Inverting with a scaler that was fitted on different data, such as test data, produces plausible-looking wrong numbers. There is no error, because every set of statistics gives a valid linear map. Name your scalers by the data they describe, such as x_scaler and y_scaler, and keep one fitted scaler per transformation.
Sparse input
StandardScaler(with_mean=False) works on sparse matrices because it does not center, and inverse_transform accepts sparse input in that mode. Centering a sparse matrix would make it dense, so scikit-learn refuses it.
Quick checks before you trust an inverse
- Confirm that a round trip on the training data returns the original data with
np.allclose. - Confirm that the scaler you invert with is the one that was fitted for that array.
- Confirm that the array has the same number of columns as at fit time, and is 2D.
- Check that no clipping or other lossy step sits between the scaling and the inversion.
- Compute metrics only after inverting, comparing predictions and truth in the same units.
Exercise
You fit y_scaler = StandardScaler().fit(y_train.reshape(-1, 1)) and train a model on the scaled target. The model predicts [0.5, -1.0] on test rows. y_scaler.mean_ is [200.0] and y_scaler.scale_ is [40.0]. What are the predictions in original units, and which line of code produces them?
Show answer
Use x = z scale + mean. The first value is 0.5 40 + 200 = 220. The second is -1.0 * 40 + 200 = 160. In code: y_scaler.inverse_transform(np.array([[0.5], [-1.0]])), which returns [[220.], [160.]]. The input must be 2D with one column.
Exercise
A MinMaxScaler(clip=True) is fitted on training values ranging from 0 to 10. A new value of 15 is transformed and then inverted. What value do you get back, and why does it differ from a scaler with clip=False?
Show answer
You get 10. With clip=True, transform clamps the scaled value 1.5 to 1.0, and inverse_transform of 1.0 is the training maximum of 10. The clamp discards the information that the input was 15. With clip=False, the scaled value is 1.5 and the inverse returns 15.
Exercise
A linear regression is fitted on standardized features. One feature has scale_ = 20.0, and its coefficient in the scaled model is 3.0. What is the coefficient for that feature in original units? Does the same conversion give the raw-data solution for a Ridge model?
Show answer
Divide the coefficient by the scale: 3.0 / 20.0 = 0.15 target units per original unit of the feature. For ordinary least squares this matches the model fitted on raw data. For Ridge it does not match, because the penalty acts on the coefficients in scaled space, so fitting on scaled and raw data are different problems. The conversion still describes the scaled-space model in original units.