Sub topic 7
Linear and logistic models
This chapter assumes you can build the preprocessing pipeline and the stratified cross-validation setup from the earlier chapters. It also assumes you know what a baseline is. Here you will see what linear and logistic models do, when they are the right choice, and the errors that most often cause trouble.
The working model
A linear model predicts from a weighted sum of the features: w1*x1 + w2*x2 + ... + b. Training finds the weights w and the intercept b.
- Linear regression returns the weighted sum as the prediction. It fits the weights by minimizing squared error.
- Logistic regression passes the weighted sum through a sigmoid function, which squeezes any number into the range 0 to 1. The result is a predicted probability for classification. Despite the name, it is a classifier.
Each weight is the effect of one feature while the others are held fixed. In logistic regression the weight is a change in log-odds, and exp(w) is an odds ratio. This makes the model easy to explain.
The model is linear in the features you give it. It cannot find an interaction or a curve unless you add one, for example with a product column or a binned feature.
Regularization
With many features, or features that are strongly correlated, the weights can grow large and fit noise. Regularization adds a penalty on weight size.
- L2 (ridge) shrinks all weights toward zero. This is the default in scikit-learn's
LogisticRegression. - L1 (lasso) can push some weights to exactly zero, which acts as feature selection.
In LogisticRegression, the parameter C is the inverse of the penalty strength. A smaller C means stronger regularization. Because the penalty depends on weight size, the features must be on comparable scales. This is why the pipeline from the preprocessing chapter includes StandardScaler.
Fitting and inspecting a model
This example reuses the setup from the baseline chapter. It fits the pipeline and reads the weights from the fitted steps.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, 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"]),
])
model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
model.fit(X, y)
names = model[0].get_feature_names_out()
weights = model[-1].coef_[0]
for name, w in sorted(zip(names, weights), key=lambda t: -abs(t[1])):
print(f"{name:12s} {w:+.2f}")In this data the label depends on an XOR of age and city. That is an interaction, so the linear model cannot capture it well. A tree-based model can, and you will see that in later chapters. A linear model scoring close to the baseline is useful evidence that the signal is not additive.
Common errors
- Skipping scaling. Unscaled features make regularization unfair and can stop the solver from converging. Keep the scaler inside the pipeline.
- Reading weights as importance when features are correlated. Correlated columns split or swap weight between them. Compare weights only when the features share a scale and are not strongly collinear.
- Integer codes for categories. Coding
cityas 0, 1, 2 tells the model that c is twice b. Use one-hot encoding. - Ignoring the convergence warning. If scikit-learn warns that the solver did not converge, raise
max_iteror scale the inputs. - Using 0.5 as a fixed threshold. The model outputs probabilities. Choose the threshold from your metric and costs.
When to choose a linear model
| Situation | Linear model fit |
|---|---|
| Effects are roughly additive | Strong |
| You need explainable weights | Strong |
| Many sparse or high-dimensional columns | Strong, with L1 or L2 |
| Strong interactions or thresholds | Weak unless you engineer features |
| Very small dataset | Good, because it has low variance |
Exercise
A logistic regression scores a cross-validated ROC AUC of 0.52, close to the dummy baseline. A random forest on the same folds scores 0.90. What does the gap suggest, and what is one way to help the linear model?
Show answer
The relationship is not additive in the given features, for example an interaction or a threshold effect, which the forest can find and the linear model cannot. You can add engineered features such as products of columns or binned values, then re-score the pipeline on the same folds.
Exercise
You make the penalty weaker in LogisticRegression. Do you raise or lower C, and why?
Show answer
Raise C. It is the inverse of the regularization strength, so a larger value means a weaker penalty and larger weights are allowed.