+91 99301 12627
Machine Learning

Gradient Descent Explained: How Machine Learning Models Learn (with Python)

By Mehul Prajapati

Hiking path descending a mountain valley representing gradient descent
On this page

Gradient descent is the algorithm most machine learning models use to learn. It starts with a guess for the model’s parameters, measures how wrong the predictions are (the loss), works out which direction makes the loss smaller (the gradient), and takes a small step in that direction. Repeat that thousands of times and the parameters settle at values that fit the data well. Linear regression, logistic regression and every neural network, including large language models, are trained with some form of it.

The intuition: walking down a valley in fog

Imagine you are standing on a hillside in thick fog and want to reach the lowest point of the valley. You cannot see the bottom, but you can feel the slope under your feet. The sensible strategy is to take a step in the steepest downhill direction, check the slope again, and repeat. That is gradient descent.

  • Your position on the hill = the model’s current parameters (weights and bias).
  • Your height = the loss, for example mean squared error.
  • The slope under your feet = the gradient.
  • The size of each step = the learning rate.

The update rule

For every parameter w, gradient descent applies the same rule in each iteration:

w_new = w_old − learning_rate × (∂Loss / ∂w)

The gradient ∂Loss/∂w tells you how much the loss would change if you nudged w slightly. If the gradient is positive, increasing w increases the loss, so you decrease w. If it is negative, you increase w. The minus sign is what makes it descent.

For linear regression with mean squared error, ŷ = w·x + b, the gradients are:

  • ∂Loss/∂w = 2 × mean((ŷ − y) × x)
  • ∂Loss/∂b = 2 × mean(ŷ − y)

If these derivatives look unfamiliar, our guide to the math for data science covers the calculus you actually need.

Gradient descent from scratch in Python

Let us generate data that follows y = 3x + 5 plus some noise, start from w = 0 and b = 0, and let gradient descent find the true values.

import numpy as np

rng = np.random.default_rng(42)
X = rng.uniform(0, 10, 100)
y = 3 * X + 5 + rng.normal(0, 1, 100)

w, b = 0.0, 0.0
lr = 0.01  # learning rate

for epoch in range(3000):
    y_pred = w * X + b
    error = y_pred - y
    dw = 2 * np.mean(error * X)
    db = 2 * np.mean(error)
    w -= lr * dw
    b -= lr * db
    if epoch % 500 == 0:
        print(epoch, round(np.mean(error ** 2), 3))

print(round(w, 2), round(b, 2))

When we ran this, the loss dropped from about 451.7 at epoch 0 to about 1.0 by epoch 500 and then levelled off near 0.96 (the noise we added). The final parameters were w ≈ 3.01 and b ≈ 4.95, very close to the true 3 and 5. Libraries such as scikit-learn and PyTorch do exactly this, just faster and with smarter step rules.

Why the learning rate matters so much

Learning rate What happens Sign in the loss curve
Too small Tiny steps; training takes far too long Loss falls very slowly
About right Fast, steady progress to the minimum Loss drops quickly, then flattens
Too large Steps overshoot the valley and bounce around or diverge Loss jumps up and down or shoots to infinity / NaN

In the example above, a learning rate of 0.01 works. Try 0.05 and the loss explodes, because the steps overshoot. Always plot the loss per epoch; it is the quickest way to diagnose a bad learning rate.

Batch, stochastic and mini-batch gradient descent

Type Data used per update Pros Cons
Batch The entire dataset Smooth, stable updates Slow and memory-heavy on large data
Stochastic (SGD) One row at a time Very fast updates; noise can escape shallow minima Noisy, zig-zag path to the minimum
Mini-batch A small batch, for example 32 to 256 rows Best balance; uses GPUs efficiently Batch size becomes another setting to tune

In practice, “SGD” in deep learning libraries almost always means mini-batch gradient descent.

Problems you will meet, and the fixes

  • Features on different scales. If one feature is in rupees (lakhs) and another is age in years, the loss surface becomes a long narrow valley and gradient descent zig-zags. Standardise or normalise features first.
  • Local minima and saddle points. Linear and logistic regression have a single bowl-shaped minimum, but neural networks do not. Mini-batch noise and momentum help the optimiser move past flat regions.
  • Vanishing and exploding gradients. In deep networks, gradients can shrink to almost zero or grow huge as they pass back through layers. Good weight initialisation, ReLU activations, batch normalisation and gradient clipping help.
  • Overfitting. Gradient descent will happily keep reducing training loss after the model has stopped generalising. Watch validation loss and stop early; see overfitting vs underfitting.

Better optimisers built on gradient descent

  • Momentum keeps a running average of past gradients, so the optimiser builds speed in consistent directions and damps zig-zagging.
  • RMSProp gives each parameter its own learning rate, shrinking steps for parameters with large, noisy gradients.
  • Adam combines momentum and RMSProp. It is the default choice for most deep learning projects because it works well with little tuning.

Gradient descent also appears in a different form in XGBoost and gradient boosting, where each new tree is fitted to the gradient of the loss of the trees before it.

Frequently asked questions

Is gradient descent used in linear regression?

It can be. Linear regression also has a direct formula (the normal equation), but gradient descent scales better to very large datasets and many features, which is why libraries offer both.

What is the difference between gradient descent and backpropagation?

Backpropagation is the method for calculating the gradients in a neural network, layer by layer. Gradient descent is the method for using those gradients to update the weights. Training a network uses both.

How do I choose a learning rate?

Start with a common default (0.01 for plain gradient descent, 0.001 for Adam), plot the loss, and adjust by factors of 10. Learning-rate schedules that reduce the rate over time are standard in deep learning.

When should gradient descent stop?

Typically after a fixed number of epochs, when the loss stops improving by more than a small threshold, or when validation loss starts rising (early stopping).

Want to implement gradient descent, regression and neural networks on real datasets with guidance? Explore our Machine Learning course or the complete Data Science course.

A note from Mehul Prajapati

I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in machine learning and want a second opinion on your learning path, I am happy to help.

“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”

Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Machine Learning course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.