PeaBox Lab › PeaLang › Learn › Chapter 19 › Lesson 2

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:

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

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:

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

Guided practice

Hands-on lab: Two interpretable baselines

Review questions

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.

← Previous Next →