Sub topic 11
Edge cases: constant columns, sparse matrices and clipping
This chapter assumes you know how StandardScaler and MinMaxScaler work, including fit, transform and the rule that you fit on training data only. It covers three situations where the simple formulas stop being enough:
- A column has no spread.
- The data is a sparse matrix.
- New data falls outside the range you learned.
Each one has a specific, predictable behavior in scikit-learn. Knowing that behavior keeps you from shipping silent bugs.
Constant columns: dividing by zero
Both scalers divide by a spread. StandardScaler divides by the standard deviation, and MinMaxScaler divides by max - min. A constant column has a spread of zero, so a literal implementation would produce NaN or inf.
scikit-learn avoids this. When it detects a zero spread, it replaces the divisor with 1. The column is then only shifted, not stretched. You can see this in the learned attributes.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[1.0, 5.0],
[2.0, 5.0],
[3.0, 5.0]]) # second column is constant
std_scaler = StandardScaler().fit(X)
mm_scaler = MinMaxScaler().fit(X)
print(std_scaler.scale_) # second entry is 1.0, not 0.0
print(mm_scaler.scale_) # second entry is 1.0 as well
X_new = np.array([[2.0, 7.0]])
print(std_scaler.transform(X_new))
print(mm_scaler.transform(X_new))On the training data, the constant column becomes all zeros under both scalers. With StandardScaler that is the centered value. With MinMaxScaler it is the lower end of feature_range.
The new row shows the catch. The constant column was 5 during training, but the new row has 7. Because the divisor is 1, the scaled value is 7 - 5 = 2.0 under both scalers. That value is neither a z-score nor a number inside [0, 1]. The scaler does not warn you.
What to do about constant columns
A constant column carries no information for most models, so removing it is often the cleanest choice. VarianceThreshold drops columns whose variance is at or below a threshold. With the default threshold of 0, it drops only exactly constant columns.
import numpy as np
from sklearn.feature_selection import VarianceThreshold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 5.0],
[2.0, 5.0],
[3.0, 5.0]])
prep = make_pipeline(VarianceThreshold(threshold=0.0), StandardScaler())
print(prep.fit_transform(X).shape) # (3, 1): the constant column is gonePlace the selector before the scaler and inside the pipeline. The decision to drop a column is then learned from training data only, like every other statistic.
Near-constant columns
A column can be constant in exact arithmetic but not in floating point. For example, a column of the same value computed by a long sum can have a standard deviation around 1e-17. Dividing by that would blow up rounding noise into values of order 1. Recent versions of scikit-learn treat a spread that is negligible relative to the column's magnitude as zero. Older versions do not.
If you support several scikit-learn versions, or your columns come from computed values, check the learned scale_ after fitting. Treat any very small value as a signal to investigate.
import numpy as np
from sklearn.preprocessing import StandardScaler
def tiny_scales(scaler: StandardScaler, limit: float = 1e-8) -> np.ndarray:
"""Return indices of columns whose learned scale is suspiciously small."""
return np.flatnonzero(scaler.scale_ < limit)A scale of exactly 1.0 does not mean the column was healthy. It may be the replacement value for a zero spread. A fitted scaler cannot tell you that on its own, so compare against var_ for StandardScaler. A column with var_ == 0 was constant.
Missing values
Both scalers ignore NaN when computing statistics during fit and keep NaN in the output of transform. This is convenient, but it means a column with a single non-missing value is effectively constant. It follows the same zero-spread rule. Impute missing values after scaling only if your model needs it. Otherwise impute first, inside the same pipeline.
Sparse matrices: centering destroys sparsity
A sparse matrix stores only its nonzero entries. This is how bag-of-words counts or one-hot encodings stay small. Subtracting a column mean from every entry turns nearly every zero into a nonzero number. The matrix becomes dense, and memory use can jump by orders of magnitude.
scikit-learn therefore treats the two scalers differently for sparse input.
| Scaler | Sparse input | Behavior |
|---|---|---|
| `StandardScaler()` | Raises `ValueError` | Default `with_mean=True` would densify the data |
| `StandardScaler(with_mean=False)` | Works | Divides by the standard deviation and keeps zeros as zeros |
| `MinMaxScaler()` | Raises `TypeError` | Shifting by the minimum would also densify the data |
| `MaxAbsScaler()` | Works | Divides by the largest absolute value, range `[-1, 1]` |
The following script exercises all four rows.
import numpy as np
from scipy import sparse
from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler
X = sparse.csr_matrix(np.array([[0.0, 10.0],
[0.0, 0.0],
[3.0, 0.0],
[0.0, 2.0]]))
try:
StandardScaler().fit(X)
except ValueError as err:
print("StandardScaler default:", type(err).__name__)
try:
MinMaxScaler().fit(X)
except TypeError as err:
print("MinMaxScaler:", type(err).__name__)
scaled = StandardScaler(with_mean=False).fit_transform(X)
print(sparse.issparse(scaled), scaled.nnz == X.nnz)
maxabs = MaxAbsScaler().fit_transform(X)
print(sparse.issparse(maxabs))
print(maxabs.toarray())The last two checks of StandardScaler(with_mean=False) confirm that the output is still sparse and has the same number of stored entries. Scaling by a constant never turns a zero into a nonzero.
What `with_mean=False` gives up
Without centering, the result does not have mean 0. It has unit variance (the divisor is the standard deviation), but its mean is whatever the data's mean divided by the standard deviation happens to be. For linear models with an intercept and for distance-based methods on sparse text features, this is usually acceptable. Be aware that models which assume centered inputs, such as PCA, will behave differently. PCA itself rejects sparse input, and TruncatedSVD is the usual sparse substitute.
Choosing for sparse data
- Use
MaxAbsScalerwhen you want bounded features and exact zeros preserved. It is the sparse counterpart to min-max scaling. - Use
StandardScaler(with_mean=False)when you want comparable variances across columns, for example before an L2-regularized linear model. - Convert to dense with
.toarray()only when the matrix is small enough that memory is not a concern. Then any scaler is allowed.
Clipping: when new data leaves the learned range
Min-max scaling learns data_min_ and data_max_ from the training set. Test or production data can fall outside that interval, and the transform does not prevent it. A value above the training maximum maps to a number above 1. A value below the training minimum maps to a number below 0.
This is correct arithmetic, and it is often the right answer, because it preserves information. But some consumers expect a hard bound:
- Neural network inputs with a bounded activation.
- Image-like data that must stay in
[0, 1]. - Pipelines where a single extreme value should not dominate.
MinMaxScaler has a clip parameter for this. When clip=True, transformed values are cut to feature_range.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X_train = np.array([[0.0], [5.0], [10.0]])
X_new = np.array([[-5.0], [15.0]])
plain = MinMaxScaler().fit(X_train)
clipped = MinMaxScaler(clip=True).fit(X_train)
print(plain.transform(X_new).ravel()) # -0.5 and 1.5
print(clipped.transform(X_new).ravel()) # 0.0 and 1.0
back = clipped.inverse_transform(clipped.transform(X_new))
print(back.ravel()) # 0.0 and 10.0, not -5.0 and 15.0The last two lines show the cost. Clipping is lossy, so inverse_transform cannot recover the original out-of-range values. Keep the unscaled data if you need it later.
Clipping applies only at transform time. It does not change what the scaler learns during fit. Clipping does not remove outliers from the training data. If an extreme training value stretches data_max_, the ordinary values are still compressed, as the outlier chapter showed.
Clipping with StandardScaler
StandardScaler has no clip parameter, because z-scores have no natural bound. If you want to limit extremes, clip the output yourself. A bound such as 5 standard deviations is a common choice. Wrap it in FunctionTransformer so the step can live in a pipeline.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
rng = np.random.default_rng(0)
X_train = rng.normal(size=(200, 2))
X_new = np.array([[0.0, 12.0]]) # second feature is far outside the training spread
pipe = make_pipeline(
StandardScaler(),
FunctionTransformer(np.clip, kw_args={"a_min": -5.0, "a_max": 5.0}),
)
pipe.fit(X_train)
print(pipe.transform(X_new)) # the second value is capped at 5.0The clip bounds are fixed constants, not learned from data, so this step introduces no leakage.
Choosing a response
The right handling depends on what you want the model to see. This diagram summarizes the decisions in this chapter.
Common mistakes
- Trusting a scale of 1.0. It can mean a real standard deviation of 1 or the replacement for zero. Check
var_or the raw column. - Densifying by accident. Calling
.toarray()to get past the sparse error works on small data and runs out of memory on large data. Usewith_mean=FalseorMaxAbsScalerinstead. - Clipping before fitting.
clip=Trueleaves the learned minimum and maximum unchanged. If you want training outliers to stop stretching the range, winsorize the training data first, or useRobustScaler. - Expecting a round trip. After clipping,
inverse_transformreturns the clipped values, not the originals. - Dropping columns outside the pipeline. Removing constant columns by hand on the full dataset uses test data to make a decision. Put
VarianceThresholdinside the pipeline.
Summary
A constant column is scaled with a divisor of 1, so training values become 0 and new values are only shifted. Drop such columns inside the pipeline. Sparse input rules out centering, which means StandardScaler(with_mean=False) or MaxAbsScaler, and rules out MinMaxScaler entirely. Out-of-range values map outside [0, 1] unless you set clip=True on MinMaxScaler or clip z-scores yourself, at the price of losing the ability to invert the transform.
Exercise
A training column is constant at 4.0. You fit StandardScaler on it, then transform a new row where the same column is 6.5. What value comes out, and why?
Show answer
The output is 2.5. The standard deviation is zero, so scikit-learn replaces the divisor with 1. The transform then computes (6.5 - 4.0) / 1 = 2.5. It is not a true z-score, and no warning is raised.
Exercise
You have a sparse TF-IDF matrix and want every feature in the range [-1, 1] without losing sparsity. Which scaler do you use, and why can't you use MinMaxScaler?
Show answer
Use MaxAbsScaler. It divides each column by its largest absolute value, which keeps zeros as zeros and bounds values to [-1, 1]. MinMaxScaler subtracts the column minimum, which would make the zero entries nonzero, so it refuses sparse input and raises a TypeError.
Exercise
You fit MinMaxScaler(clip=True) on training values 0, 5 and 10. A new value of 15 is scaled, and then you call inverse_transform on the result. What do you get back, and what does this tell you about clipping?
Show answer
The scaled value is 1.0 (clipped from 1.5), and inverse_transform returns 10.0, not 15. Clipping discards information, so the original out-of-range value cannot be recovered.