Sub topic 7
Linear and logistic models
This chapter assumes you can build a scikit-learn Pipeline with a ColumnTransformer and run stratified cross-validation, as covered in the preprocessing and validation chapters. It also assumes you have a baseline score to compare against.
Why a linear model comes right after the baseline
A dummy baseline tells you what a model with no information achieves. A linear model tells you how much of the signal can be captured by a weighted sum of the features. That second number is useful for three reasons:
- It is cheap to fit and has few settings to tune.
- Its behavior is easy to inspect, because each feature gets one coefficient.
- It sets the bar that more complex models must clear to justify their cost.
On small datasets, or on data with many sparse columns such as one-hot encoded categories, a regularized linear model often matches tree ensembles. Treat it as a serious candidate and not only as a stepping stone.
The working model
Linear regression predicts a number as a weighted sum of the features:
y_hat = b0 + b1*x1 + b2*x2 + ... + bk*xk
Logistic regression is a classifier built on the same weighted sum. The sum is called the log-odds, or logit. The model passes it through the sigmoid function to get a probability:
p = 1 / (1 + exp(-(b0 + b1*x1 + ... + bk*xk)))
Training picks the coefficients that minimize a loss. For regression the loss is squared error. For logistic regression it is log loss, the same quantity you meet as a metric. Both models also add a penalty on the size of the coefficients. This is regularization.
| Penalty | scikit-learn estimators | Effect |
|---|---|---|
| L2 (ridge) | `Ridge`, `LogisticRegression` (default) | Shrinks all coefficients toward zero. Handles correlated features well. |
| L1 (lasso) | `Lasso`, `LogisticRegression(penalty="l1", solver="liblinear")` | Sets some coefficients exactly to zero, which acts as feature selection. |
| Elastic net | `ElasticNet`, `LogisticRegression(penalty="elasticnet", solver="saga", l1_ratio=...)` | Mixes both penalties. |
LogisticRegression uses C, the inverse of the regularization strength. A small C means strong regularization. Ridge and Lasso use alpha, where a large value means strong regularization. This mismatch is a common source of confusion when you tune both families.
Scaling is part of the model
The penalty is applied to raw coefficient sizes. A feature measured in dollars needs a tiny coefficient and a feature measured in years needs a larger one, so the penalty treats them unequally. Standardize numeric features before fitting a regularized linear model. Do it inside the pipeline so the mean and standard deviation come from the training fold only. Unscaled features also slow the solver and can trigger convergence warnings.
Example: a linear model that misses an interaction
The target in this synthetic table depends on age and city together. A plain logistic regression adds up the effects of each feature separately, so it cannot represent that dependence. Adding pairwise interaction terms fixes this.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"baseline": make_pipeline(preprocess, DummyClassifier(strategy="prior")),
"logreg": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
"logreg_interactions": make_pipeline(
preprocess,
PolynomialFeatures(degree=2, interaction_only=True, include_bias=False),
LogisticRegression(max_iter=1000),
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")Expect the baseline at 0.5 ROC AUC, because it ranks every row the same. Expect the plain logistic regression to sit close to chance. The interaction model should score far higher, because the product of age and the city "a" indicator gives the model a different age slope in each city.
The lesson is about diagnosis. A linear model scoring near a baseline does not mean the data has no signal. It may mean the signal is not additive. A tree ensemble finds such interactions automatically, which is part of why trees are strong on tabular data.
Reading coefficients
You can inspect a fitted model by pairing the coefficients with the names of the transformed features:
model = models["logreg"].fit(X, y)
names = model[:-1].get_feature_names_out()
coefs = model[-1].coef_[0]
report = pd.DataFrame({"feature": names, "coef": coefs, "odds_ratio": np.exp(coefs)})
print(report.sort_values("coef", key=abs, ascending=False).to_string(index=False))How to read the table:
- A coefficient is the change in log-odds for a one-unit increase in that feature, with the other features held fixed.
exp(coef)is the odds ratio. A value of 1.3 means the odds of the positive class are multiplied by 1.3.- After
StandardScaler, one unit is one standard deviation. Coefficient sizes are then roughly comparable across numeric features.
Where linear models fail and what to do
| Symptom | Cause | Common fix |
|---|---|---|
| Score near the baseline | Interactions or non-linear effects | Add interaction terms, splines (`SplineTransformer`), or try trees |
| Convergence warning | Unscaled features or too few iterations | Scale numeric features, raise `max_iter` |
| Poor regression fit on a skewed target | Squared error dominated by large values | Wrap with `TransformedTargetRegressor` using a log transform |
| Unstable coefficients | Correlated features | Increase L2 strength, drop redundant columns |
| Large gap between train and CV score | Too many features for the rows, weak regularization | Lower `C` (or raise `alpha`), use L1 |
| Probabilities look off after `class_weight="balanced"` | Reweighting shifts predicted probabilities | Use it for ranking, or recalibrate before using probabilities |
Common errors
- Fitting the scaler or imputer outside the pipeline. This leaks fold statistics into training and inflates scores slightly. Keep all preprocessing in the pipeline, as the validation chapter requires.
- Tuning
Con the test fold. Choose it with an inner search and report the outer score only. The tuning chapter covers this. - Using
penalty=Nonewith all one-hot columns. The columns for a category sum to one, which duplicates the intercept and makes the coefficients non-unique. With the default L2 penalty this is harmless. Without a penalty, setdrop="first"in the encoder. - Treating one-hot columns as ordered numbers. Encoding cities as 0, 1, 2 forces the model to assume that city 2 is twice city 1. Use one-hot encoding for nominal categories.
- Reading accuracy at the 0.5 threshold on imbalanced data. The linear model may be ranking well while the default threshold is poor. Check ROC AUC or average precision, and choose the threshold separately.
Choosing between the linear variants
What to carry forward
Run the linear model on the same folds and the same metric as every other candidate. Record its mean and spread. Then use it as a diagnostic: if interactions or non-linear terms close the gap to tree ensembles, you have learned something about the structure of your data.
Exercise
A colleague fits LogisticRegression on a table with an income column (values in the tens of thousands) and an age column (values from 18 to 80), without scaling. Training raises a convergence warning, and the coefficients for the two columns differ by a factor of about 1000. They then lower C to regularize more. Explain why the unscaled setup is problematic for a regularized model, and what to change.
Show answer
The L2 penalty acts on raw coefficient sizes. Income needs a very small coefficient to have the same effect as age, so the penalty barely restricts income but restricts age heavily, which makes the regularization uneven. Differences in feature scale also make the optimization poorly conditioned, which causes the convergence warning. Add a StandardScaler (after imputation) inside the pipeline so the statistics are learned per training fold. Then tune C with cross-validation, and raise max_iter only if the warning persists.