Sub topic 19
Assumptions, perfect separation, and when to move on
This chapter assumes you can fit and evaluate a logistic regression, read its coefficients as log-odds, and use L2 regularization. Here we look at where the model stops working: what it assumes, how it fails, and what to try next.
What the model assumes
Logistic regression assumes the log-odds of the positive class is a linear function of the features:
log(p / (1 − p)) = w·x + b
Several practical assumptions follow from this.
- Linear log-odds. Each feature moves the log-odds by a constant amount per unit, wherever it sits on its range. If the true effect is curved or has thresholds, the model is misspecified.
- Independent observations. The likelihood multiplies per-example probabilities. Repeated measurements of the same patient, user, or machine break this. The coefficients can still be useful, but standard errors and any significance claims become too optimistic.
- No severe multicollinearity. Strongly correlated features do not hurt prediction much, but they make individual coefficients unstable. They can swing in sign between samples.
- Enough examples per feature. A common rule of thumb is at least 10 to 20 examples of the rarer class per feature. Below that, the fit overfits unless you regularize.
- Correct labels. Noisy labels pull probabilities toward 0.5 and hide real structure.
The model does not need normally distributed features, equal class variances, or a linear relationship between the features and the probability. Linearity applies to the log-odds only.
Perfect separation
Perfect (or complete) separation happens when some linear boundary classifies every training example correctly. Then the likelihood can always be increased by making the weights larger, because larger weights push every probability closer to 0 or 1. The maximum is only reached at infinity.
The effects are:
- Unregularized fits never converge. Solvers stop at an iteration limit, and coefficients are huge.
- Odds ratios become absurd, such as e^40.
- Predicted probabilities are extreme and overconfident.
- Statistical packages may report enormous standard errors or warnings.
It is most common with small datasets, many features, or a single feature that nearly determines the label, such as an ID-like column or a leaked outcome.
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[-3.0], [-2.0], [-1.0], [1.0], [2.0], [3.0]])
y = np.array([0, 0, 0, 1, 1, 1])
for C in [1, 100, 10000, 1e6]:
clf = LogisticRegression(C=C, max_iter=10000).fit(X, y)
print(C, clf.coef_[0][0])The data is perfectly separated at 0. As C grows (weaker regularization), the coefficient keeps growing instead of settling. With a small C, the L2 penalty acts as a brake and the weight stays finite.
Responding to separation
- Check for leakage first. A feature that separates perfectly may encode the label.
- Keep or strengthen regularization. L2 gives finite weights. L1 also drops features.
- Collect more data, or reduce the number of features.
- For inference on small samples, consider Firth's penalized likelihood, available in some statistics packages but not in scikit-learn.
Nonlinear structure
When the classes are not separable by a line or plane, logistic regression underfits. The raw model below cannot separate two concentric rings. Adding squared terms makes the boundary an ellipse in the original space, which fits.
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
X, y = make_circles(n_samples=400, noise=0.1, factor=0.4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
linear = LogisticRegression().fit(X_train, y_train)
poly = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
StandardScaler(),
LogisticRegression(max_iter=1000),
).fit(X_train, y_train)
print("linear:", linear.score(X_test, y_test))
print("degree 2:", poly.score(X_test, y_test))The linear model scores near chance, while the degree-2 model scores close to 1. The model is still logistic regression. Only the features changed. This is the cheapest fix for nonlinearity: add squares, interactions, splines, or binned versions of a feature.
Other pitfalls
| Pitfall | Symptom | Response |
|---|---|---|
| Unscaled features | Slow or failed convergence, uneven regularization | Standardize inside a pipeline |
| Leakage | Suspiciously high test scores | Remove features unavailable at prediction time |
| Class imbalance | High accuracy, low recall | Use PR curves, adjust the threshold, consider class weights |
| Multicollinearity | Coefficients flip sign between samples | Drop or combine features, use L2 |
| Distribution shift | Performance decays after deployment | Monitor metrics and calibration, retrain |
| Reading coefficients causally | Wrong conclusions about interventions | Treat them as associations, not effects |
Outliers in the features also matter. A single extreme value has a large lever on the linear score, so consider clipping or transforming heavy-tailed features.
When to move on
Logistic regression is a strong baseline, and often a good final model. It trains fast, its coefficients are explainable, and with calibration its probabilities are usable. Move on when the evidence says it is the limit, not before.
Signs that a more flexible model may help:
- Learning curves show high training error as well as high validation error (underfitting), and extra features do not close the gap.
- Residual analysis shows strong interactions you cannot easily enumerate.
- You have many examples and many features with unknown structure, such as images, text, or audio. Neural networks or specialized models usually win there.
Signs you should stay:
- You need transparent coefficients for stakeholders or regulators.
- Data is small, so a flexible model would overfit.
- Latency or memory limits are tight.
Always keep the logistic baseline. If a gradient-boosted model improves the validation metric only slightly, the simpler model is usually the better choice to deploy.
Exercise
A logistic regression fitted without regularization on a small dataset reports a coefficient of 38 for one feature and warns about non-convergence. Name the likely cause, one way to check it, and two ways to fix it.
Show answer
The likely cause is perfect (or near-perfect) separation, where the likelihood keeps increasing as the weight grows. Check by looking for a single feature or a linear combination that splits the classes with no errors on the training set, and by confirming the feature is not leaking the label. Fixes: add or strengthen L2 regularization (lower C), remove or combine features, collect more data, or use a penalized method such as Firth's.
Exercise
Logistic regression scores near chance on data where one class forms a ring around the other. Why, and how can you improve it without changing the model family?
Show answer
The classes are not linearly separable, and the log-odds is not a linear function of the raw features. Add nonlinear features such as squared terms and interactions (for example PolynomialFeatures with degree 2). The boundary becomes curved in the original space, while the model is still logistic regression.