Skip to content
mlmentorship

How do you choose a loss function?

Choose a loss from the target, noise model, error cost, and output constraints. A well-trained model still fails when its objective is wrong.

Published · 7 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

How do you choose a loss function?

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Context. Three equally weighted outcomes, 0, 0, and 9, represent the intended population for a constant predictor. Task. Find the best constant under squared and absolute error, compare their objective values, and explain the implied prediction targets. Then distinguish changing a prediction loss from changing the costs of a downstream action. Constraints. Use the same stipulated population and weights for both fits. Neither loss is universally better. A changed decision threshold does not always require retraining the probability model. Predict one constant $a$ for three equally weighted outcomes: $0,0,9$. All three represent the intended population. Find the best constant under squared error and absolute error. Then ask whether changing action costs requires a different prediction model.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Reading depth

Choose a loss by identifying the quantity to predict and separating that estimate from the later deployment decision.

Problem

Context. Three equally weighted outcomes, 0, 0, and 9, represent the intended population for a constant predictor.

Task. Find the best constant under squared and absolute error, compare their objective values, and explain the implied prediction targets. Then distinguish changing a prediction loss from changing the costs of a downstream action.

Constraints. Use the same stipulated population and weights for both fits. Neither loss is universally better. A changed decision threshold does not always require retraining the probability model.

Predict one constant for three equally weighted outcomes: . All three represent the intended population. Find the best constant under squared error and absolute error. Then ask whether changing action costs requires a different prediction model.

Estimate a quantity, then choose an action

The same observations support different prediction targets

A probability of 0.8 does not pick an action without its costs

Probability 0.8 can still favor the negative actionFalse-positive cost is 10; false-negative cost is 1. Expected positive-action cost is 0.2x10=2; expected negative-action cost is 0.8x1=0.8.Width: error chance. Height: errorcost.error chance 0.2error cost 10area 2error chance 0.8error cost 1area 0.8Negative action costs lessCompare actions; do not add theircosts.
Derivation
Loss changes the preferred constant; action costs change the preferred action For the same outcomes zero, zero and nine, constant zero has absolute residuals zero, zero and nine; constant three has residual magnitudes three, three and six. Squaring then averaging gives MSE 27 versus 18, favoring three. Averaging the distances gives MAE 3 versus 4, favoring zero. Each pair of bars shares a zero baseline and scale; MSE and MAE have different units. In a separate binary task with calibrated positive probability 0.8, false-positive cost 9 and false-negative cost 1, positive action costs 1.8 and negative action costs 0.8. The lower-cost action is negative without changing the probability estimate. 1. Same outcomes: 0, 0, 9 a = 0: distances 0, 0, 9 a = 3: distances 3, 3, 6 MSE: square, then average a = 027 a = 318 Minimum at the mean: 3 MAE: average the distances a = 03 a = 34 Minimum at the median: 0 2. Separate binary decision p = 0.8; false positive 9, false negative 1 Positive1.8 Negative0.8 Choose negative: 0.8 < 1.8
Read it this way: lower bars win within each comparison, not across different losses. Squared distances favor 3; absolute distances favor 0. The separate action example chooses negative despite an unchanged positive probability of 0.8.
Check: Why can probability 0.8 favor a negative action under these costs?
Read it this way: False-positive cost is 10; false-negative cost is 1. Expected positive-action cost is 0.2x10=2; expected negative-action cost is 0.8x1=0.8.
Would the same score choose the same action if false-positive cost fell to one?

References: Gneiting and Raftery on proper scoring rules, Huber on robust location, and scikit-learn's threshold guidance.

Calculate both targets

For observations, define and . Here,

Squared error selects , the mean. Absolute error selects , the median.

ConstantMSEMAE

If nine is a genuine costly outcome, discarding it as an outlier changes the task. At each input, squared and absolute loss similarly target conditional means and medians when their risks exist.

Change the requirement

1. Limit contamination influence

New task: nine may be corrupted, and the required output is a robust location.

Picture and change: Huber loss bounds each residual’s gradient. For residual and scale ,

Check: with at , the nine observation contributes gradient , not squared-error gradient . The mean Huber loss here is minimized at because .

Use when: contamination may cause large residuals, rather than a genuine tail needed for mean estimation.

2. Change action costs

New task: false positives cost , false negatives cost , and the calibrated positive probability is . Correct decisions have zero cost.

Picture and change: compare the expected costs of both actions before retraining. Choose positive when

Check: the threshold is . Positive action costs in expectation; negative costs . Choose negative.

Use when: probabilities remain suitable but the cost of acting changes. Capacity and other constraints may require a different decision rule.

Do not treat every score as a probability

Weighted or focal objectives can change score meaning. Check calibration before applying a threshold derived for true probabilities. Focal modulation emphasizes difficult examples; it does not specify which error costs more.

Try increasing the precision requirement

The model already ranks relevant cases well. What changes first?

Check your answer

Test thresholds on representative validation data, separate from final evaluation. Report recall and accepted volume. Retrain only if the resulting operating choices fail the requirement.

Likelihood and output meaning

Negative log likelihood is . Fixed-variance Gaussian likelihood gives squared error up to constants and scale. Fixed-scale Laplace likelihood gives absolute error. Learned scales require their log terms too. These likelihood assumptions are not required merely to target means or medians.

Categorical cross-entropy is for one-hot targets. Squared error on probability vectors can also be a proper Brier score. Gradient problems depend on the output link and parameterization, not just the loss name.

Focal loss multiplies log loss by for the true-class probability . Optional class weights are separate from that modulation; see the original focal-loss paper.

Common follow-up

For a higher precision target, thresholding may suffice. Other options include cost-sensitive retraining, a ranking surrogate, or high-recall retrieval followed by a precision-focused filter. Evaluate representative held-out precision, recall, volume and segment behavior.

Combined objectives

Ranking losses target order; contrastive and triplet losses shape embedding relationships. Multi-task weights change the combined objective. Uncertainty weighting and GradNorm use different weight-selection rules. Auxiliary reconstruction or load-balancing losses also change the optimized objective, even when the main term stays unchanged. Next-token, preference and reward-based training objectives need downstream behavioral evaluation rather than assuming equal loss reductions mean equal improvements.

Related: multi-task learning, cross-entropy and softmax, regularization, and calibration.