Linear regression and MSE
How do we make predictions and choose a useful model?
18 minutes including the connected loss activity. Reuse the student-grade data; prediction first, then a criterion for choosing coefficients.
Learning a prediction function
In supervised learning, we use training examples to learn a function that maps features to a prediction:
\[\mathbf x\ \longrightarrow\ \hat f(\mathbf x)\ \longrightarrow\ \hat y\]
So far, our models have represented this function using:
Decision trees: a sequence of splits.
\(k\) -NN: targets of nearby training examples.
RBF SVMs: flexible decision boundaries.
Linear regression restricts the prediction function to a weighted sum of the represented features plus an intercept.
Keep this introduction to about one minute within the existing 18-minute regression allocation. Training pairs X and y provide examples from which we learn a prediction function; for a new example x, that function produces y hat. Previous model families also impose assumptions, so avoid suggesting they were assumption-free. Here we explicitly restrict the form of the prediction function. This is a modelling choice, not a claim that the true relationship must be linear or every target must lie on a line. Say linear in the represented features, since preprocessing determines those inputs. The next slide makes the restriction concrete with one feature and a straight line. Later, logistic regression keeps the weighted score but applies a sigmoid to obtain a probability.
Linear regression: One feature
Linear regression models a numeric target using a weighted sum of the features and an intercept.
In this case, with only one feature, our model is a straight line.
What do we need to represent a line?
Slope (\(w_1\) ): Determines the angle of the line.
Y-intercept (\(b\) ): Where the line crosses the y-axis.
Making predictions: \(\hat{y} = w_1 \times \text{\# hours studied} + b\)
Let’s start with a numeric target: a quiz grade. Each point shows hours studied and an observed grade. A linear model predicts a grade using a straight line. The slope tells us how much the predicted grade changes for an additional hour; the intercept is the prediction at zero hours. The line does not need to pass through every point. We need a way to choose a useful line, and that will lead us to loss.
Predictions with multiple features
Hours studied (\(x_1\) )
5
4
20
Practice sets (\(x_2\) )
6
2
12
Intercept (\(b\) )
45
The predicted grade is \(20+12+45=77\) .
\[\hat{y}=w_1x_1+\cdots+w_dx_d+b=\mathbf{w}^{\mathsf T}\mathbf{x}+b\]
The dot product means multiply corresponding entries and add .
We learn one coefficient per feature and an intercept, shared across examples.
A coefficient describes the change in the model’s prediction per feature unit, holding other represented features fixed. Interpret this with care: it does not establish causation. Lecture 8 develops interpretation.
With multiple features, the prediction is still a weighted sum. Five hours contributes twenty points, six practice sets contributes twelve, and the intercept adds forty-five. Together, the prediction is seventy-seven. The dot product is just shorthand for multiplying corresponding feature values and coefficients and adding the results. The model learns one shared coefficient per feature, rather than a separate coefficient for each student.
Your turn: What shape is a prediction?
For three students and two features:
\[\underbrace{X}_{3\times2}\quad
\underbrace{\mathbf w=\begin{bmatrix}4\\2\end{bmatrix}}_{2\times1}
\quad b=45\]
What is the shape of \(X\mathbf w\) ?
What is the shape of \(\mathbf w^{\mathsf T}\mathbf x_1\) , the weighted sum for one student?
Do \(\mathbf w^{\mathsf T}\mathbf x_1\) and \(\mathbf x_1^{\mathsf T}\mathbf w\) give the same value? Use \(\mathbf x_1=[5,6]^{\mathsf T}\) .
\((3\times2)(2\times1)\rightarrow3\times1\) : one value per student .
\((1\times2)(2\times1)\rightarrow1\times1\) : one weighted sum . Both dot-product orders give \(32\) .
Allow about ninety seconds before revealing the answers. Both products have shape (1 by d)(d by 1) and produce the same scalar for real vectors: 4×5 + 2×6 = 5×4 + 6×2 = 32. Adding the intercept gives 77. This equality does not mean matrix multiplication can generally be reversed. The inner dimensions must match; the outer dimensions give the result’s shape. For Xw, every row supplies two values to multiply by the same two weights, producing one result per student. For w transpose x_1, the dot product is a scalar, represented here as a 1 by 1 result. Adding b to every entry does not change the shape. The coefficients have shape d by 1 and the intercept is scalar. Ask students to explain the output in words before applying the dimension rule. The next slide computes all three predictions.
One rule for every example
\[\hat{\mathbf y}=X\mathbf w+b
=\begin{bmatrix}5&6\\2&3\\7&5\end{bmatrix}
\begin{bmatrix}4\\2\end{bmatrix}+45
=\begin{bmatrix}77\\59\\83\end{bmatrix}\]
Each row uses the same coefficients and intercept.
\(+b\) means adding the intercept to every prediction.
One feature gives a line; two give a plane; more give a hyperplane.
A coefficient describes a prediction change with other features fixed; interpret it carefully, not as a causal effect .
Give students a moment to calculate the second or third prediction. Briefly mention the coefficient-interpretation caution; details are reserved for lecture 8. For B, two times four plus three times two plus forty-five is fifty-nine. Adding a student adds a row of X and an entry to the prediction vector; it does not add a coefficient. Refitting could change the coefficient values. The intercept addition is shorthand for adding b times a vector of n ones. We will return to the parameter-count question later.
What happens during fit
For a linear model, fit learns the coefficients and intercept :
Predict: use candidate parameters to compute \(\hat{y}\) from the training features.
Measure error: compare \(\hat{y}\) with the observed targets \(y\) using a loss function .
Optimize: choose coefficients and an intercept that minimize training loss.
We know how to make a prediction once we have the weights and intercept. The next question is: how does fit choose those values? For a linear model, these are the parameters we learn from the training data.
Follow the diagram from left to right. With candidate parameter values, the model turns training features into predictions. The loss function compares those predictions with the observed targets and measures their disagreement. Lower loss means better agreement according to that particular loss function. Different losses can favor different predictions.
Optimization chooses coefficients and an intercept that minimize training loss. For linear regression without a penalty, we use squared-error loss.
The loop illustrates an iterative optimizer: predict, measure error, update parameters, and repeat. Some linear models can instead be fitted using direct numerical methods, so not every fit literally follows this loop. Other model families learn differently: k-NN mainly stores training examples, while a decision tree chooses splits. Here we are focusing on how linear models learn their parameters.
During training, observed targets provide the feedback. At prediction time, a new example only follows the features-to-prediction path; we do not need its target. Next, let’s make the loss concrete by looking at residuals and squared error.
Residuals and squared-error loss
A residual is the observed target minus the prediction: \(y-\hat{y}\) .
\[\mathrm{MSE}=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2=\frac{4+16}{2}=10\]
Positive residual: prediction too low. Negative residual: prediction too high.
Optimization chooses coefficients and an intercept to minimize squared-error loss.
Squared error penalizes large prediction errors more heavily than small ones.
A residual is observed minus predicted. Predicting sixty-eight when the grade is seventy gives a residual of two. Predicting sixty-six gives a residual of four. Squaring gives four and sixteen, so the larger mistake contributes disproportionately more. Averaging these squared errors gives an MSE of ten. Squaring also prevents positive and negative residuals from cancelling. Optimization chooses coefficients and an intercept to minimize squared error.
MSE across all three students
Reuse the predictions from \(\hat{\mathbf y}=X\mathbf w+b\) :
\[\mathbf y=\begin{bmatrix}75\\62\\86\end{bmatrix},\quad
\hat{\mathbf y}=\begin{bmatrix}77\\59\\83\end{bmatrix},\quad
\mathbf r=\mathbf y-\hat{\mathbf y}=\begin{bmatrix}-2\\3\\3\end{bmatrix}\]
\[\mathrm{MSE}=\frac{(-2)^2+3^2+3^2}{3}=\frac{22}{3}\approx7.33\]
Each example contributes a squared error; the mean combines all examples into one loss.
Walk from observed targets and predictions to the residual vector. Ask which prediction is too high: the first, because its residual is negative. The squared errors are 4, 9, and 9. Sum all three before dividing by n=3. These are the same students and hypothetical parameters used earlier. This example explains the calculation, not an independent evaluation of a fitted model. No norm notation is needed.
Your turn: Compare two candidates
\[X=\begin{bmatrix}5&6\\2&3\\7&5\end{bmatrix},\qquad
\mathbf y=\begin{bmatrix}75\\62\\86\end{bmatrix}\]
A
\([4,2]^{\mathsf T}\)
45
\([77,59,83]^{\mathsf T}\)
7.33
B
\([3,3]^{\mathsf T}\)
45
\([78,60,81]^{\mathsf T}\)
?
Verify B’s predictions and calculate its MSE. Which candidate results in a lower MSE?
B: \((9+4+25)/3\approx12.67\) . A has lower MSE.
Allow two minutes. Reuse the same three students and two features as the preceding worked example. X has shape 3 by 2; each coefficient vector has shape 2 by 1; b is scalar. For B, multiply each row by [3,3] transpose and add 45 to obtain 78, 60, and 81. Residuals are -3, 2, and 5, giving squared errors 9, 4, and 25. Their mean is 38/3, about 12.67, versus A’s 22/3, about 7.33. B is closer for the second student, but A has lower MSE across all examples. Neither candidate is claimed to be optimal. Fitting compares parameter choices using the aggregate loss, not one student’s error alone.
Ridge and model complexity
How can we constrain the fit while keeping the same prediction rule?
13 minutes including the housing plot and checkpoint. Complete this section before the five-minute break.
Ridge: Loss plus regularization
LinearRegression minimizes squared-error loss.
Large positive and negative contributions can nearly cancel.
With correlated features, small data changes can produce unstable coefficients.
Ridge adds regularization : a penalty that discourages large coefficients.
Fitting balances agreement with training targets against the penalty.
Regularization can reduce overfitting; it keeps the same prediction rule.
Changing regularization does not change the number of coefficients.
In this course, we’ll use Ridge for linear regression.
You will study regularization in more depth in DSCI 573 .
Minimizing training error alone can produce coefficients that are sensitive to the particular training sample, especially when features overlap in the information they provide. Ridge adds a cost for large coefficients. It balances fitting the training targets against keeping coefficients smaller. This can reduce overfitting, although it is not guaranteed to improve every dataset. The prediction rule remains a weighted sum. Ridge will be our standard linear regression estimator in this course.
Regularization and scaling
Larger alpha \(\rightarrow\) stronger regularization \(\rightarrow\) smaller coefficients; greater risk of underfitting.
Smaller alpha \(\rightarrow\) weaker regularization; greater risk of overfitting.
Choose alpha using cross-validation on training data; reserve the test set for final evaluation.
Scale numeric features: their units affect coefficient sizes and hence the penalty.
ridge_pipe = make_pipeline(StandardScaler(), Ridge(alpha= 1.0 ))
cross_validate(ridge_pipe, X_train, y_train)
The pipeline fits the scaler separately within each cross-validation fold.
Ridge minimizes sum_i (y_i - yhat_i)^2 + alpha sum_j w_j^2; the intercept is not penalized. This is a sum of squared errors. With a penalty, changing to a mean requires rescaling alpha to keep the same balance. Larger alpha reduces the coefficient norm, not necessarily every individual coefficient’s absolute value. Effective complexity changes while the feature count and linear prediction form stay fixed.
Increasing alpha makes the coefficient penalty stronger. If it is too strong, the model can underfit; if too weak, it may overfit. We choose alpha using cross-validation on training data. Scaling matters because the same predictive effect can require very different coefficient sizes in different units. The pipeline keeps scaling inside each fold, so the validation fold does not influence the fitted scaler. The code shows evaluating one setting; selecting alpha requires comparing candidate settings.
Housing: A scaled Ridge pipeline
Task: Predict King County house-sale prices from seven numerical features.
Living area, bedrooms, bathrooms, floors, year built, latitude, longitude.
Reserve 20% as test data; compare alpha settings using training-data CV.
Keep scaling inside the pipeline and every CV fold.
ridge_pipe = make_pipeline(StandardScaler(), Ridge(alpha= 1.0 ))
Use this setup only to establish the task for the next plot. These are the chapter’s features and split. Identifiers, sale date, and ZIP code are omitted. The random split illustrates similar sampled sales, not a claim of future forecasting performance. Test data remain untouched. We defer coefficient interpretation and a detailed metrics discussion to lecture 8.
What changes as alpha increases?
Predict first: Must stronger regularization improve validation performance?
Look for a plateau , then underfitting at very large alpha.
Here CV reports \(R^2\) , an evaluation score: larger is better .
Pause before revealing the plot. The numerical-feature housing example has similar training and CV scores across many settings. Stronger regularization provides little improvement here; at very large alpha both scores fall. Do not treat small CV differences as reliable improvements. The prediction rule remains linear throughout. R² is the default regression evaluation score, not the squared-error fitting loss. One is perfect; zero matches the evaluated-data-mean reference. Detailed metric comparisons belong to lecture 8. We have evaluated training folds only and have not used test performance to select settings.
iClicker: Exercise 7.1
Select all of the following statements which are TRUE.
Increasing the hyperparameter alpha of Ridge is likely to decrease model complexity.
Ridge can be used with datasets that have multiple features.
With Ridge, we learn one coefficient per training example.
If you train a linear regression model on a 2-dimensional problem (2 features), the model will learn 3 parameters: one for each feature and one for the bias term.
Select all the true statements, and think about learned parameters versus hyperparameters. [Pause for voting.] A, B, and D are true. Increasing alpha strengthens the penalty and usually reduces effective complexity. Ridge supports multiple features. It learns one coefficient per feature, not per example, so C is false. Two features give two weights and one intercept, for three parameters. Ask yourself whether changing the number of examples would change that count.
Break: 5 minutes
Next: keep the weighted sum, but predict classes and probabilities .
Break at approximately minute 45; resume at minute 50. We have completed notation, regression/MSE, and Ridge. The second half uses the same prediction–loss–regularization structure for classification.
Logistic regression and log loss
How does a score become a probability—and what should fitting reward?
22 minutes: prediction and cities activity about 9; loss and dataset calculation about 10; regularization and checkpoint about 3. No detailed coefficient-interpretation detour.
Logistic regression: Decision boundary
Binary classification: use longitude and latitude to predict Canada or USA.
The black line is the fitted boundary : \(z=\mathbf w^{\mathsf T}\mathbf x+b=0\) . It is not the actual national border.
The model uses standardized coordinates and a fixed default C. These are training examples used to explain the fitted rule, not an independent evaluation. A is the Canadian training example nearest the fitted boundary; B is the Canadian example with the most negative score; C is the most confident mistake among USA training examples. The selection deliberately includes two observed Canada labels and one USA label. Ask students to compare the marked cities with the fitted line and the class markers. A straight line cannot reproduce the geographic border and disconnected regions such as Alaska.
Cities: From scores to probabilities
classes_ = ["Canada", "USA"]: the sigmoid gives \(P(\mathrm{USA})\) .
\(p=P(\mathrm{USA})=\sigma(z)=1/(1+e^{-z})\) . Choose the more probable class.
decision_function returns z; predict_proba returns probabilities in classes_ order; predict returns a class. The sigmoid is nonlinear, but the boundary is still the linear equation z=0. With d features, a nondegenerate boundary has dimension d-1. Negative scores favour Canada, zero gives equal probabilities, and positive scores favour USA. Despite its name, logistic regression is a classifier.
Use the same fitted cities model and the same marked examples A, B, and C as on the boundary plot. The horizontal axis is a weighted score computed from both standardized coordinates, not longitude or latitude alone. The sigmoid maps that score to the probability of classes_[1], which is USA here. A is the Canadian example nearest the boundary, with a score near zero and probability near one half. B and C have negative scores and favour Canada, even though C’s observed label is USA. The vertical dashed line marks score zero, corresponding to the fitted geographic boundary. Ask students which points favour Canada before advancing. More extreme probabilities do not guarantee correctness.
Your turn: Trace the city predictions
Using the same cities A, B, and C on the boundary and sigmoid plots:
Which city should have probabilities closest to 0.5 ?
Predict the sign of each score and the predicted country.
Can a city far from the fitted boundary be confidently misclassified?
Class order: ['Canada', 'USA']. Negative scores favour Canada.
A
-0.188
0.547
0.453
Canada
Canada
B
-2.706
0.937
0.063
Canada
Canada
C
-2.255
0.905
0.095
Canada
USA
Ask for predictions before revealing the table. A has a score near zero and probabilities near one half. C demonstrates that a large probability need not mean a correct prediction. Distance here means perpendicular distance in standardized feature space to the fitted line, not kilometres to the real national border. These selected training examples explain the model; the table is not a validation result.
Loss for logistic regression
We can now predict probabilities. How should fit choose the coefficients?
Could we use mean squared error?
What should a loss reward when the model predicts a probability rather than a numeric target?
Keep this transition brief within the existing 22-minute logistic-regression allocation. Invite initial thoughts, then use the next poll to explore desirable loss behaviour before introducing log loss. Do not suggest that squared error is invalid for probabilities: for a binary label y and probability p, (y-p)^2 is a valid probability loss, commonly called the binary Brier score. Logistic regression conventionally fits using binary cross-entropy plus regularization. Squared error on unrestricted linear scores is a different proposal: those scores can fall outside [0,1] and are not probabilities. We are motivating the loss used by this estimator, not proving that classification admits only one loss. Detailed loss comparisons belong to lecture 8.
iClicker: Ranking prediction penalties
Vancouver is in Canada . Three hypothetical models predict its country.
Illustrative probabilities , not outputs from our fitted cities model.
A
0.50
0.50
B
0.03
0.97
C
0.90
0.10
Which ranking is most appropriate for the penalties these models should receive? Order penalties from smallest to largest .
A. penalty(A) < penalty(B) < penalty(C)
B. penalty(C) < penalty(A) < penalty(B)
C. penalty(B) < penalty(A) < penalty(C)
D. All three receive the same penalty.
We used cities to connect scores, probabilities, and predictions. Now ask what fitting should reward. This poll keeps Vancouver as a concrete city whose observed country is Canada. Three hypothetical models assign different Canada-versus-USA probabilities. The map is context; the model inputs remain coordinates, not map pixels. Map data: Natural Earth, https://www.naturalearthdata.com/about/terms-of-use/ (public domain); country geometries from https://github.com/nvkelso/natural-earth-vector/blob/master/geojson/ne_50m_admin_0_countries.geojson. Vancouver is marked at approximately 49.2827 N, 123.1207 W. Before seeing a formula, choose the most appropriate penalty ranking, from smallest to largest. [Pause for voting.] The answer is option B. Model C puts high probability on the true class, A is uncertain, and model B is confidently wrong. Why should B receive a larger penalty than A? We want the loss to capture that distinction.
Correct answer: B. C < A < B. A is uncertain; B is confidently wrong; C is confidently correct. A’s probabilities are tied, so avoid assigning it a predicted label. After voting, ask students why model B should receive a larger penalty than model A. Option D invites discussion of whether confidence should affect the penalty. Ask students to propose what a loss should reward before introducing the formula.
Log loss: Probability of the true class
\[L=-\log(p_{\text{True class}})\]
For Vancouver , the true class is Canada: select \(P(\mathrm{Canada})\) .
A
0.50
0.69
Uncertain
B
0.03
3.51
Confidently wrong
C
0.90
0.11
Confidently correct
High probability for the true class \(\to\) small loss. We use the natural logarithm .
Connect the formula to the poll’s ranking C < A < B. Only select the probability of the observed class, then take its negative natural log. Probability one for that class gives zero loss; as it approaches zero, loss grows without bound. Unlike accuracy, the loss distinguishes how much probability was assigned to the truth. These three models predict one example; the next dataset calculation instead averages over distinct examples.
Log loss penalizes confident mistakes
Increasing the probability assigned to the true class reduces the loss.
Read the horizontal axis carefully: it is probability of the true class, whether that class is Canada or USA. The vertical axis is the loss for that example. Moving right reduces loss; near zero the curve rises sharply. Our three models sit on this same curve. Notice that there is no special break at one half. Log loss changes continuously with the probability, even when the predicted label stays the same.
Binary cross-entropy (log loss)
Encode Canada as \(y=0\) and USA as \(y=1\) . Let \(p=P(\mathrm{USA}\mid\mathbf x)\) .
\[L=-\left[y\log(p)+(1-y)\log(1-p)\right]\]
True class is Canada (\(y=0\) ): \(L=-\log(1-p)\) .
True class is USA (\(y=1\) ): \(L=-\log(p)\) .
In both cases, this is negative log probability of the true class .
Dataset log loss is the average loss across examples. Logistic regression minimizes training log loss plus a regularization penalty.
Continue the Vancouver example with our cities model’s class encoding. Encode Canada as zero and USA as one, matching classes_ = [Canada, USA]. p is the probability of USA. If Canada is observed, y is zero and the loss uses negative log of 1-p, the probability of Canada. If USA is observed, y is one and the loss uses negative log p. Both cases select the probability of the true class. We average these losses across examples, and logistic regression fits the training data using log loss together with a regularization penalty.
For endpoint probabilities, interpret the formula by limits: probability 1 on the true class gives zero loss; probability 0 on the true class gives infinite loss. The unused term contributes zero.
Log loss across all examples
Illustrative city predictions , not output from our fitted model.
1
Canada
0.20
0.80
0.223
2
Canada
0.30
0.70
0.357
3
USA
0.10
0.10
2.303
\[\text{Mean log loss}=\frac{0.223+0.357+2.303}{3}\approx0.961\]
\[\mathcal L=\frac1n\sum_{i=1}^n L_i
=-\frac1n\sum_{i=1}^n[y_i\log p_i+(1-y_i)\log(1-p_i)]\]
Cover the last two columns verbally first: ask students which probability to use in each row before explaining the losses. Encode Canada as zero and USA as one. The first two examples are Canada: row one uses 1-p=0.8 and row two uses 1-p=0.7. The third is USA and uses p=0.1. Thus two examples require taking the complement of P(USA). The confident mistake dominates the total. Calculations are rounded; the mean using unrounded logarithms is approximately 0.9608. This is loss across three different examples, unlike the preceding three hypothetical models for Vancouver. Logistic fitting minimizes mean training log loss plus a coefficient penalty. As with MSE, low training loss does not establish generalization.
Regularization: alpha vs. C
Ridge
Increase alpha
Decrease alpha
LogisticRegression
Decrease C
Increase C
C controls inverse regularization strength.
Too much regularization can cause underfitting; more is not always better.
Select hyperparameters using cross-validation.
Probabilities and log loss can change even when class predictions and accuracy stay the same.
Both estimators regularize, but their controls point in opposite directions. Larger alpha makes Ridge regularization stronger. Smaller C makes logistic regression regularization stronger, because C controls inverse strength. Think carefully about that direction when tuning. We use cross-validation to choose settings rather than assuming more regularization is always better. Changing regularization can alter the predicted probabilities and log loss even if no examples cross the classification boundary.
iClicker: Exercise 7.2
Select all statements that are true for binary logistic regression.
A. Increasing C strengthens regularization.
B. A score of zero gives classes_[1] probability 0.5.
C. A high predicted probability guarantees the class prediction is correct.
D. A confidently incorrect prediction receives more log loss than a hesitant incorrect prediction.
B and D are true. Larger C weakens regularization. A high predicted probability does not guarantee correctness: the cities example exposed a confident mistake. Confidently wrong means assigning very little probability to the observed class, producing large negative log probability. If votes are split, ask students to explain their reasoning to a neighbour before voting again.
Regression and classification: The shared structure
Shared calculation
\(\mathbf w^{\mathsf T}\mathbf x+b\)
\(\mathbf w^{\mathsf T}\mathbf x+b\)
Output
Numeric prediction
Sigmoid probability → class
Fitting loss
Squared error
Binary cross-entropy
Regularization control
Ridge: alpha
C
Both learn one coefficient per represented feature and an intercept .
Keep this synthesis brief within the logistic section’s 22 minutes. We changed the output interpretation and loss, while retaining the weighted sum. Ridge and logistic regression add a coefficient penalty. Loss is aggregated over training examples; validation checks generalization. Transition: if both models retain coefficients, does doubling the training set double what they must retain?