Sub topic 7
Reading coef_ and intercept_
This chapter assumes you can fit a LinearRegression, split data, and use pandas DataFrames and NumPy arrays. After fitting, the model's learned numbers sit in two attributes. This chapter shows how to read them, and when a reading is misleading.
What the attributes hold
After fit, a LinearRegression stores its learned parameters in attributes that end in an underscore. This is the scikit-learn convention for values learned from data.
coef_is a NumPy array with one weight per input feature. For a single target its shape is(n_features,).intercept_is a single number, the prediction when every feature equals zero.
The model computes prediction = X @ coef_ + intercept_. Reading the model means reading those two objects against the units of your data.
A first reading
The data below has a known structure: price rises 1.5 per square metre and falls 0.8 per year of age.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
n = 300
df = pd.DataFrame({
"area_m2": rng.uniform(40, 160, n),
"age_years": rng.uniform(0, 50, n),
})
price = 1.5 * df["area_m2"] - 0.8 * df["age_years"] + 20 + rng.normal(0, 5, n)
model = LinearRegression().fit(df, price)
print(pd.Series(model.coef_, index=df.columns))
print("intercept:", model.intercept_)Wrapping coef_ in a pd.Series indexed by column name is the safest habit. coef_ is ordered by the columns you passed to fit, and the order is easy to lose track of. The estimate for area_m2 should come out close to 1.5, age_years close to -0.8, and the intercept near 20.
The units of a coefficient
A coefficient is measured in units of the target per unit of the feature.
area_m2 ≈ 1.5means one extra square metre goes with 1.5 more units of price.age_years ≈ -0.8means one extra year of age goes with 0.8 fewer units of price.
The phrase that matters is "holding the other features fixed". Each coefficient is a partial effect. It describes the change in prediction when only that feature moves. If you add or remove another feature, the same coefficient can change, because the model divides credit differently.
The intercept follows the same rule. Here it is the predicted price of a house with zero area and zero age, which is outside the data and has no physical meaning. An intercept is often just an anchor for the line. Do not interpret it unless zero is a realistic value for every feature.
Coefficients depend on scale
Because coefficients carry units, they cannot be compared across features. A weight of 0.002 for a feature measured in millimetres could be a larger effect than a weight of 5 for a feature measured in kilometres. Standardizing the features puts them on a common scale, so each coefficient means "change in target per one standard deviation of the feature".
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 300
df = pd.DataFrame({
"area_m2": rng.uniform(40, 160, n),
"age_years": rng.uniform(0, 50, n),
})
price = 1.5 * df["area_m2"] - 0.8 * df["age_years"] + 20 + rng.normal(0, 5, n)
raw = LinearRegression().fit(df, price)
pipe = make_pipeline(StandardScaler(), LinearRegression()).fit(df, price)
scaler, lin = pipe[0], pipe[-1]
print(pd.Series(lin.coef_, index=df.columns))
print("scaled intercept:", lin.intercept_, "mean of y:", price.mean())
coef_raw = lin.coef_ / scaler.scale_
intercept_raw = lin.intercept_ - np.sum(lin.coef_ * scaler.mean_ / scaler.scale_)
print(np.allclose(coef_raw, raw.coef_), np.isclose(intercept_raw, raw.intercept_))Three things to notice:
- The scaled coefficients are no longer 1.5 and -0.8. They are larger in magnitude, because one standard deviation of each feature spans many raw units. Their sizes can now be compared with each other.
- With centered features, the fitted intercept equals the mean of the target. This is a property of ordinary least squares, not a coincidence.
- The last line prints
True True. Dividing each scaled coefficient by the feature'sscale_recovers the raw coefficient, and the intercept is adjusted by the feature means. The two models make identical predictions, so the information is the same. Only the units differ.
Use raw coefficients when you want to say "per square metre". Use standardized coefficients when you want to rank features by influence.
Where interpretation breaks
| Situation | What goes wrong | What to do |
|---|---|---|
| Correlated features | Coefficients trade off against each other and can flip sign between samples | Check feature correlations. Consider Ridge or dropping a feature |
| Categorical features | One-hot columns are read relative to a baseline category | Use `drop="first"` or remember the baseline when reading them |
| Association vs cause | A coefficient describes the data, not what happens if you intervene | Say "associated with", not "causes" |
| Extrapolation | The line keeps going outside the range of training data | Report the feature ranges you trained on |
| Regularized models | Ridge and Lasso shrink coefficients toward zero on purpose | Do not read them as unbiased effect sizes |
Less common shapes and options
If you fit with a 2-D target, coef_ has shape (n_targets, n_features) and intercept_ becomes an array with one value per target.
LinearRegression(fit_intercept=False) sets intercept_ to 0.0 and forces the line through the origin. This is only appropriate if you have centered the data yourself or know the target is zero when every feature is zero. Otherwise the remaining coefficients are distorted to compensate.
Inside a Pipeline, you reach the fitted regressor with pipe[-1] or pipe.named_steps. If the preceding steps change the columns, as one-hot encoding does, label the coefficients with pipe[:-1].get_feature_names_out(). Mislabeled coefficients are the most common reading error in pipelines.
Checklist before you report a coefficient
- Label each value with its column name.
- State the units of the feature and the target.
- Say whether the features were scaled.
- Check for strongly correlated features.
- Confirm the model generalizes, using a held-out score, before explaining its parameters. Explaining a bad model gives you a confident story about nothing.
Exercise
A pipeline of StandardScaler and LinearRegression gives coef = [4.0, 0.5] for features "income" and "tenure". The scaler's scale is [2.0, 0.25]. What are the raw coefficients, and which feature has the larger effect per standard deviation versus per original unit?
Show answer
Raw coefficients are coef / scale, which gives [2.0, 2.0]. Per standard deviation, income has the larger effect (4.0 versus 0.5). Per original unit, the two effects are equal (2.0 each). The ranking depends on which units you use, so state the units when you compare.