Lecture 8: Loss Functions, Model Interpretation, Multiclass Classification

Varada Kolhatkar

Focus on the breath!

Announcements

iClicker: Lecture 7 recap

Let \(z=\mathbf w^{\mathsf T}\mathbf x+b\) and \(p=\sigma(z)=1/(1+e^{-z})=P(y=1\mid\mathbf x)\).

Which statements are true? Select all that apply.

  • A. If \(z=0\), then \(p=0.5\); increasing \(z\) increases \(p\).
  • B. The sigmoid converts the score directly into a class label.
  • C. For a true label \(y=1\), increasing \(p\) from \(0.6\) to \(0.9\) reduces log loss.
  • D. A correct class prediction always has zero log loss.
  • E. Mean squared error gives larger errors disproportionately more weight than smaller errors.

Today’s roadmap

  1. More loss functions: regression, classification, fitting versus evaluation
  2. Model interpretation: coefficients and feature contributions
  3. Multiclass classification: class scores, softmax, and cross-entropy
  4. Conclusions: overall workflow, ML course map, and what comes next

More loss functions

How does the choice of loss change what fitting rewards?

How strongly should a large error count?

Your turn: Delivery-time predictions

Residual \(r_i=y_i-\hat y_i\), in minutes.

Model Residuals on four validation deliveries
A 0, 0, 0, 8
B 3, 3, 3, 3

\[\operatorname{MAE}=\frac1n\sum_i|r_i|, \qquad \operatorname{MSE}=\frac1n\sum_i r_i^2\]

  1. Calculate MAE and MSE for both models.
  2. Which model does each metric favour?

MAE and MSE can rank models differently

Model MAE (minutes) MSE (minutes squared)
A: 0, 0, 0, 8 2 16
B: 3, 3, 3, 3 3 9
  • MAE favours A: every additional minute counts equally.
  • MSE favours B: the 8-minute error contributes \(8^2=64\).
  • Doubling a residual doubles absolute loss and quadruples squared loss.

Absolute and squared loss

Squared loss gives large errors relatively more influence.

Choosing MAE or MSE

MAE MSE
Penalty Grows linearly with error size Grows quadratically with error size
Use when… Each extra unit of error costs the same Large errors are disproportionately costly
Extreme errors Less sensitive Can dominate the loss
Units Same as the target Squared target units
Optimization Corner at zero Smooth and differentiable

Choose based on the cost of errors in your application.

Classification losses

Logistic loss in terms of the score

Fix a review whose true sentiment is positive (\(y=1\)).

\[z=\mathbf w^{\mathsf T}\mathbf x+b, \qquad p=P(y=1\mid\mathbf x)=\sigma(z)=\frac{1}{1+e^{-z}}\]

Substitute the sigmoid into the familiar log loss:

\[L=-\log(p)=-\log\left(\frac{1}{1+e^{-z}}\right) =\log(1+e^{-z})\]

Increasing \(z\) increases the true-class probability and reduces loss.

Linear SVM and hinge loss

Both models compute \(z=\mathbf w^{\mathsf T}\mathbf x+b\).

  • Same class decision rule: positive scores favour class 1; negative scores favour class 0.
  • Different fitting losses: they can learn different coefficients and biases.

For this positive review (\(y=1\)):

\[L_{\text{logistic}}=\log(1+e^{-z}), \qquad L_{\text{hinge}}=\max(0,1-z)\]

Hinge loss remains positive for \(0<z<1\), even though the class prediction is correct.

Hinge loss vs. logistic loss

Hinge loss and support vectors

  • Hinge loss focuses fitting on examples that are misclassified or close to the decision boundary, connecting to the support vectors we saw earlier.
  • For this positive review, once \(z \geq 1\), the loss is zero: pushing its score higher brings no further benefit.

Exponential loss

For the same positive review (\(y=1\)), another alternative is:

\[L_{\text{exponential}}=e^{-z}\]

  • Negative scores are wrong for this review; their penalty grows exponentially as \(z\) decreases.
  • Positive scores reduce the loss toward zero, without reaching zero at any finite score.
  • Exponential loss connects to AdaBoost, coming in DSCI 573.

Comparing classification losses

Hinge loss reaches zero at \(z=1\). Exponential loss penalizes strongly wrong scores most sharply.

Classification losses: Behaviour and uses

Logistic Hinge Exponential
Emphasis True-class probability Correct class with sufficient separation Strong penalty for confidently wrong scores
Zero loss (\(y=1\)) Approaches zero Zero at \(z\geq1\) Approaches zero
Typical use Logistic regression; probabilities SVMs; class decisions AdaBoost and related boosting methods

Loss choice usually comes through choosing a model or algorithm.

iClicker: Correct prediction, positive loss?

A truly positive review receives score \(z=0.5\).

Which statements are true? Select all that apply.

  • A. Its predicted class is positive.
  • B. Its hinge loss is zero.
  • C. Its hinge loss is 0.5.
  • D. Increasing this review’s score from \(0.5\) to \(1.5\) reduces both its hinge loss and its logistic loss.

Fitting loss and evaluation measures

How we learn parameters and how we assess predictions

Fitting versus evaluation

During fitting During evaluation
Question Which parameters should the model learn? How well does the model predict held-out examples?
Data Training data Validation or test data
Measure The estimator’s fitting loss A measure chosen for the application
Logistic regression example Minimize log loss plus regularization Assess accuracy, log loss, or both

The fitting loss and evaluation measure can be the same or different.

Evaluating logistic regression

Every candidate is fitted using log loss plus regularization.

We can compare candidates on validation data using:

  • Accuracy: how often is the predicted class correct?
  • Log loss: how much probability is assigned to the true class?

Changing the evaluation measure changes how we rank candidates, not how each candidate fits its parameters.

Accuracy and log loss capture different changes

For a truly positive review, compare two predictions:

\(P\)(positive) Predicted class Correct? Log loss
0.20 Negative No 1.609
0.30 Negative No 1.204
  • Accuracy is unchanged: both class predictions are wrong.
  • Log loss improves: the true class receives more probability.

Your turn: Which model wins?

Two logistic-regression candidates, each fitted using log loss plus regularization.

C Mean validation accuracy ↑ Mean validation log loss ↓
0.1 0.96 0.12
10 0.97 0.18
  1. Which candidate wins if we evaluate using accuracy? Using log loss?
  2. Does changing the evaluation measure change either candidate’s fitting loss?

Course evaluations (~10 minutes)

  • The online course evaluations are up, it’ll be great if you can fill them in when you get a chance.

Model interpretation

How do coefficients and feature values combine in a prediction?

Sentiment analysis example

  • Logistic regression learns coefficients for each word from training data.
  • Positive coefficients \(\rightarrow\) push prediction toward positive class.
  • Negative coefficients \(\rightarrow\) push prediction toward negative class.
  • In this example, positive words (fun, rewarding) outweigh the negative word (long), so the overall sentiment is likely positive.

Interpretation of coefficients

Class demo

Multiclass classification

One example, one label, several possible classes

Penguin species

Chinstrap, Gentoo, and Adelie penguins

  • Inputs: bill length, bill depth, flipper length, body mass
  • Target: Adelie, Chinstrap, or Gentoo
  • Multilabel tasks allow several labels for one example, such as “penguin” and “snow”.

One linear score per class

\[z_k=\mathbf w_k^{\mathsf T}\mathbf x+b_k\]

  • Each class \(k\) has its own coefficients and intercept.
  • \(\mathbf x\) contains the preprocessed measurements.
  • Scores can be any real numbers. They do not yet form probabilities.

For one illustrative penguin:

Adelie Chinstrap Gentoo
\(z_1=2\) \(z_2=1\) \(z_3=0\)

Softmax: Scores to probabilities

\[p_k=\frac{e^{z_k}}{\sum_{j=1}^{K}e^{z_j}}\]

Species Score Exponentiate Normalize
Adelie 2 7.389 0.665
Chinstrap 1 2.718 0.245
Gentoo 0 1.000 0.090
Total 11.107 1.000

All probabilities are positive and sum to 1.

Your turn: Softmax predictions

Class order: Adelie, Chinstrap, Gentoo.

  1. A model returns \((0.40, 0.35, 0.25)\). Which class does it predict?
  2. Must the winning probability exceed 0.5?
  3. What probabilities result if all three scores are equal?
  4. Would adding 100 to every score change the probabilities?

Cross-entropy loss

How much probability did the model assign to the true class?

One-hot targets and cross-entropy

True species: Chinstrap. Class order: Adelie, Chinstrap, Gentoo.

\[\mathbf y=\begin{bmatrix}0 \\ 1 \\0\end{bmatrix}, \qquad \hat{\mathbf p}=\begin{bmatrix}0.1\\0.8\\0.1\end{bmatrix}\]

\[L=-\sum_{k=1}^{K} y_k\log(\hat p_k) =-\log(\hat p_{\text{true class}})\]

\[L=-[0\log(0.1)+1\log(0.8)+0\log(0.1)]\approx0.223\]

Binary and multiclass log loss

For two classes, the target indicators are \(y\) and \(1-y\):

\[L=-[y\log(\hat p)+(1-y)\log(1-\hat p)]\]

For \(n\) examples and \(K\) classes, average the losses:

\[\overline L=-\frac1n\sum_{i=1}^n\sum_{k=1}^K y_{ik}\log(\hat p_{ik})\]

  • High probability for the true class gives low loss.
  • A confident wrong prediction can receive a very large loss.

iClicker: Is a log loss of 1.10 good?

A three-class model has mean validation log loss 1.10. (\(-log(1/3) = 1.09\))

Which statement is best supported?

  • A. The model is useful because 1.10 is close to zero.
  • B. The model performs about the same as this baseline.
  • C. The model has about 110% classification error.
  • D. We cannot compute the baseline loss without its accuracy.

Penguins: A complete prediction pipeline

penguin_pipeline = make_pipeline(
    SimpleImputer(strategy="median"),
    StandardScaler(),
    LogisticRegression(solver="lbfgs", max_iter=1000),
)
  • Reserve a test set first.
  • Compare with DummyClassifier() using training-data CV.
  • Keep imputation and scaling inside the pipeline.
  • Inspect both accuracy and log loss. Leave test data untouched.

Penguins: Validation results

Mean CV accuracy Mean CV log loss
Model
Class-proportion baseline 0.442 1.049
Logistic regression 0.977 0.068
  • Accuracy evaluates class decisions.
  • Log loss evaluates probability predictions.
  • Both improve relative to the class-proportion baseline here.

Same class prediction, different probabilities

Model \(P\)(Adelie) \(P\)(Chinstrap) \(P\)(Gentoo)
A 0.40 0.35 0.25
B 0.90 0.05 0.05
  1. What class does each model predict?
  2. Which has lower log loss if the true class is Adelie?
  3. Which has lower log loss if it is Chinstrap?
  4. Can accuracy distinguish the models on this example?

Course conclusions

The pieces form one supervised-learning workflow

Overall workflow: Development

  1. Define the task: target, examples, available inputs, intended use.
  2. Reserve test data: choose a split that matches the prediction setting.
  3. Explore training data: missingness, unusual values, possible leakage.
  4. Build pipelines: numerical, categorical, and text preprocessing.
  5. Compare with a baseline: consistent CV splits and suitable measures.
  6. Tune promising models: select using training-data validation results.

Overall workflow: Interpretation and evaluation

  1. Inspect the model and its mistakes. Check feature contributions and limitations.
  2. Evaluate the selected workflow on test data. Settle development choices first.
  3. Communicate the evidence. Report the baseline, evaluation procedure, and limitations.

If inspection suggests changes, return to training-data development.

Your turn: Review this workflow

A team routes support requests to three departments. It:

  • Includes the department that eventually resolved each request as an input.
  • Learns the text vocabulary from all requests before splitting.
  • Tries many values of C and selects the best test accuracy.
  • Claims that accuracy shows its probabilities are reliable.

What would you change?

What you can do now

  • Build a complete pipeline for numerical, categorical, and text inputs.
  • Compare model families against a baseline without test leakage.
  • Use validation to choose hyperparameters and representations.
  • Explain how scores, probabilities, losses, and predictions relate.
  • Inspect a fitted model and communicate what its evidence supports.

ML course map

MDS machine-learning course map connecting supervised learning, optimization, unsupervised learning, and advanced topics

What’s coming in DSCI 573

Question Topic
Do different mistakes have different costs? Evaluation metrics
Can combining models improve predictions? Ensembles
How can we control model flexibility? Regularization
How can we explain more complex models? Transparency and SHAP
How can we represent inputs more usefully? Feature engineering
Which inputs should we retain? Feature selection

Thank you!!

I hope you learned something useful from the course. You all are wonderful students and I had fun teaching this course ♥️!

FYI: If you didn’t fill out course evaluations during class , it’ll be great if you can fill them in when you get a chance.