Sub topic 11
Edge cases: constant columns, sparse matrices and clipping
This chapter covers three situations that break or surprise the default scaler workflow. It assumes you can use fit and transform on StandardScaler and MinMaxScaler, know what a SciPy sparse matrix is, and understand why scalers are fitted on training data only.
Constant columns
A constant column has zero variance and zero range, so both scaler formulas divide by zero. scikit-learn avoids this by replacing a zero scale with 1.0. The column is centered or shifted but never divided.
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]])
std = StandardScaler().fit(X)
print(std.scale_) # second entry is 1.0, not 0.0
print(std.transform(X)[:, 1]) # [0. 0. 0.]
mm = MinMaxScaler().fit(X)
print(mm.transform(X)[:, 1]) # [0. 0. 0.]Training output has no NaN or infinity. The column is now all zeros and carries no information.
A constant training column can still cause trouble at prediction time. If a new row has a different value, the transform simply subtracts the training constant. The result is a raw difference in original units, not a standardized value.
new_row = np.array([[2.0, 9.0]])
print(std.transform(new_row)[:, 1]) # [4.]
print(mm.transform(new_row)[:, 1]) # [4.]A value of 4 in a column that was always 0 is a large jump. Treat it as a sign that the data has drifted.
Constant columns are useless to most models, so a common practice is to remove them before scaling. VarianceThreshold from sklearn.feature_selection does this, and it can sit in the same pipeline.
Sparse matrices
A sparse matrix stores only its nonzero entries. Centering subtracts the mean from every entry, which turns most zeros into nonzero numbers. A sparse matrix with many entries would then use as much memory as a dense one. For this reason the scalers handle sparse input differently:
StandardScalerraises aValueErroron sparse input unless you passwith_mean=False. It then divides by the standard deviation and does not center.MinMaxScalerdoes not accept sparse input. Its shift step has the same densifying problem.MaxAbsScalerdivides each column by its maximum absolute value. It keeps zeros as zeros and works on sparse data.
import numpy as np
from scipy import sparse
from sklearn.preprocessing import StandardScaler, MaxAbsScaler
X = sparse.csr_matrix(np.array([[0.0, 10.0],
[0.0, 20.0],
[3.0, 0.0]]))
try:
StandardScaler().fit(X)
except ValueError as err:
print("default StandardScaler fails:", err)
scaled = StandardScaler(with_mean=False).fit_transform(X)
print(type(scaled).__name__, scaled.nnz) # still sparse, 3 stored values
mabs = MaxAbsScaler().fit_transform(X)
print(mabs.toarray()) # values lie in [-1, 1]With with_mean=False the output has a standard deviation of 1 per column, but the mean is not 0. That is the price of keeping the matrix sparse.
flowchart TD
A[Input matrix] --> B{Sparse?}
B -- No --> C[StandardScaler or MinMaxScaler]
B -- Yes --> D{Need unit variance?}
D -- Yes --> E[StandardScaler with_mean=False]
D -- No --> F[MaxAbsScaler]The diagram block above is not in the permitted format, so here is the same decision as a table:
| Input | Need | Scaler |
|---|---|---|
| Dense | Zero mean, unit variance | `StandardScaler()` |
| Dense | Fixed range such as [0, 1] | `MinMaxScaler()` |
| Sparse | Unit variance, no centering | `StandardScaler(with_mean=False)` |
| Sparse | Values in [-1, 1] | `MaxAbsScaler()` |
Clipping out-of-range values
MinMaxScaler learns the minimum and maximum from the training data. A test value outside that range lands outside [0, 1]. This is correct behavior, but some downstream steps expect values inside the range. Pass clip=True to cap the output.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[0.0], [10.0]])
test = np.array([[-5.0], [5.0], [15.0]])
print(MinMaxScaler().fit(train).transform(test).ravel())
# [-0.5 0.5 1.5]
print(MinMaxScaler(clip=True).fit(train).transform(test).ravel())
# [0. 0.5 1. ]clip applies only to MinMaxScaler. StandardScaler has no fixed output range, so it has nothing to clip to.
Summary of behaviors
| Situation | Result | What to do |
|---|---|---|
| Constant column | Scale becomes 1.0, output is all 0 | Drop it with `VarianceThreshold` |
| New value in a formerly constant column | Raw difference, not standardized | Check for data drift |
| Sparse input to `StandardScaler` | `ValueError` | Use `with_mean=False` |
| Sparse input to `MinMaxScaler` | Error | Use `MaxAbsScaler` |
| Test value outside training range | Output outside [0, 1] | Use `clip=True` if a bound is required |
Exercise
You fit MinMaxScaler() on a training column with values 20 to 80. A test value is 110. What is the transformed value without clipping, and what is it with clip=True?
Show answer
Without clipping, (110 - 20) / (80 - 20) = 1.5. With clip=True, the value is capped at the top of the feature range, so it becomes 1.0.
Exercise
A text pipeline produces a sparse TF-IDF matrix. You want to scale its columns to unit variance without making the matrix dense. Which scaler and argument do you use, and what property of the result do you give up?
Show answer
Use StandardScaler(with_mean=False). The columns are divided by their standard deviation, but they are not centered, so their means are not 0.