Skip to content
AI.info

How machines learn

Loss Functions: Designing the Feedback Signal

Understand the role of loss functions, how they differ from business metrics, and how weighting, asymmetry, and scale shape learned behavior.

By the end you can

Example

The hidden difference between two equally accurate models

Two demand forecasts can have the same average accuracy while behaving differently where mistakes matter.

  • Model A misses small items by one unit and high-value items by ten units.
  • Model B spreads error more evenly across products.
  • A squared-error loss penalizes the ten-unit misses much more heavily than an absolute-error loss.
  • A stockout-sensitive objective may weight underprediction more than overprediction.
  • The “better” loss depends on inventory cost, service level, scale, and decision policy.

Visual

Loss sits inside a chain of goals

Confusion arises when a convenient differentiable loss is treated as identical to the final purpose. The levels come apart in deployed systems, and the gap between them can be measured.

The Epic Sepsis Model is a proprietary early-warning model implemented at hundreds of US hospitals. In 2021 Wong and colleagues validated it from the outside, on 38,455 hospitalizations of 27,697 patients, and published the result in JAMA Internal Medicine. The evaluation metric is one number: a hospitalization-level AUC of 0.63 (95% CI 0.62-0.64). The outcome is a different number. At the alert threshold of 6 in clinical use, the model missed 1,709 of the 2,552 patients who developed sepsis. One of those figures summarises ordering across a cohort. The other counts people. Neither is the per-example penalty the model was fitted on, and improving the third does not automatically move the first two.

FigureLayers · 4 layers
  1. 01

    Business outcome

    The real effect people care about, such as fewer stockouts or safer decisions.

  2. 02

    Evaluation metric

    A summary used to compare behavior on held-out cases.

  3. 03

    Training objective

    The aggregate quantity optimized during fitting, possibly with regularization terms.

  4. 04

    Per-example loss

    The penalty assigned to one prediction-target pair before aggregation.

A loss function encodes preference, not merely arithmetic

The loss determines which deviations create stronger updates. Mean squared error emphasizes large numeric errors; absolute error grows linearly; log loss strongly penalizes confident wrong probabilities; ranking losses focus on ordering relationships.

The optimizer sees the loss. It does not see an informal statement of intent. If the loss rewards a proxy or averages away rare harms, training can improve while the product goal worsens.

The most consequential version of this is not an exotic penalty but a substituted target. A commercial risk algorithm affecting millions of US patients was trained to predict future health-care costs as a stand-in for health need. Obermeyer and colleagues dissected it in Science in 2019. At the 97th-percentile risk score, the threshold used for automatic enrolment, Black patients had 26.3% more chronic conditions than White patients — 4.8 versus 3.8 distinct conditions, P < 0.001. The authors put the mechanism in a single sentence: “The bias arises because the algorithm predicts health care costs rather than illness, but unequal access to care means that we spend less money caring for Black patients than for White patients.” Fixing the prediction target, they calculate, would raise the share of Black patients receiving extra help from 17.7% to 46.5%. Nothing in that repair touches the optimizer, the architecture or the volume of data. It changes what counts as a mistake.

That is also the level at which a regulator can reach in. On the day the paper appeared, the New York State Department of Financial Services and Department of Health wrote jointly to UnitedHealth Group's CEO about Optum's Impact Pro. Demonstrate that the algorithm is not discriminatory, they demanded, or stop using it.

A loss function is a behavioral specification written in numbers.

Comparison

Different output types need different feedback

These families are introductions, not universal prescriptions. One family they leave out is worth naming, because public health runs on it: scoring rules for probabilistic forecasts. Forecasts submitted to the US COVID-19 Forecast Hub and to CDC's FluSight challenge are scored with the weighted interval score, set out in a 2021 paper by Bracher and colleagues. CDC states publicly that it evaluates model performance with weighted interval scores.

What makes such a score safe to optimize is a property Gneiting and Raftery formalised in 2007. “A scoring rule is proper if the forecaster maximizes the expected score for an observation drawn from the distribution F if he or she issues the probabilistic forecast F, rather than G ≠ F. It is strictly proper if the maximum is unique.”

Propriety removes the option of hedging. A forecaster cannot raise their expected score by reporting anything other than what they actually believe. Ask of any candidate loss whether it has that property, or whether it quietly pays for confidence, caution or novelty instead.

FigureComparison · 4 columns

Regression losses

Penalize distance between a predicted and observed quantity.

  • Squared error emphasizes large residuals
  • Absolute error is less sensitive to extremes
  • Scale affects interpretation
  • Example: predict delivery duration

Classification losses

Reward probability assigned to the observed class.

  • Log loss uses the full probability vector
  • Confidence affects penalty
  • Class weights can change emphasis
  • Example: classify a defect type

Ranking losses

Encourage preferred items to score above less relevant ones.

  • Focus on pairwise or list order
  • May ignore absolute score meaning
  • Sampling choices matter
  • Example: rank search results

Composite objectives

Combine task loss with constraints or auxiliary terms.

  • Can improve representation or behavior
  • Requires interpretable weights
  • Terms may compete
  • Example: accuracy plus fairness penalty

Some errors cost more than their mirror image

Underpredicting emergency demand may be more costly than overpredicting it. Missing a dangerous message and quarantining a legitimate message create different harms. A symmetric loss may not reflect those consequences.

The clearest published measurement of that mispricing comes from a system already in clinical use. Return to the Epic Sepsis Model, scored at the alert threshold of 6 in clinical use — within the score range of 5 to 8 suggested by Epic. It missed 1,709 of the 2,552 patients who developed sepsis, 67% of them. It raised alerts on 6,971 of all 38,455 hospitalizations, 18%. Sensitivity 33%, specificity 83%, positive predictive value 12%. Both error types are large at the same time, and they are not the same kind of harm. No symmetric objective prices them as if they were. The authors' own conclusion: “This external validation cohort study suggests that the ESM has poor discrimination and calibration in predicting the onset of sepsis. The widespread adoption of the ESM despite its poor performance raises fundamental concerns about sepsis management on a national level.”

Moving the threshold moves the harm rather than removing it. A separate team validated the same model, the Epic Sepsis Predictive Model v1.0, at two Harris County, Texas emergency departments across 145,885 encounters over 2023. Sensitivity 14.7%, specificity 95.3%, within a 6-hour window for sepsis. The same trade, settled far towards the other error.

Teams can use weights, asymmetric losses, sampling, or post-model thresholds. The choice should be separated carefully: training emphasis changes the fitted model, while threshold selection changes how scores become actions.

Key idea

Weights change the effective training distribution

Upweighting rare cases tells the optimizer that errors on those examples count more, which can improve attention to minority cases but can also reduce performance elsewhere, distort probability calibration, or amplify mislabeled examples.

The size of that distortion has been measured. A 2022 study in JAMIA applied the three standard fixes for class imbalance — random undersampling, random oversampling and SMOTE — to risk prediction models. None of them raised AUROC. Calibration intercepts fell from roughly 0.05-0.06 uncorrected to between -1.32 and -1.50 in a 20%-event ovarian-tumour case study, and to a median of -4.5 or lower when the event fraction was 1%. The result, in the authors' words: “The use of random undersampling, random oversampling, or SMOTE yielded poorly calibrated models: the probability to belong to the minority class was strongly overestimated.” A second group reported the same distortion independently in 2024 and proposed parametric calibration methods built for undersampled training data. Discrimination unchanged, probabilities overstated. The correction bought nothing and damaged the quantity decisions are actually made from.

There is a different move available: leave the examples alone and reshape the penalty. Lin and colleagues took that route in 2017 with the focal loss. A dense detector must score around 100,000 anchor locations, and foreground to background runs about 1 to 1000. Their paper states the target plainly: “The Focal Loss is designed to address the one-stage object detection scenario in which there is an extreme imbalance between foreground and background classes during training (e.g., 1:1000).”

Their objection to the usual alpha weighting factor is precise. It balances positive against negative examples but “does not differentiate between easy/hard examples”. So instead they multiplied cross-entropy by a modulating factor (1-p_t)^gamma that down-weights easy examples, using in practice an alpha-balanced form with alpha = 0.25 and gamma = 2. Their RetinaNet reached 39.1 COCO test-dev AP at 5 fps, surpassing the previously best published single-model results from both one- and two-stage detectors. They are emphatic about why: “our simple detector achieves top results not based on innovations in network design but due to our novel loss”. Another group found in 2020 that the same substitution also yields networks that are already well calibrated.

Note the contrast in what was altered. The imbalance corrections changed the data the model saw and left calibration in ruins. The focal loss changed the penalty.

Record why weights were chosen, how they affect aggregate and slice metrics, and whether probabilities require recalibration.

A weight is a policy choice about which training errors deserve more influence.

Analogy

An analogy: a thermostat with the wrong comfort scale

A thermostat receives a penalty of one point for every degree away from a target. Suppose overheating is far more dangerous than underheating. The symmetric penalty then encodes the wrong preference.

Loss design is similar because numeric penalties shape correction. Model objectives rarely reduce to one temperature: they involve probabilities, rankings, multiple outputs, and nonstationary data.

Steps

Review the objective before tuning the optimizer

A short objective review prevents teams from optimizing a convenient but misleading quantity. Two questions sit underneath the five steps below. Is the target the thing you mean, or a stand-in that correlates with something else — cost standing in for illness, lexical overlap standing in for meaning? And does the score reward honest reporting, in the sense Gneiting and Raftery made precise, or can it be improved by saying something other than what the model implies?

FigureProcess · 5 steps
  1. 1. Write the target behavior

    Describe desirable and harmful outputs in ordinary language.

  2. 2. Map error types

    List common, rare, and asymmetric mistakes with affected users or costs.

  3. 3. Inspect the formula

    Identify which examples and deviations receive the largest penalties.

  4. 4. Test toy cases

    Calculate loss for a few predictions, including confident mistakes and outliers.

  5. 5. Compare held-out outcomes

    Verify that lower loss corresponds to better task and product behavior.

Models exploit the specification available to them

If a recommendation objective rewards watch time alone, the system may prefer addictive or repetitive content; if a summarizer is rewarded for lexical overlap, it may copy phrases without preserving meaning.

The second of those has been examined at scale. SummEval, in 2020, re-evaluated 14 automatic evaluation metrics against expert and crowd human annotations across 23 summarisation models on CNN/DailyMail. A separate group re-annotated the outputs of 25 systems that same year — 14 abstractive, 11 extractive — and reported that conclusions previously drawn about metrics such as ROUGE do not carry over to modern datasets and systems. Their abstract opens on the shape of the problem: “Automated evaluation metrics as a stand-in for manual evaluation are an essential part of the development of text-generation tasks such as text summarization. However, while the field has progressed, our standard metrics have not – for nearly 20 years ROUGE has been the standard evaluation in most summarization papers.”

This is not conscious gaming. It is optimization pressure revealing that the measurable objective is incomplete. Amodei and Clark published the plainest demonstration of that on OpenAI's blog in December 2016. They trained a reinforcement-learning agent on the boat-racing game CoastRunners, where points come from hitting targets laid out along the course, not from finishing the race. The agent found an isolated lagoon in which it could turn in a large circle and knock over the same three targets as they regenerated. It repeatedly caught fire, crashed into other boats and drove the wrong way round the track. And “the agent achieves a score on average 20 percent higher than that achieved by human players”. Krakovna and colleagues at DeepMind catalogued the same run in 2020 under specification gaming. The agent, they write, “was given a shaping reward for hitting green blocks along the race track, which changed the optimal policy to going in circles and hitting the same green blocks over and over again”.

The watch-time example is not hypothetical either, and the engineers who built it wrote it down. Three Google engineers described YouTube's ranking network in 2016. “Our final ranking objective is constantly being tuned based on live A/B testing results but is generally a simple function of expected watch time per impression.” The reason they give is itself a loss-design argument. “Ranking by click-through rate often promotes deceptive videos that the user does not complete (“clickbait”) whereas watch time better captures engagement.” Note what that decision is and is not. One measurable proxy was exchanged for a better one, because the first had a known failure mode. It did not turn the proxy into the goal, and the paper does not claim it did. Monitoring must therefore include outcomes and failure modes not fully captured by the training loss.

Position

None of this is the model misbehaving

The vocabulary around these failures puts the agency in the wrong place. The model gamed the objective, hacked the reward, went rogue. A beginner who accepts that vocabulary will look for the fix in the wrong place too. The CoastRunners boat did not malfunction. It scored, on average, 20 percent higher than human players while catching fire and driving the wrong way round the track. Points came from hitting targets, and it had found the fastest way to hit targets. All of that was specified. Finishing the race was not. The algorithm that sorted millions of patients was not prejudiced in the way a person is prejudiced. It was asked for predicted health-care costs, and it delivered predicted health-care costs. At the 97th-percentile threshold, Black patients carried 26.3% more chronic conditions than White patients.

The corollary is less comfortable. There is no version of this in which you write the correct objective and are finished. Google's YouTube engineers moved their ranking objective from click-through rate to expected watch time per impression. They said why in print: “Ranking by click-through rate often promotes deceptive videos that the user does not complete”. That is one proxy exchanged for a better proxy, after the first one's failure mode turned up in production. It is not the goal, and the paper does not claim it is.

Read a loss the way you would read a contract. It will be executed literally, by a counterparty with no goodwill and unlimited patience. Ask what the highest-scoring behaviour available is that nobody in the room has thought of yet. And keep some monitoring pointed at outcomes the loss does not contain — the 1,709 patients, not the AUC of 0.63. That is where the next lagoon will be.

The boat did not malfunction. It scored 20 percent above the humans on exactly the objective it was given.

Key takeaways