Lesson 5 of 12 · Core Algorithms
Linear Models
How linear models work: weighted sums, linear and logistic regression, reading coefficients, Ridge and Lasso regularisation, and what lines can't learn.
- 17 min read
- Intermediate
- Reviewed
- Write a linear model's prediction as a weighted sum and check it by hand
- Explain how logistic regression turns a weighted sum into a probability
- Compare coefficients fairly by scaling the features first
- Use Ridge and Lasso regularisation to stop a linear model overfitting
- Recognise patterns a linear model can't learn, and how new features help
The idea in plain words
A linear model predicts with a weighted sum: every feature is multiplied by a weight, the results are added up, and a starting value is added. You met this recipe in Introduction to Machine Learning. Training chooses the weights that give the smallest loss: squared error for linear regression and log loss for logistic regression, as you saw in Loss Functions.
prediction = intercept + weight₁ × feature₁ + weight₂ × feature₂ + … + weightₙ × featureₙLinear models are the first family in this tour because they are simple, fast and easy to explain, and they are often surprisingly hard to beat.
Linear regression
Back to the food deliveries from Regression vs Classification. The data was generated with the recipe "10 minutes, plus 2 minutes per km, plus 1 minute per item, plus some random delay". Can linear regression find that recipe from the data alone?
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.RandomState(0)
distance = rng.uniform(1, 15, size=200) # km
items = rng.randint(1, 10, size=200) # items in the order
minutes = 10 + 2 * distance + items + rng.normal(0, 4, size=200)
X = np.column_stack([distance, items])
model = LinearRegression().fit(X, minutes)
w_distance, w_items = model.coef_
b = model.intercept_
print(f"minutes = {b:.2f} + {w_distance:.2f} x distance + {w_items:.2f} x items")
order = [6, 3] # 6 km, 3 items
by_hand = b + w_distance * order[0] + w_items * order[1]
print(f"By hand: {by_hand:.2f} model.predict: {model.predict([order])[0]:.2f}")minutes = 9.99 + 2.09 x distance + 0.79 x items By hand: 24.89 model.predict: 24.89
From 200 noisy deliveries, the model recovered a recipe close to the real one: about 10 minutes to start, 2.09 minutes per km and 0.79 minutes per item (the random delays keep it from being exact). The prediction worked out by hand matches predict exactly, because the formula is the whole model: coef_ holds the weights and intercept_ the starting value.
Logistic regression
Logistic regression is the classifier version. It computes the same kind of weighted sum, called z, and then squeezes it into a probability between 0 and 1 with the sigmoid function:
z = intercept + weight₁ × feature₁ + … + weightₙ × featureₙ
probability = 1 ÷ (1 + e^(−z)) the sigmoid: always between 0 and 1A large positive z gives a probability near 1, a large negative z gives one near 0, and z = 0 gives exactly 0.5. Move the sliders to see how the weight and the intercept (called b here) shape the curve:
Here is the late-delivery classifier from Regression vs Classification, taken apart:
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.RandomState(0)
distance = rng.uniform(1, 15, size=200)
items = rng.randint(1, 10, size=200)
minutes = 10 + 2 * distance + items + rng.normal(0, 4, size=200)
X = np.column_stack([distance, items])
late = (minutes > 30).astype(int)
model = LogisticRegression().fit(X, late)
(w_distance, w_items), b = model.coef_[0], model.intercept_[0]
order = [9, 5]
z = b + w_distance * order[0] + w_items * order[1] # 1. a weighted sum, as before
p = 1 / (1 + np.exp(-z)) # 2. squeezed between 0 and 1
print(f"weighted sum z = {z:.2f}, sigmoid(z) = {p:.3f}")
print(f"predict_proba says {model.predict_proba([order])[0, 1]:.3f}")
# The boundary is where z = 0 (probability 0.5). With 5 items:
print(f"With 5 items, orders beyond {-(b + w_items * 5) / w_distance:.1f} km are predicted late")weighted sum z = 1.54, sigmoid(z) = 0.824 predict_proba says 0.824 With 5 items, orders beyond 7.4 km are predicted late
The weighted sum for a 9 km order with 5 items is 1.54, and the sigmoid turns that into a probability of 0.824, exactly what predict_proba reports. The model switches from "on time" to "late" where z crosses 0. Solving z = 0 for the distance shows that, for a 5-item order, the switch happens at 7.4 km.
Because z is a weighted sum, the boundary is always a straight line: here, a line across the map of distance and items. That's why logistic regression is called a linear classifier.
Reading coefficients fairly
Coefficients are tempting to read as "how important each feature is". Be careful: a coefficient depends on the feature's units. The program below fits house prices (in thousands) from size in m², number of bedrooms and age in years, first on the raw features and then after standardising them, which rescales every feature to have mean 0 and standard deviation 1:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.RandomState(0)
size = rng.uniform(40, 200, size=300) # square metres
bedrooms = rng.randint(1, 6, size=300)
age = rng.uniform(0, 60, size=300) # years
price = 2.5 * size + 15 * bedrooms - 1.0 * age + rng.normal(0, 20, size=300)
X = np.column_stack([size, bedrooms, age])
names = ["size", "bedrooms", "age"]
raw = LinearRegression().fit(X, price)
scaled = make_pipeline(StandardScaler(), LinearRegression()).fit(X, price)
print("feature raw coefficient coefficient after scaling")
for name, r, s in zip(names, raw.coef_, scaled[-1].coef_):
print(f"{name:<9} {r:12.2f} {s:20.2f}")feature raw coefficient coefficient after scaling size 2.49 115.70 bedrooms 15.81 21.27 age -1.09 -19.28
On raw features, a bedroom (15.81 thousand) looks far more important than a square metre (2.49 thousand). But one square metre is a tiny change, and sizes here range across 160 m², while bedrooms only range from 1 to 5. After scaling, each coefficient means "the effect of a typical-sized change in this feature" (one standard deviation), and size is clearly the biggest influence (115.70), with bedrooms and age (negative: older homes are cheaper) far behind. Compare coefficients only after scaling.
Two more cautions. When two features are strongly related, such as size and number of rooms, the model can split the credit between them in odd ways, so their individual coefficients become unreliable. And a coefficient describes a pattern in the data, not a cause: a positive weight for "owns a gym membership" in a health model doesn't mean buying one makes anyone healthier.
Regularisation: Ridge and Lasso
With many features and few rows, a linear model can fit its training data perfectly by giving large weights to features that only match by chance. Regularisation (introduced in Introduction to Machine Learning) adds a penalty for large weights to the loss:
Ridge: squared error + alpha × (sum of the squared weights)
Lasso: squared error + alpha × (sum of the absolute weights)(scikit-learn scales the two terms slightly differently in each model, so the same alpha means different things in Ridge and Lasso.) The bigger alpha, the stronger the penalty. Ridge shrinks all weights towards zero; Lasso can push weights to exactly zero, which removes those features from the model.
The program below has 60 rows and 50 features, of which only 5 really affect the label. Scores are R², the default score of scikit-learn regressors: 1 is perfect, 0 is no better than always predicting the average, and below 0 is worse than that.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.model_selection import cross_val_score
# 60 rows but 50 features, and only 5 of the features really matter
X, y = make_regression(n_samples=60, n_features=50, n_informative=5,
noise=20, random_state=0)
for name, model in [("LinearRegression", LinearRegression()),
("Ridge, alpha=1", Ridge(alpha=1)),
("Lasso, alpha=1", Lasso(alpha=1)),
("Lasso, alpha=5", Lasso(alpha=5)),
("Lasso, alpha=50", Lasso(alpha=50))]:
cv = cross_val_score(model, X, y, cv=5).mean()
model.fit(X, y)
used = np.sum(model.coef_ != 0) # features with a non-zero weight
print(f"{name:<16} train R2 {model.score(X, y):.2f} CV R2 {cv:.2f} features used {used:>2}")LinearRegression train R2 1.00 CV R2 0.40 features used 50 Ridge, alpha=1 train R2 1.00 CV R2 0.75 features used 50 Lasso, alpha=1 train R2 0.99 CV R2 0.94 features used 31 Lasso, alpha=5 train R2 0.98 CV R2 0.97 features used 7 Lasso, alpha=50 train R2 0.59 CV R2 0.44 features used 3
Plain linear regression fits the training data perfectly (1.00) and generalises poorly (0.40): a textbook case of overfitting. Ridge's penalty lifts the cross-validated score to 0.75. Lasso does even better here, because only a few features matter: with alpha=5 it keeps just 7 of the 50 features and reaches 0.97. With alpha=50 the penalty is so strong that the model underfits (0.44). alpha is a hyperparameter, so you choose it with a validation curve or cross-validation, as in Generalisation (RidgeCV and LassoCV do this search for you).
LogisticRegression is regularised by default too. Its setting C works the other way round: smaller C means a stronger penalty. Because the penalty treats every weight alike, regularised models need features on similar scales, so put a StandardScaler in front of them in a pipeline.
What straight lines can't learn
A linear model can only draw straight boundaries. In the data below, class 1 is a small disc of points surrounded by a ring of class 0. No straight line can separate them:
import numpy as np
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
# Class 1 is a small circle inside a ring of class 0: no straight line separates them
X, y = make_circles(n_samples=400, noise=0.1, factor=0.4, random_state=0)
plain = cross_val_score(LogisticRegression(), X, y, cv=5).mean()
radius_squared = (X ** 2).sum(axis=1) # a new feature: x1² + x2²
X_more = np.column_stack([X, radius_squared])
engineered = cross_val_score(LogisticRegression(), X_more, y, cv=5).mean()
print(f"x1 and x2 only: accuracy {plain:.2f}")
print(f"plus x1² + x2² as feature: accuracy {engineered:.2f}")x1 and x2 only: accuracy 0.44 plus x1² + x2² as feature: accuracy 1.00
With only the two coordinates, logistic regression is no better than guessing (0.44). Add one feature, the squared distance from the centre, and the problem becomes a straight-line problem in that feature: "class 1 if the distance is small". Accuracy jumps to 1.00. The model is still linear; the new feature did the bending. PolynomialFeatures creates squares and products of features automatically. When you can't guess the right features, use a model that finds curved patterns by itself, such as the trees in the next lesson.
| Strengths | Weaknesses |
|---|---|
| Fast to train and predict, even with millions of rows | Learn only straight-line patterns, unless you add features |
| Easy to explain: one weight per feature | Squared error makes linear regression sensitive to outliers |
| Work well with very many features, such as the words in a text | Coefficients mislead when features are strongly related |
| Logistic regression gives sensible probabilities | Need scaled features when regularised, and one-hot encoded categories |
Common mistakes
Practice
Make a logistic regression prediction by hand: weighted sum, then the sigmoid, then the threshold.
import math
# A trained logistic regression model for late deliveries
intercept = -4.0
weights = [0.8, 0.5] # for distance (km) and items
order = [6, 3] # a 6 km order with 3 items
# 1. z = intercept + each weight times its feature, added up
# 2. p = 1 / (1 + e to the power -z) (use math.exp)
# 3. the prediction is "late" if p >= 0.5, otherwise "on time"
# Print like: z = 1.00, p = 0.731, prediction: late
z = 0
p = 0
prediction = "on time"
print(f"z = {z:.2f}, p = {p:.3f}, prediction: {prediction}")
Why should you standardise features before comparing the coefficients of a linear model?
Summary
- A linear model predicts with a weighted sum: the intercept plus each feature times its coefficient.
- Logistic regression passes the weighted sum through the sigmoid to get a probability; its decision boundary is where the sum is 0, a straight line.
- Compare coefficients only after standardising the features, and don't read them as causes.
- Ridge shrinks weights and Lasso can remove features entirely; choose their strength, alpha, with cross-validation.
- Straight lines can't separate curved patterns, but new features (such as squares) or a non-linear model can.
Next: Tree-Based Models, which learn by asking yes/no questions.
Finished reading? Tick it off to track your progress.