翻篇收录说明
翻篇网页快照

A Guide to Custom Loss Functions and Calibration Metrics

https://www.analyticsvidhya.com/blog/2025/08/custom-loss-functions/

最近抓取:2026-12-04 05:39:41(北京时间)

最近内容变化:2026-12-01 03:57:54(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Go beyond accuracy. This guide teaches you how to implement custom loss functions and improve model calibration for reliable AI applications.

正文摘录

India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder d : h : m : s Get Details Interview PrepCareerGenAIPrompt EnggChatGPTLLMLangchainRAGAI AgentsMachine LearningDeep LearningGenAI ToolsLLMOpsPythonNLPSQLAIML Projects Reading list Introduction to Deep LearningWhat is Deep Learning?DL vs ML vs AIWhy Deep Learning is So Popular? Feed Forward NetworksApplications of Deep LearningMulti Layer PerceptronVisualizing the Neural NetworkUnderstanding Decision BoundaryForward and Backward Propagation Intuition Gradient DescentGradient Descent AlgorithmVariants of Gradient Descent Algorithm Loss FunctionIntroduction to Loss FunctionBinary and Categorical Cross Entropy Activation FunctionsWhy Do We Need Activation Functions?Linear Activation FunctionSigmoid and Tanh FunctionSoftmaxHow to Select Right Activation Function? Introduction to Neural networksPerceptronWeights in PerceptronIntroduction to Artificial Neural Network Forward and Backward PropagationUnderstanding Forward Propagation MathematicallyUnderstand Backward Propagation MathematicallyImplementing Neural Networks in Python OptimizersProblems with Gradient DescentGradient Descent with MomentumAdagrad and Adadelta Learning Rate SchedulersIntroduction to Learning Rate Schedulers NN on Structured DataOverview of Deep Learning FrameworksImplementing Neural Networks using KerasFunctional API in KerasImplementing Neural Networks using KerasHyperparameter Tuning of MLP in Keras Improving the Deep Learning ModelUnderstanding Early stoppingUnderstanding DropoutVanishing and Exploding GradientsWeights Initialization TechniquesImplementing Weight Initializing TechniquesBatch NormalizationImage Augmentation TechniquesImage Generator and Fit GeneratorModel CheckpointingImplementing Model CheckpointingDealing with Class ImbalanceEnsemble Deep Learning Deep Learning Model OptimizationIntroduction to GPU and TPUTensorRT Unsupervised Deep LearningIntroduction to Unsupervised LearningHow to Solve Unsupervised Learning Problems?Introduction to AutoencodersImplementing Autoencoders AutoDLA Beginners Guide to Codeless Deep Learning Model DeploymentTensorFlow ServingBuild Deep Learning Models for Android Introduction to PyTorchIntroduction to PyTorch and TensorsMathematical and Matrix Operations in PyTorchImportant PyTorch ModulesImplement CNN in PyTorchTransfer Learning in PyTorchWorking with Text Data in PyTorchBuilding a RNN model in PyTorchAutoencoders in PyTorch Evaluating Deep Learning Models with Custom Loss Functions and Calibration Metrics Vipin Vashisth Last Updated : 15 Aug, 2025 11 min read Evaluating Deep Learning models is an essential part of model lifecycle management. Whereas traditional models have excelled at providing quick benchmarks for model performance, they often fail to capture the nuanced goals of real-world applications. For instance, a fraud detection system might prioritize minimizing false negatives over false positives, while a medical diagnosis model might value recall more than precision. In such scenarios, relying solely on conventional metrics can lead to suboptimal model behavior. This is where custom loss functions and tailored evaluation metrics come into play. Table of contentsConventional Deep Learning Models EvaluationWhat Are Custom Loss Functions?Why Model Calibration Matters?Case Study using PyTorchConclusionFrequently Asked Questions Conventional Deep Learning Models Evaluation The conventional measures to evaluate classification include Accuracy, Recall, F1-score, and so on. Cross-entropy loss is the preferred loss function to use for classification. These typical measures of classification evaluate only whether predictions were correct or not, ignoring uncertainty. A model can have high accuracy but poor probability estimates. Modern deep networks are overconfident and return probabilities of ~0 or ~1 even when they are wrong. Read more: Conventional model evaluation metrics The Problem Guo et al. show that a highly accurate deep model can still be poorly calibrated. Likewise, a model might have a high F1 score but still could be miscalibrated in its uncertainty estimates. Optimizing objective functions like accuracy or log-loss can also produce miscalibrated probabilities, since traditional evaluation metrics do not assess whether the model’s confidence matches reality. For instance, a pneumonia detection AI might output 99.9% probability based on patterns that also occur in harmless conditions, leading to overconfidence. Calibration methods like temperature scaling adjust these scores so they better reflect true likelihoods. What Are Custom Loss Functions? A custom loss or objective function is any training loss function (other than standard losses like cross-entropy and MSE) that you invent to express specific goals. You might develop one when a more generic loss does not meet your business requirements. For instance, you could use a loss that penalizes false negatives, missed fraud, more than false positives. This lets you handle uneven penalties or goals, like maximizing F1 instead of just accuracy. A loss is simply a smooth mathematical formula that compares predictions with labels, so you can design any formula that closely mimics the metric or cost you want. Why build a Custom Loss Function? Sometimes the default loss under-trains on important cases (e.g., rare classes) or doesn’t reflect your utility. Custom losses give you the ability to: Align with business logic: e.g., penalize missing a disease 5× more than a false alarm. Handle imbalance: downweight the majority class, or focus on the minority. Encode domain heuristics: e.g., require predictions to respect monotonicity or ordering. Optimize for specific metrics: approximate F1/precision/recall, or domain-specific ROI. How to Implement a Custom Loss Function? In this section, we’ll implement a custom loss with PyTorch using the nn.Module function. The following are its key points: Differentiability: Make sure the loss function is differentiable for the model outputs. Numerical Stability: Use log-sum-exp or stable functions in PyTorch (F.log_softmax, F.cross_entropy, etc.). For example, one can write Focal Loss by using F.cross_entropy (containing softmax and log) in the same way, but then multiplying by (1−𝑝𝑡)𝛾. This method avoids needing to compute the probabilities in a separate softmax, which can underflow. Code Example: To demonstrate the idea, here is how one would define a custom Focal Loss in PyTorch: import torch import torch.nn as nn import torch.nn.functional as F class FocalLoss(nn.Module): def __init__(self, gamma=2.0, weight=None): super(FocalLoss, self).__init__() self.gamma = gamma self.weight = weight # weight tensor for classes (optional) def forward(self, logits, targets): # Compute standard cross entropy loss per-sample ce_loss = F.cross_entropy(logits, targets, weight=self.weight, reduction='none') p_t = torch.exp(-ce_loss) # The model's estimated probability for true class loss = ((1 - p_t) ** self.gamma) * ce_loss return loss.mean() Here, γ tunes how much focus we want on the hard examples. The higher γ=more focus, and this implies that weight can handle class imbalance. We used Focal loss as the loss function as it’s designed to address class imbalance in object detection and other machine learning tasks, particularly when dealing with a large number of easily classified examples, e.g., background in object detection. This makes it suitable for our task. Why Model Calibration Matters? Calibration describes how well predicted probabilities correspond to real-world frequencies. A model is well-calibrated if among all the instances to which it assigns probability p to the positive class, about p fraction are positive. In other words, “confidence = accuracy”. For instance, if a model predicts 0.8 on 100 test cases, we would expect about 80 to be correct. Calibration is important when using probabilities for a decision (e.g., risk scoring; cost-benefit analysis). Formally, that means for a classifier with a probability output 𝑝^, calibration is: Perfect calibration condition for a binary classifier Calibration Errors Calibration errors fall into two categories: Overconfidence: Means the model’s predicted probabilities are systematically higher than true probabilities (e.g., predicts 90%, but is right 80% of the time). Deep neural networks tend to be overconfident, especially when overparameterized. Overconfident models can be dangerous; they often make strong predictions and can mislead us when misclassifying. Underconfidence: Underconfidence is less common in deep nets. This is the opposite of overconfidence, when the model’s confidence is too low (e.g., predicts 60%, but is right 80% of the time). While underconfidence typically places the model in a safer position when predicting, it may look unsure and thus less useful. In practice, modern DNNs are typically overconfident. Guo et al. found that newer deep nets with batch norm, deeper layers, etc., had spiky posterior distributions with very high probability on one class, even while misclassifying. When we make these miscalibrations, it is critical to realize them so we can make reliable predictions. Metrics for Calibration Reliability Diagram: Calibration Curve Commonly called a reliability diagram, this also casts the predicted successes into bins based on the prediction’s confidence score. For each bin, it plots the proportion of positives (y-axis) vs. the mean predicted probability on the x-axis. Source: IQ Expected Calibration Error (ECE): It summarizes the absolute difference between accuracy and confidence, weighted by the size of the bin. Formally, where acc(b) and conf(b) are the accuracy and mean confidence in bin size. As a reminder, lower values of ECE are better (0=perfectly calibrated). ECE is a measure of average miscalibration. Expected Calibration Error formula Maximum Calibration Error (MCE): The largest gap over all bins: Maximum Calibration Error formula Brier Sco