0% found this document useful (0 votes)
23 views7 pages

Cost vs. Loss Functions in ML

Uploaded by

dothiminhphuong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views7 pages

Cost vs. Loss Functions in ML

Uploaded by

dothiminhphuong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Cost Function & Loss Function

What is a loss/Cost function?


‘Loss’ in Machine learning helps us understand the difference between the
predicted value & the actual value.
The Function used to quantify this loss during the training phase in the form of
a single real number is known as the “Loss Function”.
These are used in those supervised learning algorithms that use optimization
techniques. The terms cost function & loss function are analogous.
Loss function: Used when we refer to the error for a single training example.
Cost function: Used to refer to an average of the loss functions over an entire
training data.

Why Cost Function?


Consider a scenario where we wish to classify data. Suppose we have the
height & weight details of some cats & dogs. Let us use these 2 features to
classify them correctly.

If we plot these records, we get the following scatterplot:

Fig 1: Scatter Plot for Height & Weight

Cost Function & Loss Function 1


Fig 2: Probable Solutions of classification problems
Blue dots are cats and red dots are dogs.
Essentially all three classifiers have very high accuracy but the third solution is
the best because it does not misclassify any point. The reason why it classifies
all the points perfectly is that the line is almost exactly in between the two
groups, and not closer to any one of the groups. This is where the concept of
cost function comes in. Cost function helps us reach the optimal solution. The
cost function is the technique of evaluating “the performance of our
algorithm/model”.
It takes both predicted outputs by the model and actual outputs and calculates
how much wrong the model was in its prediction. It outputs a higher number if
our predictions differ a lot from the actual values. As we tune our model to
improve the predictions, the cost function acts as an indicator of how the model
has improved. This is essentially an optimization problem. The optimization
strategies always aim at “minimizing the cost function”

Types of the cost function


There are many cost functions in machine learning and each has its use cases
depending on whether it is a regression problem or classification problem.

1. Regression cost Function

2. Binary Classification cost Functions

3. Multi-class Classification cost Functions

1. Regression cost Function:


Regression models deal with predicting a continuous value for example salary
of an employee, price of a car, loan prediction, etc. A cost function used in the

Cost Function & Loss Function 2


regression problem is called “Regression Cost Function”. They are calculated
on the distance-based error as follows:

The most used Regression cost functions are below,

1.1 Mean Error (ME)

In this cost function, the error for each training data is calculated and then
the mean value of all these errors is derived.

Calculating the mean of the errors is the simplest and most intuitive way
possible.

The errors can be both negative and positive. So they can cancel each
other out during summation giving zero mean error for the model.

Thus this is not a recommended cost function but it does lay the foundation
for other cost functions of regression models.

1.2 Mean Squared Error (MSE)

This improves the drawback we encountered in Mean Error above. Here a


square of the difference between the actual and predicted value is
calculated to avoid any possibility of negative error.

It is measured as the average of the sum of squared differences between


predictions and actual observations.

Mean Squared Error

Cost Function & Loss Function 3


MSE = (sum of squared errors)/n

It is also known as L2 loss.

In MSE, since each error is squared, it helps to penalize even small


deviations in prediction when compared to MAE. But if our dataset has
outliers that contribute to larger prediction errors, then squaring this error
further will magnify the error many times more and also lead to higher MSE
error.

Hence we can say that it is less robust to outliers

1.3 Mean Absolute Error (MAE)

This cost function also addresses the shortcoming of mean error


differently. Here an absolute difference between the actual and predicted
value is calculated to avoid any possibility of negative error.

So in this cost function, MAE is measured as the average of the sum of


absolute differences between predictions and actual observations.

Mean Absolute Error

MAE = (sum of absolute errors)/n

It is also known as L1 Loss.

It is robust to outliers thus it will give better results even when our dataset
has noise or outliers.

2. Cost functions for Classification problems


Cost functions used in classification problems are different than what we use in
the regression problem. A commonly used loss function for classification is
cross-entropy loss. Let us understand cross-entropy with a small example.
Consider that we have a classification problem of 3 classes as follows.
Class(Orange,Apple,Tomato)

Cost Function & Loss Function 4


The machine learning model will give a probability distribution of these 3
classes as output for a given input data. The class with the highest probability
is considered as a winner class for prediction.

Output = [P(Orange),P(Apple),P(Tomato)]
The actual probability distribution for each class is shown below.

Orange = [1,0,0]

Apple = [0,1,0]

Tomato = [0,0,1]
If during the training phase, the input class is Tomato, the predicted probability
distribution should tend towards the actual probability distribution of Tomato. If
the predicted probability distribution is not closer to the actual one, the model
has to adjust its weight. This is where cross-entropy becomes a tool to
calculate how much far the predicted probability distribution from the actual
one is. In other words, Cross-entropy can be considered as a way to measure
the distance between two probability distributions. The following image
illustrates the intuition behind cross-entropy:

Fig 3: Intuition behind cross-entropy


This was just an intuition behind cross-entropy. It has its origin in information
theory. Now with this understanding of cross-entropy, let us now see the

Cost Function & Loss Function 5


classification cost functions.

2.1 Multi-class Classification cost Functions


This cost function is used in classification problems where there are multiple
classes and input data belongs to only one class. Let us now understand how
cross-entropy is calculated. Let us assume that the model gives the probability
distribution as below for ’n’ classes & for a particular input data D.

And the actual or target probability distribution of the data D is

Then cross-entropy for that particular data D is calculated as

Cross-entropy loss(y, p) = —yT l og(p)


Cross-entropy loss(y, p) = −(y1 l og(p1 ) + y2 l og(p2 ) + …… + yn l og(pn ))


​ ​ ​ ​ ​ ​

Let us now define the cost function using the above example (Refer cross
entropy image -Fig3),

p(Tomato) = [0.1, 0.3, 0.6]

y(Tomato) = [0, 0, 1]
Cross − Entropy(y, P ) = —(0 ∗ Log(0.1) + 0 ∗ Log(0.3) + 1 ∗
Log(0.6)) = 0.51
The above formula just measures the cross-entropy for a single observation or
input data. The error in classification for the complete model is given by
categorical cross-entropy which is nothing but the mean of cross-entropy for
all N training data.

Cost Function & Loss Function 6


Categorical Cross-Entropy = (Sum of Cross-Entropy for N data)/N
2.2 Binary Cross Entropy Cost Function

Binary cross-entropy is a special case of categorical cross-entropy when there


is only one output that just assumes a binary value of 0 or 1 to denote negative
and positive classes respectively. For example-classification between cat &
dog.
Let us assume that actual output is denoted by a single variable y, then cross-
entropy for a particular data D is can be simplified as follows –

when y = 1 → Cross-entropy(D) = — y*log(p)


when y = 0 → Cross-entropy(D) = — (1-y)*log(1-p)
The error in binary classification for the complete model is given by binary
cross-entropy which is nothing but the mean of cross-entropy for all N training
data.
Binary Cross-Entropy = (Sum of Cross-Entropy for N data)/N

Cost Function & Loss Function 7

Common questions

Powered by AI

Regression cost functions, like Mean Error or Mean Squared Error, calculate error based on the difference between predicted and actual continuous values, aiming to minimize this difference over all training data . They focus on predicting a single continuous value, and the error is typically computed as numerical deviations from these predictions . In contrast, classification cost functions, such as cross-entropy, focus on calculating error based on the difference between predicted and actual class distributions . These functions guide the adjustment of class-based probability distributions, essential for models dealing with discrete class labels rather than continuous values .

Mean Absolute Error (MAE) addresses the inaccuracies of Mean Error by taking the absolute value of the differences between predicted and actual values, thereby eliminating any cancellation of errors due to positive and negative values . MAE is measured as the average of these absolute differences, making it robust to outliers. Its major advantage over MSE is that MAE does not disproportionately increase error penalties for outliers, which makes it more stable in datasets with noise or extreme values .

Squaring errors in Mean Squared Error (MSE) serves a dual purpose. First, it ensures that the calculated error is always a positive number, avoiding any cancellation effect that might result from negative errors offsetting positive ones . Secondly, it amplifies larger errors, as squaring enhances error magnitude, thus serving as a penalization mechanism for large deviations . This heightened penalty due to squaring directs the optimization process, encouraging the model to focus more on reducing larger errors, which theoretically leads to nuanced improvements in prediction accuracy. However, while this aids meticulous optimization for precise predictions, it also introduces sensitivity to outliers, as extreme cases may drive the optimization process unduly .

Mean Absolute Error (MAE) is characterized by its robustness to outliers, making it a reliable choice for models dealing with noisy data . By computing error as the average of absolute differences between predicted and actual observations, MAE ensures that all deviations are treated equally rather than exaggerating large errors, as seen in MSE . This equitable treatment of error allows MAE to accommodate noise and maintain model stability without disproportionately impacting model performance, which is crucial when datasets contain variability or unexpected deviations resulting from outliers .

Binary Cross Entropy is a specific form of Categorical Cross Entropy used when the classification problem involves only two classes, typically denoted by binary values 0 and 1 . Categorical Cross Entropy, on the other hand, is used when dealing with multiple classes. In Binary Cross Entropy, the loss function is simplified to handle binary output by considering either the negative likelihood for the positive class or the alternative class . Thus, Binary Cross Entropy effectively becomes a special case of Categorical Cross Entropy by focusing on binary class distinctions .

Cross-entropy loss is preferred in multi-class classification problems because it provides a way to measure the distance between the predicted probability distribution and the actual distribution of classes . It adjusts model weights effectively to minimize this distance, thus helping to ensure that the model predictions closely align with actual class assignments. This is crucial in multi-class scenarios where each input belongs to one class, and the wrong probability distribution can significantly affect accuracy . The formula used in cross-entropy accounts for the logarithmic likelihood, which provides a smoother gradient when optimizing model parameters, aiding efficient convergence .

Cost functions are crucial in supervised learning as they quantify the error or difference between predicted outputs and actual outputs during model training . By providing a single real number that reflects this error, cost functions serve as metrics to evaluate and improve the performance of the model . Optimization techniques aim to minimize this cost value, signaling improved accuracy in predictions. Thus, cost functions guide the adjustment of model parameters, leading to optimized predictions over time .

Mean Squared Error (MSE) is not ideal for datasets with significant outliers because the squaring of errors during calculation exaggerates these errors' magnitude . Outliers, which are already large errors, become disproportionately large when squared, which can bias the model's learning process towards fitting these outliers rather than capturing the overall data trend . This emphasis can distort the model's predictions and lead to poor generalization on normal data patterns, compromising performance .

Cross-entropy is derived from information theory and is used as a measure of the dissimilarity between the predicted probability distribution and the true probability distribution over multiple classes . It calculates the negative sum of the predicted probabilities multiplied by the log of the actual probability distribution for each class, thereby determining the difference between expected and predicted values . By minimizing cross-entropy, the model adjusts its parameters to increase prediction accuracy, making it a critical loss function in guiding models towards producing outputs that closely mirror real data class distributions .

Mean Error (ME) calculates the mean of the errors from each training data, which can sometimes lead to a zero mean error due to cancellation of positive and negative errors, making it less robust to identifying actual error trends . In contrast, Mean Squared Error (MSE) computes the average of the squared differences between predicted and actual observations, mainly to avoid negative error possibilities. Squaring the errors highlights even minor deviations, making MSE less robust to outliers because large errors become disproportionately larger when squared .

You might also like