Sub topic 14
Correlated features and unstable coefficients
This chapter assumes you can fit a LinearRegression, read coef_, and split data with train_test_split. It also assumes basic NumPy and pandas. Here you will see why correlated features make coefficients unreliable even when predictions stay good, how to detect the problem, and what to do about it.
What multicollinearity is
Multicollinearity means two or more features carry overlapping information. The simplest case is two columns that are nearly copies of each other, such as height in centimeters and height in inches with a little measurement noise. A subtler case is one feature that is almost a linear combination of several others, such as total = a + b + c stored next to a, b and c.
Ordinary least squares (OLS) picks the coefficients that minimize squared error. When two features move together, many different coefficient pairs give almost the same error. The data cannot say which pair is right, so the solution becomes sensitive to small changes in the sample.
The consequences are specific:
- Predictions on data that resemble the training data stay accurate.
- Individual coefficients get large standard errors. They can swing in size and even flip sign between samples.
- Coefficients can become huge, with one large positive value cancelling a large negative one.
- The "holding other features fixed" reading of
coef_stops being meaningful, because in the real data the features never change independently.
Seeing the instability
The next script builds two nearly identical features. The true model uses only the first one. It then refits on 30 bootstrap resamples and reports how much the coefficients vary.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
n = 100
x1 = rng.normal(size=n)
x2 = x1 + rng.normal(scale=0.05, size=n) # almost a copy of x1
y = 3.0 * x1 + rng.normal(scale=1.0, size=n)
X = np.column_stack([x1, x2])
print("correlation:", np.corrcoef(x1, x2)[0, 1])
coefs = []
for _ in range(30):
idx = rng.integers(0, n, size=n) # bootstrap resample
m = LinearRegression().fit(X[idx], y[idx])
coefs.append(m.coef_)
coefs = np.array(coefs)
print("mean coef:", coefs.mean(axis=0))
print("std coef: ", coefs.std(axis=0))
print("mean of sum:", coefs.sum(axis=1).mean())
print("std of sum: ", coefs.sum(axis=1).std())Each individual coefficient has a large standard deviation. The sum of the two coefficients is much steadier and sits near 3. The data pins down the combined effect of the pair but cannot split it between the two columns.
Detecting it
Three checks are standard, from cheapest to most informative.
- Correlation matrix. Compute
df.corr()and look for off-diagonal values near 1 or -1. This catches pairs but misses a feature that is a combination of three or more others. - Variance inflation factor (VIF). For feature j, regress it on all the other features and take R² from that regression. Then VIF = 1 / (1 - R²). A VIF of 1 means no overlap. Common rules of thumb treat values above 5 or 10 as a concern.
- Condition number. A very large condition number of the feature matrix signals near-linear dependence.
The code below computes VIF with scikit-learn only, so you do not need statsmodels.
import numpy as np
from sklearn.linear_model import LinearRegression
def vif(X):
X = np.asarray(X, dtype=float)
out = []
for j in range(X.shape[1]):
others = np.delete(X, j, axis=1)
r2 = LinearRegression().fit(others, X[:, j]).score(others, X[:, j])
out.append(1.0 / (1.0 - r2))
return np.array(out)
rng = np.random.default_rng(0)
a = rng.normal(size=200)
b = a + rng.normal(scale=0.1, size=200)
c = rng.normal(size=200)
X = np.column_stack([a, b, c])
print("VIF:", vif(X))
print("condition number:", np.linalg.cond(X))The first two features get large VIFs, and the independent third feature stays close to 1.
Exact dependence
If one column is an exact linear combination of others, the problem is called perfect multicollinearity. A common cause is one-hot encoding every category and also keeping an intercept: the dummy columns sum to a column of ones. LinearRegression does not fail in this case. It uses a least-squares solver that returns the minimum-norm solution, so you get a valid fit with arbitrary-looking coefficients. Predictions are fine, but the coefficients are not individually meaningful. Dropping one category with OneHotEncoder(drop="first") removes this exact dependence for linear models.
Fixing it
There is no single correct fix. The right choice depends on whether you need interpretation or prediction.
| Approach | What it does | Best when | Cost |
|---|---|---|---|
| Drop one of the correlated features | Removes redundant information | You need interpretable coefficients and one feature is clearly redundant | Loses any signal unique to the dropped feature |
| Combine features | Average them or build a ratio or index | The features measure one underlying idea | Needs domain knowledge |
| Ridge regression | Shrinks coefficients and spreads weight across correlated features | You care about prediction and stable coefficients | Coefficients are biased toward zero |
| Lasso | Tends to keep one feature from a correlated group and zero the rest | You want a sparse model | The chosen feature can change between samples |
| ElasticNet | Mixes the L1 and L2 penalties | You have groups of correlated features and want some sparsity | Two hyperparameters to tune |
| PCA before regression | Replaces features with uncorrelated components | Prediction matters and interpretation does not | Components are hard to explain |
| Collect more varied data | Breaks the correlation in the sample | You control data collection | Often not possible |
Ridge as a stabilizer
Ridge adds a penalty alpha * sum(w²) to the loss. This makes the problem have one clear best answer even when columns are nearly duplicates, and it splits the shared effect across them. Features must be on the same scale first, because the penalty treats all coefficients equally. Use a pipeline with StandardScaler.
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 100
x1 = rng.normal(size=n)
x2 = x1 + rng.normal(scale=0.05, size=n)
y = 3.0 * x1 + rng.normal(scale=1.0, size=n)
X = np.column_stack([x1, x2])
models = {
"ols": LinearRegression(),
"ridge": make_pipeline(StandardScaler(), Ridge(alpha=10.0)),
}
for name, est in models.items():
coefs = []
for _ in range(30):
idx = rng.integers(0, n, size=n)
est.fit(X[idx], y[idx])
last = est[-1] if name == "ridge" else est
coefs.append(last.coef_)
coefs = np.array(coefs)
print(name, "std of each coef:", coefs.std(axis=0))The Ridge coefficients vary much less across resamples. Note that the Ridge coefficients are in standardized units, so compare their spread with care. The stability comes from the penalty, and the price is bias: the two coefficients each take roughly half of the shared effect, which is a reasonable answer when the features are interchangeable.
Common mistakes
- Reading a large coefficient as a strong effect without checking scale. Coefficients depend on units. Compare them only after standardizing, and only when features are not strongly correlated.
- Removing correlated features using the full dataset. Selecting features with correlations computed on all rows leaks test information. Do selection inside a pipeline or on the training split only.
- Treating a high VIF as an error. It is a diagnostic. If you only need predictions, a high VIF may not need action.
- Ignoring perfect dependence. Keep an eye on dummy variables, sums, and percentages that add to 100.
- Judging the fix by R² alone. A fix for interpretation, such as dropping a feature, may leave R² almost unchanged. Check coefficient stability across bootstrap resamples or cross-validation folds as well.
Decision guide
Start from the goal. If the goal is prediction, leave the features alone, use Ridge or ElasticNet, and choose alpha by cross-validation. If the goal is explanation, check VIF, merge or drop redundant features, refit, and confirm that coefficients stay steady across resamples. If features are correlated for reasons that matter, such as two real causes that rise together, accept that the data alone cannot separate their effects and say so.
Exercise
You fit OLS on two features with a correlation of 0.99. Test-set R² is high, but the two coefficients are +40 and -37 and change sharply when you refit on a different split. What is happening, and what are two reasonable responses depending on your goal?
Show answer
The features are nearly collinear, so many coefficient pairs fit almost equally well and OLS picks one that is driven by noise. The large opposite-signed values cancel each other, which is why predictions stay good. If you need prediction, use Ridge (or ElasticNet) in a pipeline with StandardScaler and tune alpha by cross-validation. If you need interpretation, drop or combine the redundant feature, then check that the remaining coefficient is stable across bootstrap resamples or folds.
Exercise
A feature has a VIF of 12. Name the regression that VIF is computed from, and say what R² value that VIF implies.
Show answer
VIF for a feature comes from regressing that feature on all the other features. VIF = 1 / (1 - R²), so a VIF of 12 means R² is 1 - 1/12, about 0.917. Roughly 92% of the feature's variance is explained by the other features.