Linear and logistic models as predictors
A weighted sum is a strong baseline you can read. See when it matches boosting, when it can't, and how new features let it draw curves.
What runs in CodeSplash
- Linear / logistic regression Verified in Python and R
You will be able to
- Read a linear or logistic prediction as a weighted sum
- Predict when a linear model will keep up with flexible learners
- Add features that let a linear model draw non-linear boundaries
Read first
A weighted sum
ReadEach prediction is a weighted sum of standardized features:
For two classes, the sum is the log-odds, and the logitLogitThe log of the odds, log(p / (1 − p)); logistic regression models it as a straight line. link turns it into a probability. For more classes, there's one sum per class.
You can write any prediction out by hand, check it, and export it. Linear / logistic regression can export as SQL, which most learners can't.
Will it keep up?
PredictPredict first
Two problems: diabetes from seven clinical measurements, and ozone from weather. You compare a linear model with boosting on each, using cross-validation. What do you expect?
Reveal
Linear keeps up on diabetes and falls behind on ozone. Diabetes: AUC 0.857 against 0.843 for boosting. Ozone: RMSE 22.9 against 18.2. Ozone rises sharply on hot, still days, and a straight line can't bend that way.
A boundary is linear in what you give it
ExploreA logistic model's boundary is a straight line in its features. On Ring around a core, it can't separate the classes. Change Model to Logistic with squared terms and see it draw a circle.
DExplorable · Decision boundary zoo
What shapes of boundary can each kind of model draw?
Which model will score highest on new data from this shape?
Data
Model
k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.
Commit your prediction above to see the result
Make your prediction to see the result.
The same trick works on your data: splines, interactions and ratios let a linear model bend. The check asks you to reach new-data accuracy above 0.9 with a logistic model.
Prediction isn't inference
ReadA coefficient here is a prediction weight on a standardized feature. Correlated features trade weight freely, without changing the prediction. So a large coefficient doesn't show that a feature causes anything, and a small one doesn't show that it doesn't matter.
With every level of a category encoded, the design is collinear. The app's learner takes the minimum-norm solution, so predictions stay well defined: on penguins, for example, cross-validated log loss is 0.436.
For standard errors and tests on coefficients, use Analyze, not Predict.
Check your understanding
CheckpointCheck yourself
A logistic model's sum for one row is 0. What probability does it predict?
Show the answer
Answer: b
The logit is 0 when the probability is one half. The intercept is already part of the sum.
Check yourself
A linear model is within noise of a boosted one. Which is the better choice, other things equal?
Show the answer
Answer: a
If the cheaper, clearer model is as good within noise, complexity hasn't earned its keep. The leaderboard's Most interpretable badge marks that model.
Check yourself
Two features are highly correlated. One gets a large positive coefficient and the other a large negative one. What's the safest reading?
Show the answer
Answer: b
The prediction can be fine while the split between correlated columns is arbitrary. Use permutation grouped by feature cluster, or remove one, before saying anything about either.
Train it
In the appIn the Learners step, select Linear / logistic regression next to Baseline (no features). Its card shows a high interpretability rating and standardizes inputs. After training, Overview lists each feature's coefficient size, and Explain offers SHAP (linear), which is exact for this model.
import pandas as pd
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 StandardScaler
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
model = make_pipeline(StandardScaler(), LogisticRegression(C=1e6, max_iter=500))
cv = StratifiedKFold(5, shuffle=True, random_state=1)
print(cross_val_score(model, X, y, cv=cv, scoring="roc_auc").mean())
print(pd.Series(model.fit(X, y)[-1].coef_[0], X.columns).round(2))df <- rbind(MASS::Pima.tr, MASS::Pima.te)
num <- setdiff(names(df), "type")
df[num] <- scale(df[num])
fit <- glm(type ~ ., binomial, df)
round(coef(fit), 2)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
mean(sapply(1:5, function(k) {
m <- glm(type ~ ., binomial, df[fold != k, ])
as.numeric(pROC::auc(df$type[fold == k], predict(m, df[fold == k, ], type = "response"), quiet = TRUE))
}))Recap
Recap- A linear or logistic prediction is a sum you can read and export.
- It keeps up when effects are close to additive and smooth, and falls behind when they bend or interact.
- New features let it draw curves. Read its coefficients as weights, not causes.
Concepts in this lesson