Linear & Logistic Regression
Linear and logistic regression are the foundation of supervised learning: fast, interpretable, and often surprisingly competitive. Understand them before moving to more complex models.
Every code block runs in a container in the companion repository, so the numbers are real.
Linear regression
Section titled “Linear regression”Linear regression predicts a continuous target as a weighted sum of features.
from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.datasets import make_regressionfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScaler
out = Path("outputs")out.mkdir(exist_ok=True)feature_names = [f"feature_{i}" for i in range(10)]
features, y = make_regression(n_samples=500, n_features=10, n_informative=5, noise=15, random_state=42)x_train, x_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=42)
lr = Pipeline([("scaler", StandardScaler()), ("regressor", LinearRegression())])lr.fit(x_train, y_train)y_pred = lr.predict(x_test)print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.2f}")print(f"R2: {r2_score(y_test, y_pred):.4f}")RMSE: 16.21R2: 0.9427After scaling, coefficients show the relative importance and direction of each feature.
coefs = pd.DataFrame({ "feature": feature_names, "coefficient": lr.named_steps["regressor"].coef_,}).sort_values("coefficient", key=abs, ascending=False)print(coefs.round(3).to_string(index=False)) feature coefficientfeature_6 46.052feature_0 28.095feature_7 24.972feature_2 20.291feature_8 15.396feature_9 -0.757feature_3 0.725feature_4 0.488feature_5 -0.335feature_1 -0.123The five informative features (6, 0, 7, 2, 8) have large coefficients; the rest sit near zero. The model recovered the signal.
Regularization
Section titled “Regularization”Regularization penalizes large coefficients, reducing overfitting.
from sklearn.linear_model import ElasticNet, Lasso, Ridge
models = { "Linear": LinearRegression(), "Ridge (alpha=1)": Ridge(alpha=1), "Ridge (alpha=10)": Ridge(alpha=10), "LASSO (alpha=1)": Lasso(alpha=1), "LASSO (alpha=10)": Lasso(alpha=10), "ElasticNet (alpha=1, l1=0.5)": ElasticNet(alpha=1, l1_ratio=0.5),}rows = []for name, model in models.items(): pipe = Pipeline([("scaler", StandardScaler()), ("model", model)]) pipe.fit(x_train, y_train) pred = pipe.predict(x_test) n_nonzero = int((pipe.named_steps["model"].coef_ != 0).sum()) rows.append([name, np.sqrt(mean_squared_error(y_test, pred)), r2_score(y_test, pred), n_nonzero])columns = ["Model", "RMSE", "R2", "Non-zero coefs"]print(pd.DataFrame(rows, columns=columns).to_string(index=False)) Model RMSE R2 Non-zero coefs Linear 16.214131 0.942674 10 Ridge (alpha=1) 16.206463 0.942728 10 Ridge (alpha=10) 16.212423 0.942686 10 LASSO (alpha=1) 16.470168 0.940850 5 LASSO (alpha=10) 28.599540 0.821647 5ElasticNet (alpha=1, l1=0.5) 27.512949 0.834942 9- Ridge shrinks coefficients but keeps all 10 features; performance is unchanged.
- LASSO (alpha=1) zeros 5 features, keeping exactly the informative ones.
- LASSO (alpha=10) over-penalizes and hurts performance.
- Elastic Net blends both penalties.
The LASSO coefficient path shows how coefficients shrink to zero as regularization grows. Informative features survive longest.
alphas = np.logspace(-2, 2, 50)paths = []for alpha in alphas: pipe = Pipeline([("scaler", StandardScaler()), ("lasso", Lasso(alpha=alpha))]) pipe.fit(x_train, y_train) paths.append(pipe.named_steps["lasso"].coef_)paths = np.array(paths)
fig, ax = plt.subplots(figsize=(6, 4))for i in range(10): ax.plot(alphas, paths[:, i], label=feature_names[i])ax.set_xscale("log")ax.set_xlabel("alpha")ax.set_ylabel("Coefficient")ax.set_title("LASSO coefficient path")fig.tight_layout()fig.savefig(out / "lasso-coefficient-path.png", dpi=150)plt.close(fig)
Logistic regression
Section titled “Logistic regression”Logistic regression predicts class probability via a sigmoid of the weighted sum.
from sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, cross_val_score
features, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=2, weights=[0.7, 0.3], random_state=42)x_train, x_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=42, stratify=y)
log_reg = Pipeline([("scaler", StandardScaler()), ("classifier", LogisticRegression(max_iter=1000, random_state=42))])cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)scores = cross_val_score(log_reg, x_train, y_train, cv=cv, scoring="roc_auc")print(f"Cross-validated ROC-AUC: {scores.mean():.4f} (+/- {scores.std():.4f})")log_reg.fit(x_train, y_train)y_prob = log_reg.predict_proba(x_test)[:, 1]print(f"Test ROC-AUC: {roc_auc_score(y_test, y_prob):.4f}")Cross-validated ROC-AUC: 0.8786 (+/- 0.0192)Test ROC-AUC: 0.8595Coefficients are log-odds; exponentiating gives odds ratios, which are easier to read.
lcoef = log_reg.named_steps["classifier"].coef_[0]odds = pd.DataFrame({ "feature": feature_names, "coefficient": lcoef, "odds_ratio": np.exp(lcoef),}).sort_values("coefficient", key=abs, ascending=False)print(odds.head(5).round(4).to_string(index=False)) feature coefficient odds_ratiofeature_3 1.0415 2.8334feature_5 -0.8766 0.4162feature_0 0.8740 2.3964feature_4 -0.8477 0.4284feature_1 -0.3235 0.7236fig, ax = plt.subplots(figsize=(6, 4))ordered = odds.iloc[::-1]ax.barh(ordered["feature"], ordered["coefficient"], color="#4c72b0")ax.axvline(0, color="grey", lw=0.8)ax.set_xlabel("Coefficient (log-odds)")ax.set_title("Logistic regression coefficients")fig.tight_layout()fig.savefig(out / "logistic-coefficients.png", dpi=150)plt.close(fig)
An odds ratio of 2.83 (feature_3) means a one-standard-deviation increase multiplies
the odds of the positive class by 2.83. An odds ratio of 0.42 (feature_5) cuts them
by 58%. Ratios near 1.0 have little effect.
The C parameter controls regularization (inverse of alpha). Performance is stable
across a wide range, so the default C=1 is a fine start.
for c_value in [0.01, 0.1, 1, 10, 100]: model = LogisticRegression(C=c_value, max_iter=1000, random_state=42) pipe = Pipeline([("scaler", StandardScaler()), ("classifier", model)]) scores = cross_val_score(pipe, x_train, y_train, cv=cv, scoring="roc_auc") print(f"C={c_value:>6}: ROC-AUC={scores.mean():.4f}")C= 0.01: ROC-AUC=0.8759C= 0.1: ROC-AUC=0.8783C= 1: ROC-AUC=0.8786C= 10: ROC-AUC=0.8788C= 100: ROC-AUC=0.8788When to use it
Section titled “When to use it”Use linear or logistic regression when you need interpretable results, the relationship is roughly linear, or you want a fast baseline. Avoid it when the relationship is highly nonlinear or feature interactions matter and cannot be engineered by hand.
| Linear | Logistic | |
|---|---|---|
| Task | Regression | Classification |
| Output | Continuous | Probability |
| Loss | Mean squared error | Log loss |
| Regularization | alpha (Ridge/LASSO) | C (inverse of alpha) |
| Interpretation | Coefficient = change in y per unit x | Odds ratio = multiplicative change in odds |
Next steps
Section titled “Next steps”Linear models assume linearity. The next page covers XGBoost, which captures nonlinear patterns and interactions automatically.
Further reading
Section titled “Further reading”-
The guide defines least squares, Ridge, Lasso, ElasticNet, and logistic regression. Its objectives explain why penalty parameters and coefficient units need model-specific interpretation.
-
scikit-learn cross-validation guide
The guide explains how to compare parameter settings without using the final test set. Apply that procedure when selecting a point along a regularization path.