Part IV — Expert Production Engineering · Chapter 19 · Lesson 2 of 7 · 7 min read
Lesson 2: Linear and Logistic Regression
Lesson level: Advanced
Purpose: Fit, interpret, and diagnose the two most widely used interpretable models — linear regression for numeric targets and logistic regression for binary targets — and know when their assumptions break.
Learning objectives
By the end of this lesson you will be able to:
- explain linear regression as a weighted sum of features plus an intercept
- describe how least squares and gradient descent find the weights
- interpret coefficients on scaled and unscaled features
- explain logistic regression as a linear score passed through the sigmoid function
- interpret log-odds coefficients and predicted probabilities
- diagnose non-linearity, outliers, multicollinearity, and class imbalance
2.1 Linear regression
Linear regression predicts a number as a weighted sum of the features:
ŷ = b0 + b1x1 + b2x2 + … + bkxk
The intercept b0 is the prediction when every feature is zero, and each coefficient bj is the change in the prediction for a one-unit increase in feature xj, holding the others fixed. The model is fitted by choosing the coefficients that minimize the sum of squared errors between predictions and actual values on the training data.
For small and medium problems the least-squares solution can be computed directly. For large datasets, or when regularization or other losses are used, gradient descent starts with some weights and repeatedly moves them a small step in the direction that reduces the loss. The step size is the learning rate; too large and the loss diverges, too small and training takes forever. Standardized features make gradient descent converge far more reliably, which is one reason Lesson 1 scales them.
Illustrative listing.
from pealang.ml import LinearRegression
model = LinearRegression()
model.fit(Xtr, y_train) # preprocessed training features
pred = model.predict(Xte)
print("intercept", model.intercept)
for name, coef in zip(feature_names, model.coefficients):
print(name, round(coef, 3))
2.2 Interpreting coefficients
Coefficients are only interpretable relative to the scale of their features. On raw features, "each extra year of tenure adds 0.8 hours" is a direct business statement. On standardized features, each coefficient is the change for a one-standard-deviation increase, which makes coefficients comparable with each other but less directly meaningful. Report both when explaining a model to stakeholders: standardized coefficients to rank importance, and raw-unit effects to explain size.
Two cautions apply. First, a coefficient describes an association in the training data, not a causal effect: raising a customer's tenure does not cause anything. Second, when features are strongly correlated with each other — multicollinearity — individual coefficients become unstable and can even flip sign between training runs while predictions stay similar. Check pairwise correlations, drop or combine redundant features, or use regularization (Lesson 4).
2.3 When linear regression struggles
- Non-linear relationships: the effect of a feature is curved or has a threshold. Add transformed features (logarithms, squares, bins) or interaction terms that express the real shape.
- Outliers: squared errors give extreme points large influence. Investigate them; consider robust losses or capping.
- Changing error size: errors grow with the level of the target, common for prices and revenue. Modelling the logarithm of the target often helps.
- Extrapolation: predictions outside the range of training data are just the line continued, which may be absurd.
The main diagnostic is a residual plot: residuals (actual minus predicted) against predictions and against each important feature. Residuals should look like patternless noise around zero. A curve means missing non-linearity; a funnel means changing error size; isolated far points are outliers to investigate.
2.4 Logistic regression
For a binary target — churned or not, fraudulent or not — a straight-line prediction can fall below 0 or above 1, which makes no sense as a probability. Logistic regression computes the same linear score z = b0 + b1x1 + … + bkxk and passes it through the sigmoid function:
p = 1 / (1 + e−z)
The sigmoid maps any score to a probability between 0 and 1: a score of 0 gives 0.5, large positive scores approach 1, and large negative scores approach 0. The model is fitted by maximizing the likelihood of the observed labels, equivalently minimizing log loss (also called cross-entropy), which heavily penalizes confident wrong predictions.
Illustrative listing.
from pealang.ml import LogisticRegression
clf = LogisticRegression(max_iter=500, seed=42)
clf.fit(Xtr, y_train)
proba = clf.predict_proba(Xte) # probability of the positive class
label = [1 if p >= 0.5 else 0 for p in proba]
Note that the 0.5 cut-off in the last line is a default, not a decision. Lesson 5 shows how to choose the threshold from business costs.
2.5 Interpreting logistic coefficients
A logistic coefficient is the change in the log-odds of the positive class for a one-unit increase in the feature. Exponentiating it gives an odds ratio: a coefficient of 0.69 means the odds roughly double (e0.69 ≈ 2.0) for each unit increase. Odds ratios are easier to communicate than log-odds, but they are still not probabilities: doubling odds from 1:99 to 2:98 barely changes the probability, while doubling 1:1 to 2:1 moves it from 50% to 67%.
For stakeholders, the clearest explanation is often a small table of predicted probabilities for representative customers — "a two-year customer on the basic plan with three support tickets has a 12% predicted churn probability; with eight tickets, 31%" — computed directly from the model.
2.6 Class imbalance
When the positive class is rare, a model can reach high accuracy by predicting "no" for everyone. Logistic regression will still produce useful probabilities, but its default 0.5 threshold will flag few cases. Responses, in order of preference:
- Evaluate with metrics that respect imbalance (Lesson 3), not accuracy.
- Choose the decision threshold from costs (Lesson 5) instead of using 0.5.
- If needed, apply class weights so that errors on the rare class count more during fitting; record that the predicted probabilities are then no longer calibrated and must be recalibrated.
- Resample only inside the training data, never in validation or test data.
2.7 Annotated example: job-duration estimate
A facilities team predicts repair job duration in hours from job type, building age, floor area, and technician seniority. A first linear model has acceptable average error but a funnel-shaped residual plot: errors on large jobs are huge. Modelling the logarithm of duration, adding a building-age-squared term, and one-hot encoding job type reduces large-job error substantially, and the residuals become patternless.
The coefficients then read naturally as percentage effects: "each additional 1,000 square metres adds about 9% to expected duration". Predictions are converted back from the log scale before use, and the team documents that the back-converted value estimates the typical (median) job rather than the mean.
Common mistakes
- Reading coefficients as causes: they describe associations in the training data.
- Ignoring scale when comparing coefficients: compare standardized coefficients, explain raw-unit effects.
- Skipping residual plots: curves, funnels, and outliers are invisible in a single metric.
- Trusting unstable coefficients under multicollinearity: remove redundancy or regularize.
- Using linear regression for probabilities: use logistic regression for binary targets.
- Treating 0.5 as the decision threshold: choose it from costs.
- Resampling before splitting: duplicates of training rows leak into evaluation.
Guided practice
- Fit linear regression on raw and on standardized features. Confirm predictions are identical while coefficients differ, and explain why.
- Create two nearly identical features and fit twice with different seeds or samples. Observe the coefficients.
- Compute the sigmoid of −4, −1, 0, 1, and 4 and sketch the curve.
- Convert three logistic coefficients to odds ratios and describe each in a sentence.
Hands-on lab: Two interpretable baselines
- Using the preprocessed data from Lesson 1, fit logistic regression for churn and record coefficients, odds ratios, and predicted probabilities on the test set.
- Using a separate dataset with a numeric target (for example monthly spend), fit linear regression and draw residual plots.
- Improve the linear model with at most three feature transformations justified by the residual plots.
- For both models, write a one-page explanation for a business reader: what drives the prediction, how large the effects are, and what the model cannot tell you.
Review questions
- What does a linear-regression coefficient represent?
- Why does standardization help gradient descent?
- What does a funnel-shaped residual plot indicate?
- How does the sigmoid turn a linear score into a probability?
- What is an odds ratio, and why is it not a probability?
- Why can high accuracy be misleading with rare positives?
- What happens to calibration when class weights are used?
Applied challenge
A lender wants an interpretable model of loan default. Build a logistic regression with no more than ten features, check multicollinearity, explain each coefficient as an odds ratio, and produce a table of predicted probabilities for five representative applicants. Identify any feature that should be excluded for legal or fairness reasons before deployment, and explain why.
Lesson summary
Linear regression predicts numbers as a weighted sum of features; logistic regression turns the same kind of score into a probability with the sigmoid. Both are fast, interpretable baselines. Interpret coefficients with their scale and as associations, diagnose with residual plots and correlation checks, handle imbalance through metrics and thresholds, and transform features or targets when relationships are not linear.
Transition to Lesson 3
A fitted model is only as useful as our ability to measure it. Lesson 3 defines regression and classification metrics and links each to the cost of the errors it measures.
Lesson status: Ready for review.