Lecture 7: Linear Models and Loss Functions

Varada Kolhatkar

Focus on the breath!

Announcements

iClicker: Hyperparameter search recap

search = RandomizedSearchCV(
    make_pipeline(StandardScaler(), SVC()),
    {"svc__C": loguniform(1e-2, 1e2),
     "svc__gamma": loguniform(1e-3, 1e1)},
    n_iter=20, cv=5, random_state=123,
)
search.fit(X_train, y_train)

Select all statements that are true.

  • A. The search samples 20 candidate combinations, each evaluated using five-fold CV.
  • B. For C, the intervals 0.01–0.1, 0.1–1, 1–10, and 10–100 are equally likely.
  • C. By default, the selected pipeline is refitted on all of X_train.
  • D. Increasing n_iter guarantees better performance on new data.

Today’s roadmap

  1. Notation: represent examples, features, and targets.
  2. Linear regression and MSE: predict, then measure error.
  3. Ridge: control complexity with alpha.
  4. Logistic regression and log loss: predict and fit probabilities.
  5. Parametric versus non-parametric: compare what models retain.

Notation

How do we represent data and predictions?

Your turn: Match the notation

Match each symbol to a meaning.

Symbol Meaning (shuffled)
\(X\) A. Number of represented features
\(\mathbf y\) B. Feature matrix
\(\mathbf x_i\) C. Predicted targets
\(\hat{\mathbf y}\) D. Features of example \(i\)
\(n\) E. Observed targets
\(d\) F. Number of examples

Notation: Answers

Symbol Match Meaning
\(X\) B Feature matrix
\(\mathbf y\) E Observed targets
\(\mathbf x_i\) D Features of example \(i\)
\(\hat{\mathbf y}\) C Predicted targets
\(n\) F Number of examples
\(d\) A Number of represented features

From a data table to a matrix

Student Hours studied Practice sets Observed grade
A 5 6 75
B 2 3 62
C 7 5 86

\[X=\begin{bmatrix}5&6\\2&3\\7&5\end{bmatrix}, \qquad \mathbf y=\begin{bmatrix}75\\62\\86\end{bmatrix}\]

  • \(X\): \(n\) examples as rows, \(d\) represented features as columns.
  • Here \(n=3\), \(d=2\); observed targets are separate from \(X\).
  • \(\mathbf x_1=[5,6]^{\mathsf T}\) contains student A’s features; \(\hat{\mathbf y}\) will contain predicted grades.
  • The model receives numerical features produced by our preprocessing.

Your turn: Transpose and shape

\[X=\begin{bmatrix}5&6\\2&3\\7&5\end{bmatrix}, \qquad \mathbf x_1=\begin{bmatrix}5\\6\end{bmatrix}\]

  1. What are the shapes of \(X\) and \(\mathbf x_1\)? Use rows × columns.
  2. Write \(X^{\mathsf T}\) and \(\mathbf x_1^{\mathsf T}\).
  3. Where does student A appear in \(X^{\mathsf T}\)?

Transpose exchanges rows and columns

\[X=\begin{bmatrix}5&6\\2&3\\7&5\end{bmatrix} \quad\longrightarrow\quad X^{\mathsf T}=\begin{bmatrix}5&2&7\\6&3&5\end{bmatrix}\]

\[\underbrace{\mathbf x_1=\begin{bmatrix}5\\6\end{bmatrix}}_{2\times1} \qquad \underbrace{\mathbf x_1^{\mathsf T}=\begin{bmatrix}5&6\end{bmatrix}}_{1\times2}\]

  • \(X\): \(3\times2\); \(X^{\mathsf T}\): \(2\times3\).
  • Student A is row 1 of \(X\) and column 1 of \(X^{\mathsf T}\).
  • In general, transposing an \(n\times d\) matrix gives a \(d\times n\) matrix.

Linear regression and MSE

How do we make predictions and choose a useful model?

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.

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\)

Predictions with multiple features

Feature Value Coefficient Contribution
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.

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\]

  1. What is the shape of \(X\mathbf w\)?
  2. What is the shape of \(\mathbf w^{\mathsf T}\mathbf x_1\), the weighted sum for one student?
  3. 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\).

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.

What happens during fit

Features enter a model; predictions and observed targets enter a loss function; optimization updates the model parameters.

For a linear model, fit learns the coefficients and intercept:

  1. Predict: use candidate parameters to compute \(\hat{y}\) from the training features.
  2. Measure error: compare \(\hat{y}\) with the observed targets \(y\) using a loss function.
  3. Optimize: choose coefficients and an intercept that minimize training loss.

Residuals and squared-error loss

A residual is the observed target minus the prediction: \(y-\hat{y}\).

Observed grade \(y\) Prediction \(\hat{y}\) Residual Squared error
70 68 2 4
70 66 4 16

\[\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.

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.

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}\]

Candidate \(\mathbf w\) \(b\) \(\hat{\mathbf y}=X\mathbf w+b\) MSE
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.

Ridge and model complexity

How can we constrain the fit while keeping the same prediction rule?

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.

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.

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))

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.

iClicker: Exercise 7.1

Select all of the following statements which are TRUE.

    1. Increasing the hyperparameter alpha of Ridge is likely to decrease model complexity.
    1. Ridge can be used with datasets that have multiple features.
    1. With Ridge, we learn one coefficient per training example.
    1. 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.

Break: 5 minutes

Next: keep the weighted sum, but predict classes and probabilities.

Logistic regression and log loss

How does a score become a probability—and what should fitting reward?

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.

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.

Your turn: Trace the city predictions

Using the same cities A, B, and C on the boundary and sigmoid plots:

  1. Which city should have probabilities closest to 0.5?
  2. Predict the sign of each score and the predicted country.
  3. Can a city far from the fitted boundary be confidently misclassified?

Class order: ['Canada', 'USA']. Negative scores favour Canada.

Score z P(Canada) P(USA) Predicted True class
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

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?

iClicker: Ranking prediction penalties

Vancouver is in Canada. Three hypothetical models predict its country.

Illustrative probabilities, not outputs from our fitted cities model.

Regional map showing Vancouver in British Columbia, Canada, north of the border with Washington, USA.
Model \(P(\text{Canada})\) \(P(\text{USA})\)
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.

Log loss: Probability of the true class

\[L=-\log(p_{\text{True class}})\]

For Vancouver, the true class is Canada: select \(P(\mathrm{Canada})\).

Model \(p_{\text{True class}}\) Log loss Interpretation
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.

Log loss penalizes confident mistakes

Increasing the probability assigned to the true class reduces the loss.

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.

Log loss across all examples

Illustrative city predictions, not output from our fitted model.

Example True class \(P(\mathrm{USA})\) \(p_{\text{True class}}\) Loss
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)]\]

Regularization: alpha vs. C

Model Stronger regularization Weaker regularization
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.

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.

Regression and classification: The shared structure

Linear regression Binary logistic regression
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.

Parametric versus non-parametric models

What does a fitted model retain as the training set grows?

Your turn: How many parameters?

  • Imagine you are training a binary logistic regression model. For each of the following scenarios, identify how many parameters (weights and biases) will be learned.
  • Scenario 1: 100 features and 1,000 examples
  • Scenario 2: 100 features and 1 million examples

What does fitting retain?

Linear model \(k\)-NN
For prediction Coefficients and intercept Training examples and targets
More rows, fixed features/classes Parameter values can change; count stays fixed Stored examples grow
Prediction Weighted sum; sigmoid for binary classification Consult nearby examples
Model family Parametric Non-parametric
  • Parametric can still overfit, especially with many features.
  • Non-parametric still has hyperparameters, such as \(k\) and distance choices.

Your turn: More reviews, more coefficients?

A team doubles its text training data and refits:

make_pipeline(CountVectorizer(), LogisticRegression())

The classifier now has more coefficients.

Does this contradict calling logistic regression parametric? What would you check?

More reviews may expand the learned vocabulary, changing the number of features.

Summary

  1. Notation: \(X\) has examples as rows; transpose exchanges rows and columns.
  2. Linear regression: \(\hat{\mathbf y}=X\mathbf w+b\); MSE averages squared residuals.
  3. Ridge: penalize large coefficients; larger alpha means stronger regularization.
  4. Logistic regression: score \(\to\) sigmoid probability \(\to\) class; fit with mean log loss and a penalty. Smaller C means stronger regularization.
  5. Model families: linear-model parameter count stays fixed for fixed features and classes; \(k\)-NN retains training examples.

Coming up: Lecture 8

  • More than two classes: class scores, softmax, and cross-entropy.
  • Different error preferences: MAE versus MSE, logistic versus hinge loss, and a brief look at exponential loss.
  • Inspecting word contributions and coefficients after mixed preprocessing.
  • Bringing the complete supervised-learning workflow together.