Sitemap
Mr. Vivek Kumar

Mr. Vivek Kumar

Data Scientist/Machine Learning 💻 | https://www.linkedin.com/in/mrvivekkumar7171 https://github.com/mrvivekkumar7171

Parameters, Differentiation and Optimization of Loss Function

20 min readMar 10, 2026

--

Using Derivative to Optimize the Loss Function in Machine Learning and Deep Learning

Press enter or click to view image in full size

Two ways to train a Model

  • Closed form expression: It is used for simple expression or direct formula like simple linear regression. It is slow on high dimensionality data. Example: OLS (Ordinary Least Squares) etc.
  • Non-closed form expression: It uses integration and differentiation to find values and used for complex expression like higher dimensions. It is fast on high dimensionality data. Example: Stochastic Gradient Descent (SGD) etc.

SGDRegressor uses SGD, while, LinearRegression class of sklearn uses OLS.

Functions

It is a mathematical rule that takes an input value, processes it according to a specific formula or set of instructions, and produces a unique output value. In other words, a function is a relationship between input and output values where each input is connected to exactly one output. Every function has a Domain/Search Space (the complete set of all possible/allowed input values) and a Range (the resulting output values). 2D graph.

Multivariable Functions

It is a mathematical function that takes two or more independent input variables (e.g., x and y) and maps them to a single output dependent variable (often denoted as z = f(x,y)), allowing for the modeling of complex relationships in higher-dimensional spaces. For a particular combination of input values the output will be same. These functions extend single-variable calculus to analyze surfaces, gradients, and optimization in 3D or higher dimentions.

Parameters in a Function

They are the variables that are used to define the behaviour of the function. The parameters influence the function’s output by determining how the input values are processed. The parameters are the constants or coefficients that appear in the function’s formula. For example, in the quadratic function f(x) = ax² + bx + c, ‘a’, ‘b’, and ‘c’ are the parameters of the function. By changing the values of these parameters, you can modify the shape and position of the parabola represented by the function.

Machine Learning models as Mathematical Function

Machine learning models are mathematical functions y = f(x, θ) that map input data, x to desired outputs, y by optimizing parameters, θ to minimize prediction errors. These models, rooted in linear algebra, calculus, and statistics, act as parameterized functions learned from data rather than hard-coded rules. When ever your train a model means in most cases you find a methematical function that takes input and optimizing parameters to make prediction.

Parametric Vs Non-Parametric ML models

Parametric ML models:

It use a fixed, finite number of parameters to map inputs to outputs, assuming a specific, pre-defined functional form (e.g., a linear relationship) regardless of the training data size. They are generally faster to train, require less data, and are highly interpretable, but might struggle with complex data. Example: Linear Regression(assume data is linearly distributed), Logistic Regression, SVM, Neural Network, etc.

Non-Parametric ML models:

They are algorithms that do not assume a fixed, predefined functional form or a specific probability distribution for the underlying data. Instead, they learn the mapping directly from the training data, allowing for flexible, complex, and non-linear relationships where the number of parameters grows with data size. Example: Decision Tree(CART), KNN, ANN etc.

What is differentiation?

Differentiation is the process of finding the derivative of a function. The derivative of a function represents the instantaneous rate of change (at a point) of the function with respect to its variable, typically denoted as ‘x’. In simple terms, it measures how y = f(x) changes in response to a infinitesimally small change in x.

Why instantaneous (at a point)?

Normally, a rate of change can only be calculated between two distinct points. However, to calculate the rate of change at a single exact point, we use a mathematical trick (limits) by taking a second point with a near-zero difference from the first.

Why does calculating differentiation means calculating the slope?

When the distance between the two points used to calculate the rate of change approaches 0, the line connecting them becomes a tangent that only touches the graph at one specific point. The derivative gives us the slope of that tangent line.

How do we find Maxima and Minima using derivatives?

Since the derivative represents the slope, equating the derivative to 0 and solving the equation gives us the “stationary points” where the slope is exactly 0. These points on the graph can be a local maximum, a local minimum, or a saddle point. However, simply finding where the slope is 0 doesn’t confirm which of these three it is.

NOTE: minima, maxima and saddle point are a point where slope is 0.

Derivative of a Constant?

Derivative of a constant is always 0 because for any change in x, the value of y = f(x) remains fixed; therefore, its rate of change is zero.

Cheatsheet

Press enter or click to view image in full size
  • Power Rule
Power Rule
  • Sum/Difference Rule
Sum/Difference Rule
  • Product Rule
Product Rule
  • Constant Multiple Rule
Constant Multiple Rule
  • Quotient Rule
Quotient Rule
  • Chain Rule
Chain Rule

Partial Differentiation

Partial differentiation is used to calculate the gradients (or slopes) for multiple parameters and variables, which is essential when working with Loss Functions in Machine Learning. It involve differentiating with respect to one variable, then the other.

Press enter or click to view image in full size
Press enter or click to view image in full size

Higher Order Derivatives

It involve taking the derivative of a function multiple times (for example, finding the derivative of a first derivative), even if it’s just with respect to the same single variable x. It essentially measures the rate of change of the slope itself (the curvature). Example: Finding the acceleration from velocity.

NOTE: The sign of the second-order derivative tells us whether the stationary point found by the first derivative is a local minimum (positive sign) or a local maximum (negative sign).

- To find the global minimum or maximum, you must evaluate the original function f(x) at all local minima/maxima and compare their outputs to see which is the absolute lowest or highest.

- In optimization, Gradient Descent relies on first-order derivatives, while Newton’s Method utilizes second-order derivatives.

Matrix Differentiation

It is a formal, structured way to calculate the partial derivatives of a function with respect to every element in a matrix or vector. It generalizes the concept of a derivative to multivariable calculus by arranging the partial derivatives in a matrix that matches the dimensions of the input or output. This is highly useful in optimization, machine learning, and physics.

Loss Function (Error Function/Objective Function/Cost Function)

It is a mathematical function that measures the difference between the predicted output and the actual target values in a machine learning model. The primary goal of training a machine learning model is to minimize the value of the loss function, which corresponds to improving the model’s performance on the given task. It play a crucial role in the optimization process, guiding the learning algorithm to adjust the model’s parameters to achieve better predictions.

It is a mathematical formula that quantifies the disparity between a model’s predicted values and the actual “ground truth” target values. By assigning a numerical penalty to errors, it guides training algorithms (like gradient descent) to adjust model parameters to minimize this loss. On differentiate the Loss Function at 0 (slop is 0 at minimum), we got the minima (a point where Loss Function is mimimum and take the parameters). It is a metrics to determine the efficiency of a model.

Press enter or click to view image in full size
Press enter or click to view image in full size
Gradient Descent, figure1 and figure 2

Types of Metrics to determine the efficiency of a model:

  • MAE (Mean Absolute Error): It represents average error in the same units as the target variable (interpretable loss function), robust to outliers (as it does not square the errors) and not differentiable at 0. It measures the average magnitude of errors between predicted and actual values, without considering their direction (i.e., positive or negative). This makes MAE robust to outliers, as it does not square the errors like Mean Squared Error (MSE) does.

Where n is the number of data points, y_pred(i)​ is the predicted value for the i-th data point and y_true(i)​ is the actual value for the i-th data point.

  • MSE (Mean Squared Error): It can be used as loss function (as it is differentiable thus suitable for gradient-based optimization methods), square of the target variable’s unit (makes it harder to compare) and highly sensitive to outliers (as it squares the errors, which amplifies the impact of large errors). It measures the average of the squared differences between the actual values (y true​) and the predicted values (y pred​). Squaring the errors ensures that larger errors are penalized more heavily, making MSE sensitive to outliers.

Where n is the number of data points, y_pred(i)​ is the predicted value for the i-th data point, y_true(i)​ is the actual value for the i-th data point.

  • RMSE (Root Mean Squared Error): It can be used as loss function as it is differentiable, same unit (easier to compare) and sensitive to outliers. It measures the square root of average of the squared differences between the actual values (y true​) and the predicted values (y pred​). Squaring the errors ensures that larger errors are penalized more heavily, making MSE sensitive to outliers.
Press enter or click to view image in full size

Where n is the number of data points, y_hat(i)​ is the predicted value for the i-th data point, y(i)​ is the actual value for the i-th data point.

  • R2 Score (coefficient of determination/Goodness of fit): It ranges between 0 and 1. One means perfect fit while zero means not fit at all. If negative means even worse than average example applying linear regression on non-linear data. It shows how much input columns are able to explain the variance in output column example, 0.80 R2 score means input columns is able to explain 80% of vairance in output column that expected output. It increases on adding dependent column while remain constant or reduces on adding unnecessary column or increase negligible. Here, SSR is (sum of squared residuals/sum of squared errors) in regression line and SST is (total sum of squares/sum of squared deviations from the mean) in the mean line.
Press enter or click to view image in full size
  • Adjusted R2 Score: It is used if there are multiple columns and some columns are unnecessary. It increases on adding dependent column and while reduced on adding unnecessary (independent) column.

Effect of Different scale of data on Loss Function:

If salary in lakh and age is under 100, then it will take more steps to converse while if we normalize/standardize the salary then it will converse early.

Press enter or click to view image in full size

How to select a good Loss Function?

  1. Problem type: The choice of a loss function depends on the type of problem you are solving. For example, in regression tasks, mean squared error (MSE) or mean absolute error (MAE) are commonly used. For binary classification, cross-entropy loss or hinge loss can be
    employed. For multi-class classification, categorical cross-entropy or multi-class hinge loss can be used. Choose a loss function that aligns with the objectives of the specific problem you are addressing.
  2. Robustness to outliers: Some loss functions, like mean squared error, are more sensitive to outliers, which can lead to a model that is overly influenced by extreme values. If your dataset contains outliers or is prone to noise, consider using a loss function that is more robust to outliers, such as mean absolute error (MAE) or Huber loss.
  3. Interpretability and ease of use: A good loss function should be interpretable and easy to implement. Simple loss functions like mean squared error or cross-entropy loss are widely used because they are easy to understand, compute, and differentiate. When possible, opt for a loss function that is easy to work with and can be easily incorporated into your optimization process.
  4. Differentiability: Most optimization algorithms, like gradient descent, require the loss function to be differentiable. Choose a loss function that has continuous first-order derivatives, which makes it easier to compute the gradients needed for optimization.
  5. Compatibility with the model: Ensure that the chosen loss function is compatible with the model architecture you are using. Some models have specific requirements or assumptions about the loss function. For example, linear regression assumes a Gaussian noise distribution, which is why mean squared error is a suitable loss function in that case.

Problem:

  1. Non-convexity: The loss function may not always be convex, meaning that it might have multiple local minima and maxima. In such cases, setting the gradient to zero might lead to a local minimum or maximum, which is not necessarily the global minimum (the optimal solution).
  2. Complexity: For some models, the loss function can be highly complex, and finding the analytical solution by setting the gradient to zero might be computationally expensive or even impossible. This is particularly true for deep learning models, where the loss functions involve a large number of parameters and complex relationships between them.
  3. Scalability: In large-scale machine learning problems with massive amounts of data or high-dimensional feature spaces, computing the analytical solution by setting the gradient to zero can be computationally prohibitive due to the high cost of processing and storing the data.
  4. Online learning and streaming data: In some applications, the data is not available all at once but arrives in a continuous stream. In these scenarios, models need to be updated incrementally as new data arrives, and an analytical solution would not be practical. Gradient descent and its variants, such as stochastic gradient descent, are well-suited for online learning and handling streaming data.

Convex And Non Convex Loss Functions

Convex Function:

Get Mr. Vivek Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

It is a real-valued function where the line segment connecting any two points on the graph lies on or above the graph. Often visualized as a cup shape, these functions have the crucial property that any local minimum is also a global minimum i.e. only one minima.

Non-Convex Functions:

It is a mathematical function that does not satisfy the definition of convexity, typically characterized by having multiple local minima, maxima, or saddle points, rather than a single global minimum. Visually, its graph has “dips and hills,” where a line connecting two points can lie above the function.

If we restrict the domain of a non-convex function to a specific region that contains only one minimum (like zooming in on a single “dip” in a wavy graph), the function behaves as a perfectly convex function within those boundaries. Furthermore, depending on how we set the boundaries of our domain, the global minimum or maximum can change, as some local minima might be excluded from the allowed search space.

NOTE: Differentiating at 0 may not give global minima for Non-Convex Function.

Press enter or click to view image in full size
Press enter or click to view image in full size
Convex Function vs Non-Convex Function vs Concave Function

This issue can be solved using derivative Optimization Algorithm like Gradient Descent, Newton Method, Quadratic Programming and Linear Programming.

Learning Rate

The learning rate is a crucial hyperparameter (usually denoted as α or η) in machine learning that controls the magnitude of adjustments made to model weights during optimization, acting as the step size towards minimizing the loss function. It dictates how quickly or slowly a model learns, directly influencing convergence speed and final model performance. It take big steps if far from best fit line and take small steps if near to best fit line. Most common Learning Rate is 0.01 .

  • Too small learning rate can take infinite time but you will reach the actual solution.
  • Too high learning rate can jump and miss the actual solution.
Press enter or click to view image in full size
J(θ) is Loss Function and θ is weight (parameter of Loss Function and weight/bias of the best fit line)

If number of rows is m and number of columns is n+1, then

  • Input data is n-dimentional.
  • Number of parameters for best fit line will be n+1.
  • Loss Function will be n+2 dimention (one dimention for each parameter and one dimention for Loss).

Gradient Descent

It is a fundamental iterative optimization algorithm used in machine learning and deep learning to minimize a model’s error (cost function). By calculating the gradient (derivative) of the cost function, it updates parameters — such as weights and biases — in the direction of the steepest descent to find the lowest point, or minimum error,. Examples: Linear Regression, Logistic Regression, Perceptron, Deep Learning (ANN, CNN, RNN) etc. If there are multiple minima then Varient of Gradient Descent like Momentum, NAG, RMSProp, Adam, Adagrad etc are used. Gradient descent is a first-order iterative optimization algorithm for finding a local minimum of a differentiable function. The idea is to take repeated steps in the opposite direction of the slope/gradient of the function at the current point, because this is the direction of steepest descent.

NOTE: Gradient Descent don’t guarantee that the minimum you got is lowest point of global minima. But in case of Linear Regression there are only one minima i.e. global minima thus Gradient Descent guarantee the lowest point(Loss Function is Convex).

Gradient Descent with Single Parameter

Gradient Descent in 2D (Single Parameter)
Parameter Updation || ∇ f(w^t) is slope

Gradient Descent with Multiple Parameters

Press enter or click to view image in full size
Press enter or click to view image in full size
Gradient Descent in 3D (Two Parameters)

NOTE: Visualization of Gradient Descent of more than two parameters in very difficult.

Batch Gradient Descent (BGD):

Calculates the gradient of the loss function using the entire dataset before updating model parameters. 1 update per epoch. Only used if Loss Function is Convex and data is not big. It is good for small dataset and Convex Loss Function.

  • Pros: Stable, direct convergence path, guaranteed to find global minima for convex error surfaces.
  • Cons: Extremely slow on large datasets, high memory requirement, cannot handle large data that doesn’t fit in RAM (vectorization load whole train and test dataset).
class GDRegressor:
"""
GDRegressor for Multiple Linear Regression
"""
def __init__(self, learning_rate=0.01, epochs=100):
"""
Initializing the parameters
"""
self.coef_ = None
self.intercept_ = None
self.lr = learning_rate
self.epochs = epochs

def fit(self, X_train, y_train):
"""
Train the Model and update all the Coefficients and Intercept.
Return the Coefficients and Intercept
"""

# Initializing Coefficient
self.intercept_ = 0
self.coef_ = np.ones(X_train.shape[1])

for i in range(self.epochs):
# Update
y_hat = np.dot(X_train, self.coef_) + self.intercept_

# Update the Intercept for all epochs
intercept_der = -2 * np.mean(y_train - y_hat)
self.intercept_ = self.intercept_ - (self.lr * intercept_der)

# Update all the Coefficients for all epochs
coef_der = -2 * np.dot((y_train - y_hat),X_train)/X_train.shape[0]
self.coef_ = self.coef_ - (self.lr * coef_der)

print(self.intercept_, self.coef_)

def predict(self, X_test):
"""
Make Prediction
"""
return np.dot(X_test,self.coef_) + self.intercept_

Stochastic Gradient Descent (SGD):

Updates model parameters after processing each individual training example randomly. n updates per epoch and need less number of epochs as number of updates is high. It is mostly used. For fixed number of epochs, BGD is faster than SGD. However, SGD is overall faster than BGD as it require less number of epochs to reach same accuracy as BGD for Big Datasets. It don’t guarantee that new Loss Function of Best Fit Line will be batter than previous one. It is good for large dataset and Non-Convex Loss Function.

  • Pros: Very fast convergence for large datasets, can escape local minima due to noisy, erratic, and oscillating steps. No need to load whole data at once.
  • Cons: Never fully converges (will oscillate around the minimum), higher variance, no vectorized speedup and No steady Solution (Different Solution for different run) and to solve this we use Learning Schedules.

Learning Schedules: A learning rate schedule in SGD dynamically adjusts the step size during training, typically reducing it over time to ensure faster initial convergence and more stable, precise convergence near the minimum. It solves the issue of high fluctuation (noise) near the optimal solution that occurs with a constant learning rate.

NOTE: In the below three graphs, epoch is actually the Number of Updation for each row.

Press enter or click to view image in full size
Press enter or click to view image in full size
Contour Plot || Line Plot
Press enter or click to view image in full size
Cost Function vs Number of Updation
class SGDRegressor:
"""
SGDRegressor for Large Dataset and Non-Convex Loss Function.
"""

def __init__(self, learning_rate=0.01, epochs=100):
"""
Initializing the parameters.
"""
self.coef_ = None
self.intercept_ = None
self.lr = learning_rate
self.epochs = epochs

def fit(self, X_train, y_train):
"""
Train the Model and update all the Coefficients and Intercept.
Return the Coefficients and Intercept
"""
self.intercept_ = 0
self.coef_ = np.ones(X_train.shape[1])

for i in range(self.epochs): # for each epoch
for j in range(X_train.shape[0]): # for each row
# Randomly select one row
idx = np.random.randint(0, X_train.shape[0])
# y_hat for only one row
y_hat = np.dot(X_train[idx], self.coef_) + self.intercept_

intercept_der = -2 * (y_train[idx] - y_hat)
self.intercept_ = self.intercept_ - (self.lr * intercept_der)

coef_der = -2 * np.dot((y_train[idx] - y_hat), X_train[idx])
self.coef_ = self.coef_ - (self.lr * coef_der)

print(self.intercept_, self.coef_)

def predict(self, X_test):
"""
Make Prediction
"""
return np.dot(X_test, self.coef_) + self.intercept_

Mini-Batch Gradient Descent (MBGD):

A hybrid approach that divides the dataset into small subsets (mini-batches) and updates parameters after each batch. n*b updates per epoch, where b is the batch size.

  • Pros: Balances speed and stability, faster than BGD, less noisy/erratic than SGD, efficient use of GPU acceleration.
  • Cons: Requires tuning the “batch size” hyperparameter. Never fully converges and No steady Solution, so can use Learning Schedules here also.
Press enter or click to view image in full size
Contour Plot
class MBGDRegressor:
"""
MBGDRegressor for .
"""
def __init__(self, batch_size, learning_rate=0.01, epochs=100):
"""
Initializing the parameters.
"""
self.coef_ = None
self.intercept_ = None
self.lr = learning_rate
self.epochs = epochs
self.batch_size = batch_size

def fit(self, X_train, y_train):
"""
Train the Model and update all the Coefficients and Intercept.
Return the Coefficients and Intercept
"""
self.intercept_ = 0
self.coef_ = np.ones(X_train.shape[1])

for i in range(self.epochs):
for j in range(int(X_train.shape[0]/self.batch_size)):
# generate list of random rows
idx = random.sample(range(X_train.shape[0]), self.batch_size)

y_hat = np.dot(X_train[idx],self.coef_) + self.intercept_

intercept_der = -2 * np.mean(y_train[idx] - y_hat)
self.intercept_ = self.intercept_ - (self.lr * intercept_der)

coef_der = -2 * np.dot((y_train[idx] - y_hat),X_train[idx])
self.coef_ = self.coef_ - (self.lr * coef_der)

print(self.intercept_, self.coef_)

def predict(self, X_test):
"""
Make Prediction
"""
return np.dot(X_test, self.coef_) + self.intercept_

Problems faced in Optimization

  1. Non-convexity: For many machine learning models, such as artificial neural networks, the loss function is non-convex, which means it has a complex landscape with multiple local minima, maxima, and saddle points. This makes it difficult for optimization algorithms to find the global minimum and can result in suboptimal solutions.
Saddle Points
  1. Ill-conditioning: The loss function may be ill-conditioned, meaning the gradients in some dimensions are much larger than in others. This can cause gradient-based optimization algorithms, such as gradient descent, to oscillate and converge slowly.
  2. Vanishing and exploding gradients: In deep neural networks, the gradients can become very small (vanish) or very large (explode) as they propagate through the layers. This can lead to slow convergence or unstable training dynamics, making it difficult to optimize the loss function.
  3. Overfitting: When optimizing the loss function, the algorithm may overfit the training data, resulting in a model that performs poorly on unseen data. This occurs when the model is too complex and learns the noise in the training data instead of the underlying patterns.
  4. Scalability: For large-scale problems with a high number of features, instances, or model parameters, optimizing the loss function can be computationally expensive and time — consuming. This can limit the applicability of certain optimization techniques or require significant computational resources.

Newton Method:

Quadratic Programming:

SVM, PCA etc.

Linear Programming:

Derivative vs Gradient: The derivative is the rate of change for a function with a single input variable, resulting in a single scalar value. In machine learning, we almost always work with functions that have many input variables (like weights in a neural network). The gradient is the generalization of the derivative for these multivariable functions; it is a vector that collects the partial derivatives for every input variables.

Model training works by find “the best fit line” means finding the parameters (slopes and intercept of the best fit line) of the Loss Function for which the is Loss is minimum.

Step-by-step Model Training Procedure:

  • Initialize Parameters: Start the model training by assigning initial values to your parameters (the slope and the intercept). These can be set to 0, 1, or completely random values. Most time intercept is set to 0 initially and coefficient is set to 1 initially.
  • Make Predictions: Use these current parameter values to calculate a prediction for every single row in your training data.
  • Calculate the Loss: Evaluate the model’s performance by calculating the Loss Function. This involves comparing the actual, known outputs against your model’s predicted outputs from the previous step.
  • Calculate the Gradient: Find the slope/gradient of the Loss Function for your current parameters (slopes and intercept of the best fit line). You do this by finding the mathematical derivative of the Loss Function and plugging your current parameter values into that derivative equation.
  • Update Parameters: Adjust the parameters (slopes and intercept of the best fit line) to move in the opposite direction of the slope/gradient of the Loss Function. This step is what actively reduces the Loss Function. The exact amount the parameters change is determined by the step size (learning rate * slope/gradient of the Loss Function).
  • Check Stopping Criteria: Evaluate if you need to keep iterating. You should loop back to Step 2 and repeat the process until one of the following stopping conditions is met:
  1. The difference between the previous parameters and the newly updated parameters is very small (e.g., less than 0.001), meaning there is no further benefit to updating.
  2. A finite, predetermined number of loops (epochs), such as 100 or 1000, has been completed.
  • Save and Finalize: Once the Loss Function is minimized and the optimal “best fit line” is found, save the trained model with these final parameters so it is ready to make future predictions.

NOTE: Here in the example of Linear Regression, Loss Function is MSE which is Convex Function means only one minima i.e. global minima.

from sklearn.model_selection import train_test_split
from sklearn.datasets import make_regression
import numpy as np

X, y = make_regression(n_samples=100, n_features=1, n_informative=1, n_targets=1,noise=20,random_state=13)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=2)

class GDRegressor:

def __init__(self,learning_rate = 0.001, epochs = 100):
self.m = 0 # Initializing slopes of the Best Fit Line with zero
self.b = 0 # Initializing intercept of the Best Fit Line with zero
self.lr = learning_rate
self.epochs = epochs

def fit(self, X, y):
"""
Calculate the slopes and intercept of the Best Fit Line
or Parameters of the Loss Function
"""
for i in range(self.epochs):
# Loss Function will have 3D graph (Loss x m x b)
# Direction of Slop of b where Loss Function will reduce
loss_slope_b = -2*np.sum(y-self.m*X.ravel()-self.b)
# Direction of Slop of m wherer Loss Function will reduce
loss_slope_m = -2*np.sum((y-self.m*X.ravel()-self.b)*X.ravel())

self.b = self.b - (self.lr * loss_slope_b) # step size
self.m = self.m - (self.lr * loss_slope_m) # step size
print(self.m, self.b)

def predict(self,X):
return self.m * X + self.b

gd = GDRegressor(0.001, 30)
gd.fit(X_train, y_train) # Output: (27.82, -2.29)
gd.predict(X_test)
Press enter or click to view image in full size
Press enter or click to view image in full size
Gradient Descent converging towards the Best Fit Line in Linear Regression || Loss in Loss Function vs Epochs Graph Converging towards 0
Press enter or click to view image in full size
Press enter or click to view image in full size
b vs Epochs Graph || m vs Epochs Graph

Loss Function vs Epochs Graph tells you when to stop the iteration. Example: If increasing Epochs don’t effecting the Loss Function i.e. straight line then stop.

Press enter or click to view image in full size
Press enter or click to view image in full size
Contour Plot of m vs b || 3D of Loss Function vs m vs b

➡️ Next Up: [Multicollinearity Explained]

If you found value in this content, I invite you to stay connected for more insightful posts. Your time and interest are greatly appreciated. Thank you for reading!

--

--