Knowledge / Artificial Intelligence and Data Science / Linear and logistic regression

Linear and logistic regression

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

Linear regression fits a straight-line (or hyperplane) relationship between numeric predictors and a continuous target by minimising squared error; logistic regression models the probability of a class by passing a linear score through the sigmoid and fitting by maximum likelihood. Both are *generalised linear models* — linear in the parameters — and both are the baseline every data-science team builds before anything fancier. They are the most heavily examined topics in ML papers under AICTE/CBCS curricula and in GATE DA (Data Science and Artificial Intelligence, introduced 2024), and the most asked in Indian analytics interviews (Mu Sigma, Fractal, Tiger Analytics, ZS Associates, TCS/Infosys/Wipro data units, bank and NBFC risk teams). Interviewers favour them because the maths is closed-form enough to probe and the coefficients are interpretable enough to defend to a regulator.

Explained

Simple and multiple linear regression

Assumptions, diagnostics and inference

Logistic regression — model and fitting

Regularisation, scaling and class balance

Comparison, strengths and limits

Key points

Formulas and examples

Simple OLS slope and intercept: β₁ = Sxy/Sxx = [Σxy − (ΣxΣy)/n] / [Σx² − (Σx)²/n]; β₀ = ȳ − β₁x̄
Matrix OLS: β̂ = (XᵀX)⁻¹Xᵀy (X: n×(p+1) design matrix, y: n×1 target)
Sums of squares: SST = Σ(yᵢ − ȳ)² = SSR + SSE, where SSR = Σ(ŷᵢ − ȳ)², SSE = Σ(yᵢ − ŷᵢ)²
R² = SSR/SST = 1 − SSE/SST; Adjusted R² = 1 − (1 − R²)(n − 1)/(n − p − 1)
Error estimates: s² = SSE/(n − p − 1) (MSE, units of y²); RMSE = √(SSE/n); MAE = Σ|eᵢ|/n
SE of slope (simple): SE(β₁) = s/√Sxx; t = β₁/SE(β₁), df = n − 2
Correlation link: r = β₁ · (s_x/s_y); R² = r² in simple linear regression
VIF_j = 1/(1 − R²_j), R²_j from regressing x_j on all other predictors
Gradient descent: β_j ← β_j − α·(1/n)Σ(ŷᵢ − yᵢ)x_ij (α = learning rate, dimensionless)
Sigmoid: p = 1/(1 + e−z), z = β₀ + Σβ_j x_j (z is dimensionless log-odds)
Logit / odds: odds = p/(1 − p); ln(odds) = z; odds ratio for x_j = eβ_j
Log loss: J = −(1/n) Σ [yᵢ ln pᵢ + (1 − yᵢ) ln(1 − pᵢ)] (nats per sample)
Ridge (centred, one feature): β₁ridge = Sxy/(Sxx + λ); Lasso objective: SSE + λΣ|β_j|
Classification metrics: Accuracy = (TP+TN)/N; Precision = TP/(TP+FP); Recall = TP/(TP+FN); F1 = 2PR/(P+R); Specificity = TN/(TN+FP)

Example 1 — Fit a simple regression and test the slope. Data: x = 1,2,3,4,5 (hours of practice tests per week); y = 2,4,5,4,5 (marks scored, scale 0–10).

Example 2 — Two steps of batch gradient descent (same data), α = 0.1, start β = (0, 0).

Example 3 — Logistic regression: probability and odds ratio. Placement model: z = −6 + 0.6·CGPA + 1.2·Internship (Internship = 1 if completed).

Example 4 — Threshold metrics and log loss. 100 students, threshold 0.5: TP = 35, FP = 15, FN = 10, TN = 40.

MetricWorkingValue
Accuracy(35+40)/1000.750
Precision35/500.700
Recall (sensitivity)35/450.778
Specificity40/550.727
F12(0.70×0.778)/1.4780.737

Log loss on four held-out cases — (y=1, p=0.9), (y=0, p=0.2), (y=1, p=0.6), (y=0, p=0.7): −[ln0.9 + ln0.8 + ln0.6 + ln0.3]/4 = (0.1054 + 0.2231 + 0.5108 + 1.2040)/4 = 0.511 nats. The single confident wrong call (p = 0.7 for a y = 0) contributes 59% of the loss — log loss punishes confident errors hardest.

Example 5 — Ridge shrinkage and multicollinearity. Using Example 1's centred data (Sxx = 10, Sxy = 6): λ = 0 → β₁ = 0.600; λ = 5 → 6/15 = 0.400; λ = 20 → 6/30 = 0.200. Coefficients shrink towards zero but never reach it. If a second predictor x₂ = 2x₁ were added, XᵀX would be singular and OLS would have no unique solution, while ridge still returns a stable (split) pair of coefficients.

Linear regressionLogistic regression
TargetContinuous (₹, kg, marks)Categorical (0/1 or k classes)
LinkIdentityLogit (sigmoid)
LossSquared error (MSE)Log loss (cross-entropy)
EstimationLeast squares, closed formMaximum likelihood, iterative
Output range(−∞, ∞)(0, 1)
Key metricsR², adj R², RMSE, MAEAccuracy, precision/recall, AUC, log loss
Coefficient readingΔy per unit xOdds multiplied by eβ per unit x
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import numpy as np, statsmodels.api as sm

X = np.array([[1],[2],[3],[4],[5]]); y = np.array([2,4,5,4,5])
lin = LinearRegression().fit(X, y)
print(lin.intercept_, lin.coef_, lin.score(X, y))   # 2.2  [0.6]  0.6

print(sm.OLS(y, sm.add_constant(X)).fit().summary())  # t, p, F, CIs

# logistic with scaling + L2 (C = 1/lambda); predict_proba, not predict, for probabilities
clf = make_pipeline(StandardScaler(),
                    LogisticRegression(C=1.0, class_weight='balanced', max_iter=1000))

Where it is used

Interview questions

Common mistakes

Related topics

Overfitting, bias-variance and regularisation · Model evaluation metrics · Feature selection and model interpretability · Machine learning workflow · Support vector machines and k-nearest neighbours · Dimensionality reduction and PCA

Open in the Knowledge reader →Find jobs →