Machine LearningCost Functions and Optimization

What Properties Should a Good Cost Function Have?

Question 298 of 303 · Updated

On this page

A cost function (or loss function) measures how poorly a machine-learning model's predictions match the desired outcomes. During training, an optimizer adjusts model parameters to reduce the average cost.

A good cost function should make better predictions score better, reflect the real consequences of mistakes, and be practical to optimize. Properties such as differentiability and convexity are valuable in many settings, but they are not universal requirements. The right loss depends on the task, model, data, and optimization method.

1. It should measure prediction error meaningfully#

The loss should assign a low value to predictions that are good for the task and a higher value to predictions that are bad. Ideally, the minimum corresponds to the desired prediction.

For a regression example, a common per-example loss is squared error:

L(y, ŷ) = (y - ŷ)²

where y is the true target and ŷ is the model prediction.

If the actual house price is ₹50 lakh:

  • Prediction ₹50 lakh → loss = 0
  • Prediction ₹48 lakh → loss = 4 (lakh²)
  • Prediction ₹40 lakh → loss = 100 (lakh²)

The cost increases as the prediction moves farther from the target. However, the exact penalty shape is a design choice: absolute error penalizes deviations linearly, while squared error penalizes large deviations more heavily.

2. It should have a meaningful minimum#

For many supervised-learning tasks, losses are designed to be non-negative and to reach zero for a perfect prediction. This makes the value easy to interpret.

Examples:

  • Mean Squared Error (MSE) is zero when every prediction equals its target.
  • Mean Absolute Error (MAE) is zero under the same condition.
  • Cross-entropy approaches zero when the model assigns probability one to the observed class.

Non-negativity and a zero minimum are useful conventions, not strict mathematical requirements for every objective. Some objectives include constants, rewards, log-likelihoods, or regularization terms and can legitimately take negative values. What matters is that the objective is correctly defined and its minimizer represents the intended goal.

3. It should be suitable for optimization#

A model learns by changing its parameters to reduce the cost. Therefore, the loss should work well with the optimizer being used.

For gradient-based training, it is helpful if the loss is differentiable, or at least has usable gradients or subgradients.

For squared error:

[ L(y,hat y)=(y-hat y)^2 ]

The derivative with respect to the prediction is:

LaTeX

This tells gradient descent how the prediction should move to reduce the loss.

But differentiability everywhere is not mandatory:

  • MAE has a non-differentiable point when prediction equals target, but subgradient methods handle it.
  • Hinge loss is non-differentiable at its margin boundary and is still widely used.
  • Some black-box optimization methods do not require gradients.

The practical requirement is compatibility with the training algorithm and a useful optimization signal.

4. Convexity is desirable when available, but not compulsory#

A convex function has a useful property: every local minimum is also a global minimum. This makes optimization easier to reason about and provides stronger theoretical guarantees.

For a differentiable convex objective, a point with zero gradient is a global minimizer.

Ordinary least-squares regression with a linear model is convex in its parameters. Logistic regression with the usual cross-entropy objective is also convex for a linear predictor.

Deep neural networks, however, generally produce non-convex objectives. They can still be trained successfully with gradient-based optimizers such as SGD and Adam.

So a good cost function should be as tractable as the problem allows. Convexity is a major advantage, not a universal condition for a useful loss.

5. It should reflect the real cost of different mistakes#

Not all prediction errors have equal consequences.

Imagine a fraud detection model:

  • Missing a fraudulent transaction may cause financial loss.
  • Incorrectly flagging a legitimate transaction may inconvenience a customer and create review costs.

A plain average loss may treat these mistakes symmetrically, even when the business does not.

Possible approaches include:

  • Weighted loss: assign different weights to classes or observations.
  • Cost-sensitive loss: encode the relative cost of false positives and false negatives.
  • Focal loss: emphasize difficult or misclassified examples in certain classification settings.
  • Quantile loss: target a particular conditional quantile rather than the mean.

The loss should reflect the decision problem. A metric that looks mathematically attractive can still train the wrong behavior if it does not match the real objective.

6. It should behave sensibly in the presence of outliers#

A cost function determines how strongly unusual examples influence training.

Compare two common regression losses:

Squared error: L = e²
Absolute error: L = |e|

For residuals of 2 and 10:

  • Squared error gives 4 and 100.
  • Absolute error gives 2 and 10.

Squared error gives the large residual much more influence. This can be desirable when large errors are especially costly, but problematic when extreme values are measurement errors or unrepresentative observations.

Robust alternatives such as Huber loss use a quadratic penalty for small residuals and a linear penalty for large residuals. This can balance smooth optimization with reduced sensitivity to extreme errors.

Robustness is not always the goal: if rare extreme events are important, suppressing their influence may be undesirable.

7. It should be numerically stable and computationally practical#

Training can involve millions of examples, high-dimensional outputs, and very large or very small predicted values. A useful loss should be implementable without avoidable numerical failures.

For example, binary cross-entropy contains logarithms:

[ L(y,p)=-[ylog(p)+(1-y)log(1-p)] ]

Directly evaluating log(0) is undefined. In practice, implementations use numerically stable formulas and logits-based versions, and handle finite-precision arithmetic carefully.

Other practical considerations include:

  • computational cost per training example;
  • stable gradients across the expected prediction range;
  • sensible behavior with mixed precision;
  • support for batching and vectorized computation;
  • predictable behavior when labels are missing or masked.

A theoretically elegant loss is less useful if it is prohibitively expensive or unstable in the actual training pipeline.

8. It should support the right statistical behavior#

A loss function determines what prediction the model is encouraged to learn.

For example:

  • Squared-error loss targets the conditional mean under standard conditions.
  • Absolute-error loss targets a conditional median.
  • Quantile loss targets a chosen conditional quantile.
  • Proper scoring rules such as log loss encourage truthful probability estimates in expectation.

This matters because the most useful prediction is not always the average. A delivery company may care about the 90th-percentile delivery time to plan service guarantees, while a demand forecast may care about the expected demand.

For probabilistic classification, cross-entropy is often useful because it evaluates predicted probabilities, not just the final class label.

9. It should match the task and avoid optimizing the wrong metric#

Different machine-learning tasks need different objectives.

  • Regression: MSE, MAE, Huber loss, quantile loss.
  • Binary or multiclass classification: binary or categorical cross-entropy.
  • Margin-based classification: hinge loss.
  • Imbalanced classification: weighted cross-entropy or focal loss, depending on the goal.
  • Ranking: pairwise or listwise ranking losses.
  • Metric learning: contrastive loss or triplet loss.

Some evaluation metrics, such as accuracy, F1-score, and AUC, are not generally convenient direct training losses. They can be discontinuous or non-differentiable with respect to model scores. A differentiable surrogate is often used for training, while the actual business metric is measured separately on validation data.

A good workflow checks that improvements in the training objective translate into improvements in the metric that matters.

10. A practical checklist for selecting a cost function#

Before adopting a loss, ask:

  1. Does minimizing it encourage the predictions we actually want?
  2. Does its penalty reflect the relative cost of different mistakes?
  3. Is it compatible with the optimizer and model architecture?
  4. Are its gradients or optimization signals useful?
  5. Does convexity provide a benefit in this model, or is non-convex optimization acceptable?
  6. How does it respond to outliers, class imbalance, and noisy labels?
  7. Is it numerically stable and affordable at production scale?
  8. Does it target the right statistical quantity—mean, median, quantile, or probability?
  9. Does lower training loss correlate with better held-out and business performance?

Interview takeaway#

A good cost function should measure the task correctly, reward better predictions, penalize costly mistakes appropriately, and be practical to optimize. Differentiability, convexity, robustness, and numerical stability are useful properties, but no single loss must satisfy every one of them. Choose the objective according to the prediction task, data characteristics, optimization method, and real-world cost of errors.

Related questions

Explore other topics:Deep LearningMLOps