close
The Wayback Machine - https://web.archive.org/web/20240825104356/https://www.geeksforgeeks.org/loss-function-for-linear-regression/
Open In App

Loss function for Linear regression in Machine Learning

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 line that captures the relationship between the input features and the target variable.

In this article, we will discuss Mean Squared Error (MSE) , Mean Absolute Error (MAE) and Huber Loss.

Mean Squared Error (MSE)

One of the most often used loss functions in linear regression is the Mean Squared Error (MSE). The average of the squared difference between the real values and the forecasted values is how it is computed:

MSE = (1/n) * Σ(y_{pred}- y_{true})^2

where,

  • y_pred is the projected value
  • y_true is the true value
  • n is the number of data points

Because of the squaring process, the MSE penalizes greater mistakes more severely than smaller ones. Because outliers have the potential to greatly raise the MSE, this makes it susceptible to them. But the MSE is differentiable, which is a desired characteristic for machine learning optimization techniques.

Computing Mean Squared Error in Python

Python
import numpy as np

def mse(y_true, y_pred):
    y_true = np.array(y_true)
    y_pred = np.array(y_pred)
    return np.mean((y_true - y_pred) ** 2)

# Example usage
y_true = [3, 6, 8, 12]
y_pred = [4, 5, 7, 10]
print("Mean Squared Error:",mse(y_true, y_pred))

Output:

Mean Squared Error: 1.75

Computing Mean Squared Error using Sklearn Library

Python
from sklearn.metrics import mean_squared_error

# Example usage
y_true = [3, 6, 8, 12]
y_pred = [4, 5, 7, 10]
print("Mean Squared Error:", mean_squared_error(y_true, y_pred))

Output:

Mean Squared Error: 1.75

Mean Absolute Error (MAE)

For linear regression, another often-used loss function is the Mean Absolute Error (MAE). The average of the absolute differences between the real values and the forecasted values is used to compute it:

MAE = (1/n) * Σ|y_{pred} - y_{true}|

Since the MAE does not square the errors, it is less susceptible to outliers than the MSE. MAE handles all mistakes the same way, no matter how big. However, certain optimization techniques may encounter difficulties since the MAE is not differentiable at zero.

Computing Mean Absolute Error in Python

Python
import numpy as np

def mae(y_true, y_pred):
    y_true = np.array(y_true)
    y_pred = np.array(y_pred)
    return np.mean(np.abs(y_true - y_pred))

# Example usage
y_true = [3, 6, 8, 12]
y_pred = [4, 5, 7, 10]
print("Mean Absolute Error:',mae(y_true, y_pred))

Output:

Mean Absolute Error: 1.25

Computing Mean Absolute Error using Sklearn

Python
from sklearn.metrics import mean_absolute_error

# Example usage
y_true = [3, 6, 8, 12]
y_pred = [4, 5, 7, 10]
print("Mean Absolute Error:",mean_absolute_error(y_true, y_pred))

Output:

Mean Absolute Error: 1.25

Huber Loss

The MSE and the MAE are combined to get the Huber Loss. It is intended to maintain differentiation but be less susceptible to outliers than the MSE:

Huber Loss = (1/n) * Σ L_δ(y_{pred} - y_{true})

where L_δ is the Huber loss function defined as:

L_δ(x)=\begin{cases} 0.5*x^2 & \text{ if } |x|\leq \delta\\ \delta(|x|-0.5*\delta)& \text otherwise \end{cases} ​

The Huber Loss exhibits the same behavior as the MAE for big errors (|x| > δ) and the MSE for minor errors (|x| <= δ). The point of transition between the two regimes is determined by the parameter δ.

Computing Huber Loss in Python

Python
import numpy as np

def huber_loss(y_true, y_pred, delta):
    residual = y_true - y_pred
    huber_loss = np.where(np.abs(residual) <= delta, 0.5 * residual ** 2, delta * (np.abs(residual) - 0.5 * delta))
    return np.mean(huber_loss)

# Example usage:
y_true = np.array([3, -0.5, 2, 7])
y_pred = np.array([2.5, 0.0, 2, 8])
delta = 1.0
print("Huber Loss:", huber_loss(y_true, y_pred, delta))

Output:

Huber Loss: 0.1875

Comparison of Loss Functions for Linear Regression

In this section, we compare different loss functions commonly used in regression tasks: Mean Squared Error (MSE), Mean Absolute Error (MAE), and Huber Loss.

  • First, it calculates the MSE and MAE using the mean_squared_error and mean_absolute_error functions from the sklearn.metrics module.
  • Then, it defines a custom function huber_loss to compute the Huber Loss, which is a combination of MSE and MAE, offering a balance between robustness to outliers and smoothness.
  • Next, it calculates the Huber Loss with a specified delta value (delta=1.0) using the implemented huber_loss function.
  • Finally, it plots the values of these loss functions for visualization using matplotlib, with labels indicating the type of loss function.

The plot provides a visual comparison of the loss values for the different functions, allowing you to observe their behavior and relative magnitudes.

Python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error

# Sample target and predicted values
y_true = np.array([3, 7, 4, 1, 8, 5])
y_pred = np.array([4, 6, 5, 3, 7, 6])

# Calculate MSE and MAE
mse = mean_squared_error(y_true, y_pred)
mae = mean_absolute_error(y_true, y_pred)

# Huber Loss implementation
def huber_loss(y_true, y_pred, delta=1.0):
    error = np.abs(y_true - y_pred)
    loss = np.where(error <= delta, 0.5 * error**2, delta * error - 0.5 * delta**2)
    return np.mean(loss)

huber_delta1 = huber_loss(y_true, y_pred, delta=1.0)

# Plot the loss functions
losses = [mse, mae, huber_delta1]
labels = ['MSE', 'MAE', 'Huber Loss (delta=1)']

# Providing x-values explicitly for plotting
x = np.arange(len(losses))

plt.figure(figsize=(10, 6))
plt.bar(x, losses, tick_label=labels)
plt.xlabel('Loss Function')
plt.ylabel('Loss Value')
plt.title('Comparison of Loss Functions')
plt.show()

Output:

Screenshot-(429)

In linear regression, the particular issue and the data’s properties determine the loss function to use. where handling regularly distributed mistakes and where outliers are not a significant problem, the MSE is often used. When robustness to outliers is crucial, the Huber Loss offers robustness without sacrificing differentiability, and the MAE is the recommended choice.

FAQs on Loss Functions for Linear Regression

Why are loss functions required in linear regression calculations?

A quantifiable indicator of a model’s performance during training is given by loss functions. The model may increase its accuracy and forecast more accurately by reducing the loss function and adjusting its parameters accordingly.

How can I choose the best loss function for the data I have?

A: The kind of data you have and the issue you’re attempting to address will determine the loss function you choose. Huber Loss combines the advantages of both MSE and MAE, and is a popular and effective model optimization technique. MAE is also resistant to outliers. Your choice will be guided by experimentation and an awareness of the trade-offs associated with each loss function.

How is the Huber Loss different from the MSE in handling outliers?

A: Beyond a threshold ($\delta$), the Huber Loss grows linearly instead of quadratically. As a result, it is less susceptible to significant mistakes, or outliers, than the mean square error (MSE), which squares errors and increases their effect on the loss amount.

Is it possible to design my own unique loss function?

A: It is possible to create unique loss functions to meet certain needs. Tailored loss functions have the ability to integrate subject expertise, manage complex data structures, and accommodate distinct assessment standards. However, mathematical optimization and a solid grasp of the issue area are often necessary for developing a meaningful bespoke loss function.



Similar Reads

Linear Regression in Machine learning
Machine Learning is a branch of Artificial intelligence that focuses on the development of algorithms and statistical models that can learn from and make predictions on data. Linear regression is also a type of machine-learning algorithm more specifically a supervised machine-learning algorithm that learns from the labelled datasets and maps the da
15+ min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
Cost function in Logistic Regression in Machine Learning
Logistic Regression is one of the simplest classification algorithms we learn while exploring machine learning algorithms. In this article, we will explore cross-entropy, a cost function used for logistic regression. What is Logistic Regression?Logistic Regression is a statistical method used for binary classification. Despite its name, it is emplo
10 min read
Robust Regression for Machine Learning in Python
Simple linear regression aims to find the best fit line that describes the linear relationship between some input variables(denoted by X) and the target variable(denoted by y). This has some limitations as in real-world problems, there is a high probability that the dataset may have outliers. This results in biased model fitting. To overcome this l
4 min read
Classification vs Regression in Machine Learning
Classification and Regression are two major prediction problems that are usually dealt with in Data Mining and Machine Learning. We are going to deal with both Classification and Regression and we will also see differences between them in this article. Classification AlgorithmsClassification is the process of finding or discovering a model or funct
5 min read
Multioutput Regression in Machine Learning
In machine learning we often encounter regression, these problems involve predicting a continuous target variable, such as house prices, or temperature. However, in many real-world scenarios, we need to predict not only single but many variables together, this is where we use multi-output regression. In this article, we will understand the topic of
11 min read
Pros and Cons of Decision Tree Regression in Machine Learning
Decision tree regression is a widely used algorithm in machine learning for predictive modeling tasks. It is a powerful tool that can handle both classification and regression problems, making it versatile for various applications. However, like any other algorithm, decision tree regression has its strengths and weaknesses. In this article, we'll e
5 min read
Naive Bayes vs Logistic Regression in Machine Learning
In the vast landscape of machine learning, selecting the most appropriate algorithm for a classification task. Two widely-used algorithms in this context are Naive Bayes and Logistic Regression. Before delving into the detailed comparison, let's establish a clear understanding of each algorithm. Table of Content Naive BayesLogistic RegressionNaive
5 min read
Regression in machine learning
Regression, a statistical approach, dissects the relationship between dependent and independent variables, enabling predictions through various regression models. The article delves into regression in machine learning, elucidating models, terminologies, types, and practical applications. What is Regression?Regression is a statistical approach used
8 min read
Logistic Regression vs K Nearest Neighbors in Machine Learning
Machine learning algorithms play a crucial role in training the data and decision-making processes. Logistic Regression and K Nearest Neighbors (KNN) are two popular algorithms in machine learning used for classification tasks. In this article, we'll delve into the concepts of Logistic Regression and KNN and understand their functions and their dif
4 min read
Machine Learning Projects Using Regression
Regression analysis in machine learning aims to model the relationship between a dependent variable and one or more independent variables. The central goal is to predict the value of the dependent variable based on input features. Linear Regression assumes a linear relationship, finding the best-fit line to minimize residuals. This article will exp
15 min read
Logistic Regression in Machine Learning
Logistic regression is a supervised machine learning algorithm used for classification tasks where the goal is to predict the probability that an instance belongs to a given class or not. Logistic regression is a statistical algorithm which analyze the relationship between two data factors. The article explores the fundamentals of logistic regressi
13 min read
CART (Classification And Regression Tree) in Machine Learning
CART( Classification And Regression Trees) is a  variation of the decision tree algorithm. It can handle both classification and regression tasks. Scikit-Learn uses the Classification And Regression Tree (CART) algorithm to train  Decision Trees (also called “growing” trees). CART was first produced by Leo Breiman, Jerome Friedman, Richard Olshen,
11 min read
R-squared in Regression Analysis in Machine Learning
The most important thing we do after making any model is evaluating the model. We have different evaluation matrices for evaluating the model. However, the choice of evaluation matrix to use for evaluating the model depends upon the type of problem we are solving whether it's a regression, classification, or any other type of problem.  In this arti
4 min read
Locally Linear Embedding in machine learning
LLE(Locally Linear Embedding) is an unsupervised approach designed to transform data from its original high-dimensional space into a lower-dimensional representation, all while striving to retain the essential geometric characteristics of the underlying non-linear feature structure. LLE operates in several key steps: Firstly, it constructs a neares
8 min read
Linear Discriminant Analysis in Machine Learning
As we know that while dealing with a high dimensional dataset then we must apply some dimensionality reduction techniques to the data at hand so, that we can explore the data and utilize it for modeling in an efficient manner. In this article, we will learn about one such dimensionality reduction technique that is used to map high dimensional data
8 min read
Linear Algebra Operations For Machine Learning
Linear algebra is the backbone of many machine learning algorithms and techniques. Understanding the fundamental operations of linear algebra is crucial for anyone aspiring to delve deep into the world of machine learning. At its core, linear algebra provides a framework for handling and manipulating data, which is often represented as vectors and
15+ min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
What is the Cost Function in Linear Regression?
Answer: In linear regression, the cost function measures how well the model's predictions match the actual data. The most common cost function used is the Mean Squared Error (MSE), which quantifies the average squared difference between the predicted values and the actual values. The goal of linear regression is to minimize this cost function, ther
2 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works &amp; what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Difference Between Machine Learning and Deep Learning
If you are interested in building your career in the IT industry then you must have come across the term Data Science which is a booming field in terms of technologies and job availability as well. In this article, we will learn about the two major fields in Data Science that are Machine Learning and Deep Learning. So, that you can choose which fie
6 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read