The Wayback Machine - https://web.archive.org/web/20240825103557/https://www.geeksforgeeks.org/ml-common-loss-functions/
Open In App

ML | Common Loss Functions

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
21.47%
903

The loss function estimates how well a particular algorithm models the provided data. Loss functions are classified into two classes based on the type of learning task

  • Regression Models: predict continuous values.
  • Classification Models: predict the output from a set of finite categorical values.

REGRESSION LOSSES 

Mean Squared Error (MSE) / Quadratic Loss / L2 Loss

  • It is the Mean of Square of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model.
  • Squaring of residuals is done to convert negative values to positive values. The normal error can be both negative and positive. If some positive and negative numbers are summed up, the sum maybe 0. This will tell the model that the net error is 0 and the model is performing well but contrary to that, the model is still performing badly. Thus, to get the actual performance of the model, only positive values are taken to get positive, squaring is done.
  • Squaring also gives more weightage to larger errors. When the cost function is far away from its minimal value, squaring the error will penalize the model more and thus helping in reaching the minimal value faster.
  • Mean of the Square of Residuals is taking instead of just taking the sum of square of residuals to make the loss function independent of number of datapoints in the training set.
  • MSE is sensitive to outliers. 

[Tex]\begin{equation} M S E=\frac{\sum_{i=1}^{n}\left(y_{i}-\hat{y}_{i}\right)^{2}}{n} \end{equation}[/Tex]

Python

import numpy as np # Mean Squared Error def mse( y, y_pred ) : return np.sum( ( y - y_pred ) ** 2 ) / np.size( y )

where,
i - ith training sample in a dataset
n - number of training samples
y(i) - Actual output of ith training sample
y-hat(i) - Predicted value of ith training sample

Mean Absolute Error (MAE) / La Loss

  • It is the Mean of Absolute of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model.
  • The absolute of residuals is done to convert negative values to positive values.
  • Mean is taken to make the loss function independent of number of datapoints in the training set.
  • One advantage of MAE is that is robust to outliers.
  • MAE is generally less preferred over MSE as it is harder to calculate the derivative of the absolute function because absolute function is not differentiable at the minima.

Source: Wikipedia

[Tex]\begin{equation} M A E=\frac{\sum_{i=1}^{n}\left|y_{i}-\hat{y}_{i}\right|}{n} \end{equation}[/Tex]

Python

# Mean Absolute Error def mae( y, y_pred ) : return np.sum( np.abs( y - y_pred ) ) / np.size( y )


Output

 

Mean Bias Error: It is the same as MSE. but less accurate and can could conclude if the model has a positive bias or negative bias. 

[Tex]\begin{equation} M B E=\frac{\sum_{i=1}^{n}\left(y_{i}-\hat{y}_{i}\right)}{n} \end{equation}[/Tex]

Python

# Mean Bias Error def mbe( y, y_pred ) : return np.sum( y - y_pred ) / np.size( y )


Output

 

Huber Loss / Smooth Mean Absolute Error

  • It is the combination of MSE and MAE. It takes the good properties of both the loss functions by being less sensitive to outliers and differentiable at minima.
  • When the error is smaller, the MSE part of the Huber is utilized and when the error is large, the MAE part of Huber loss is used.
  • A new hyper-parameter ‘????‘ is introduced which tells the loss function where to switch from MSE to MAE.
  • Additional ‘????’ terms are introduced in the loss function to smoothen the transition from MSE to MAE. 

Source: www.evergreeninnovations.co

[Tex]\begin{equation} \text { Loss }= \begin{cases}\frac{1}{2} *(x-y)^{2} & \text { if }(|x-y| \leq \delta) \\ \delta *|x-y|-\frac{1}{2} * \delta^{2} & \text { otherwise }\end{cases} \end{equation}[/Tex]

Python

def Huber(y, y_pred, delta): condition = np.abs(y - y_pred) < delta l = np.where(condition, 0.5 * (y - y_pred) ** 2, delta * (np.abs(y - y_pred) - 0.5 * delta)) return np.sum(l) / np.size(y)


Output

 

CLASSIFICATION LOSSES

Cross-Entropy Loss: Also known as Negative Log Likelihood. It is the commonly used loss function for classification. Cross-entropy loss progress as the predicted probability diverges from the actual label.

Python

# Binary Loss def cross_entropy(y, y_pred): return - np.sum(y * np.log(y_pred) + (1 - y) * np.log(1 - y_pred)) / np.size(y)


Output

 

[Tex]\begin{equation} \text { CrossEntropyLoss }=-\left(y_{i} \log \left(\hat{y}_{i}\right)+\left(1-y_{i}\right) \log \left(1-\hat{y}_{i}\right)\right) \end{equation}[/Tex]

Hinge Loss:  Also known as Multi-class SVM Loss. Hinge loss is applied for maximum-margin classification, prominently for support vector machines. It is a convex function used in the convex optimizer. 

[Tex]\begin{equation} \text { SVMLoss }=\sum_{j \neq y_{i}} \max \left(0, s_{j}-s_{y_{i}}+1\right) \end{equation}[/Tex]

Python

# Hinge Loss def hinge(y, y_pred): l = 0 size = np.size(y) for i in range(size): l = l + max(0, 1 - y[i] * y_pred[i]) return l / size


Output

 



Similar Reads

Loss when two items are sold at same price and same percentage profit/loss
Given the Selling price i.e 'SP' of the two items each. One item is sold at 'P%' Profit and other at 'P%' Loss. The task is to find out the overall Loss.Examples: Input: SP = 2400, P = 30% Output: Loss = 474.725 Input: SP = 5000, P = 10% Output: Loss = 101.01 Approach: How does the above formula work? For profit making item : With selling price (10
4 min read
Different Loss functions in SGD
In machine learning, optimizers and loss functions are two components that help improve the performance of the model. A loss function measures the performance of a model by measuring the difference between the output expected from the model and the actual output obtained from the model. Mean square loss and log loss are some examples of loss functi
10 min read
Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides
Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The triangle formed has two sides (AB
5 min read
Print common nodes on path from root (or common ancestors)
Given a binary tree and two nodes, the task is to Print all the nodes that are common for 2 given nodes in a binary tree. Examples: Given binary tree is : 1 / \ 2 3 / \ / \ 4 5 6 7 / / \ 8 9 10 Given nodes 9 and 7, so the common nodes are:- 1, 3 Asked in : Amazon Find the LCA of given two nodes.Print all ancestors of the LCA as done in this post, a
11 min read
Job Selection Problem - Loss Minimization Strategy | Set 2
We have discussed one loss minimization strategy before: Job Sequencing Problem – Loss Minimization. In this article, we will look at another strategy that applies to a slightly different problem.We are given a sequence of N goods of production numbered from 1 to N. Each good has a volume denoted by (Vi). The constraint is that once a good has been
9 min read
Program to calculate Profit Or Loss
Given the Cost Price(CP) and Selling Price(SP) of a product. The task is to Calculate the Profit or Loss.Examples: Input: CP = 1500, SP = 2000 Output: 500 Profit Input: CP = 3125, SP = 1125 Output: 2000 Loss Formula: Profit = (Selling Price - Cost Price) Loss = (Cost Price - Selling Price) Below is the required implementation: C/C++ Code // C++ cod
4 min read
Find cost price from given selling price and profit or loss percentage
Given the Selling Price(SP) and percentage profit or loss of a product. The task is to Calculate the cost price(CP) of the product.Examples: Input: SP = 1020, Profit Percentage = 20 Output: CP = 850 Input: SP = 900, Loss Percentage = 10 Output: CP = 1000 Approach: Formula to calculate cost price if selling price and profit percentage are given: CP
5 min read
Calculate the loss incurred in selling the given items at discounted price
A seller wants to sell his items at a discount of X%. He increases the price of each item by X% of the original price. The task is to calculate the total loss incurred after selling all the items.Examples: Input: price[] = {300}, quantity[] = {7}, X[] = {20} Output: 84.0 Original price = 300 Selling price = 360 Discounted price = 288 Loss incurred
7 min read
MultiLabel Ranking Metrics - Ranking Loss | ML
Ranking Loss is defined as the number of incorrectly ordered labels with respect to the number of correctly ordered labels. The best value of ranking loss can be zero Given a binary indicator matrix of ground-truth labels [Tex]y\epsilon \left \{ 0, 1 \right \}^{n_{samples} * n_{labels}}[/Tex] The score associated with each label is denoted by [Tex]
3 min read
What Is Cross-Entropy Loss Function?
Cross-entropy loss also known as log loss is a metric used in machine learning to measure the performance of a classification model. Its value ranges from 0 to 1 with lower being better. An ideal value would be 0. The goal of an optimizer tasked with training a classification model with cross-entropy loss would be to get the model as close to 0 as
8 min read
Scheduling priority tasks in limited time and minimizing loss
Given n tasks with arrival time, priority and number of time units they need. We need to schedule these tasks on a single resource. The objective is to arrange tasks such that maximum priority tasks are taken. Objective is to minimize sum of product of priority and left time of tasks that are not scheduled due to limited time. This criteria simply
11 min read
Job Sequencing Problem - Loss Minimization
We are given N jobs numbered 1 to N. For each activity, let Ti denotes the number of days required to complete the job. For each day of delay before starting to work for job i, a loss of Li is incurred. We are required to find a sequence to complete the jobs so that overall loss is minimized. We can only work on one job at a time. If multiple such
8 min read
Accuracy and Loss Don't Change in CNN. Is It Over-Fitting?
Answer : No, if accuracy and loss don't change, it's more indicative of underfitting or learning issues, not overfitting.When training a Convolutional Neural Network (CNN), encountering a situation where both accuracy and loss remain constant over epochs does not typically suggest overfitting. Instead, this scenario is often indicative of underfitt
2 min read
What is the relationship between the accuracy and the loss in deep learning?
Answer: In deep learning, as loss decreases (indicating better model performance on the training data), accuracy typically increases, reflecting improved model predictions on the evaluated data.In deep learning, accuracy and loss are two primary metrics used to evaluate the performance of a model, but they measure different aspects. MetricDescripti
2 min read
Derivative of the Softmax Function and the Categorical Cross-Entropy Loss
Understanding the interplay between the softmax function and categorical cross-entropy loss is crucial for training neural networks effectively. These mathematical constructs are fundamental to machine learning and deep learning, especially in classification tasks. In this article, we will discuss how to find the derivative of the softmax function
3 min read
Hinge-loss &amp; relationship with Support Vector Machines
Here we will be discussing the role of Hinge loss in SVM hard margin and soft margin classifiers, understanding the optimization process, and kernel trick. Support Vector Machine(SVM)Support Vector Machine(SVM) is a supervised machine learning algorithm for classification and regression. Let us use the binary classification case to understand the H
12 min read
Loss function for Linear regression in Machine Learning
The loss function quantifies the disparity between the prediction value and the actual value. In the case of linear regression, the aim is to fit a linear equation to the observed data, the loss function evaluate the difference between the predicted value and true values. By minimizing this difference, the model strives to find the best-fitting lin
7 min read
ML | Log Loss and Mean Squared Error
Log Loss It is the evaluation measure to check the performance of the classification model. It measures the amount of divergence of predicted probability with the actual label. So lesser the log loss value, more the perfectness of model. For a perfect model, log loss value = 0. For instance, as accuracy is the count of correct predictions i.e. the
1 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), k(1 time) and s(1 time). Hence the lexicographical out
6 min read
Length of the transverse common tangent between the two non intersecting circles
Given two circles of given radii, having there centres a given distance apart, such that the circles don’t touch each other. The task is to find the length of the transverse common tangent between the circles.Examples: Input: r1 = 4, r2 = 6, d = 12 Output: 6.63325 Input: r1 = 7, r2 = 9, d = 21 Output: 13.6015 Approach: Let the radii of the circles
4 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read
SequenceMatcher in Python for Longest Common Substring
Given two strings ‘X’ and ‘Y’, print the longest common sub-string. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have existing solution for this problem please refer Print the longest common substring link. We will solve problem in python using SequenceMatcher.find
2 min read
First common element in two linked lists
Given two Linked Lists, find the first common element between given linked list i.e., we need to find first node of the first list which is also present in the second list. Examples: Input : List1: 10-&gt;15-&gt;4-&gt;20 Lsit2: 8-&gt;4-&gt;2-&gt;10 Output : 10 Input : List1: 1-&gt;2-&gt;3-&gt;4 Lsit2: 5-&gt;6-&gt;3-&gt;8 Output : 3 We traverse the
6 min read
Longest Common Anagram Subsequence
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to find the length of the longest subsequence which is present in both the strings in the form of anagrams. Note: The strings contain only lowercase letters. Examples: Input : str1 = "abdacp", str2 = "ckamb" Output : 3 Subsequence of str1 = abc Subsequence of str2 = ca
7 min read
Longest Common Prefix using Linked List
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using Trie Data Structure Below is an algorithm to solve
14 min read
Count items common to both the lists but with different prices
Given two lists list1 and list2 containing m and n items respectively. Each item is associated with two fields: name and price. The problem is to count items that are in both the lists but with different prices. Examples: Input : list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}} list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 4
15+ min read
Counting common prefix/suffix strings in two lists
Given two Lists of strings s1 and s2, you have to count the number of strings in s2 which is either a suffix or prefix of at least one string of s1. Examples: Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]Output: 2Explanation: String "cat" of s2 is a prefix of "catanddog"string "dog" of s2 is suffix of "catanddog" Input: s1 =
4 min read
Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
Given a rooted tree, and two nodes are in the tree, find the Lowest common ancestor of both the nodes. The LCA for two nodes u and v is defined as the farthest node from the root that is the ancestor to both u and v. Prerequisites: LCA | SET 1 Example for the above figure : Input : 4 5 Output : 2 Input : 4 7 Output : 1 Converting LCA to RMQ(Range M
15+ min read