Reading history

Gradient Descent in Python: From Scratch with NumPy

6 min read 0 views

Learn gradient descent in Python by coding it from scratch in NumPy: loss, gradients, learning rate, divergence, feature scaling and SGDRegressor.

Most machine learning models learn the same way. They start with a guess, measure how wrong it is, and nudge the guess in the direction that reduces the error. This method is called gradient descent. In this lesson you will write it from scratch in NumPy, watch it fit a line, and see what goes wrong when the step size is too small or too large.

In this lesson you will learn

  • What a loss function and a gradient are
  • How to code gradient descent for linear regression in NumPy
  • How the learning rate controls speed and stability
  • Why feature scaling makes gradient descent much faster
  • How batch, stochastic and mini-batch gradient descent differ

You should know linear regression and basic NumPy arrays.

The Idea in Plain Words

Picture yourself on a foggy hillside, trying to reach the bottom of the valley. You cannot see the valley, but you can feel which way the ground slopes under your feet. So you take a step downhill, feel the slope again, and repeat. Gradient descent does exactly this:

  • The loss is your height: a single number saying how wrong the model is. For regression we use mean squared error.
  • The gradient is the slope under your feet: for each parameter, which way and how steeply the loss changes.
  • The learning rate is your step size.

Each step updates every parameter with the same rule: parameter = parameter − learning_rate × gradient.

Gradient Descent From Scratch

We fit a line y = w·x + b to delivery times. For mean squared error, the gradients are 2·mean(error·x) for w and 2·mean(error) for b, where error = prediction − y.

import numpy as np

# Delivery time (minutes) versus distance (km)
rng = np.random.default_rng(0)
x = rng.uniform(1, 10, 50)
y = 8 + 3 * x + rng.normal(0, 2, 50)

w, b = 0.0, 0.0          # start with a flat line at zero
lr = 0.02                # learning rate: size of each step
for step in range(1, 2001):
    pred = w * x + b
    error = pred - y
    loss = (error ** 2).mean()            # mean squared error
    grad_w = 2 * (error * x).mean()       # slope of the loss with respect to w
    grad_b = 2 * error.mean()             # slope of the loss with respect to b
    w -= lr * grad_w
    b -= lr * grad_b
    if step in (1, 10, 100, 500, 2000):
        print(f"step {step:4}: w={w:6.3f} b={b:6.3f} loss={loss:8.3f}")

best_w, best_b = np.polyfit(x, y, 1)      # exact least-squares answer
print(f"exact      : w={best_w:6.3f} b={best_b:6.3f}")

Output

step    1: w= 6.666 b= 1.012 loss= 710.426
step   10: w= 3.998 b= 1.035 loss=  11.208
step  100: w= 3.616 b= 3.947 loss=   6.059
step  500: w= 3.149 b= 7.170 loss=   3.983
step 2000: w= 3.116 b= 7.399 loss=   3.973
exact      : w= 3.116 b= 7.399
  • The loss printed at each step is measured before that step’s update, while w and b are shown after it. It starts at 710 because a flat line at zero is a terrible guess.
  • The first step jumps w to 6.666, which overshoots the true slope. Over the next steps it settles back down.
  • w settles quickly, but b creeps up slowly. The loss reacts much more strongly to w, because w is multiplied by distances up to 10. The learning rate must be small enough to keep w stable, and that same small rate makes b move slowly.
  • After 2,000 steps the answer matches the exact least-squares solution from np.polyfit to three decimal places.

Choosing the Learning Rate

import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
x = rng.uniform(1, 10, 50)
y = 8 + 3 * x + rng.normal(0, 2, 50)

def train(x, y, lr, steps=200):
    w = b = 0.0
    for _ in range(steps):
        error = w * x + b - y
        w -= lr * 2 * (error * x).mean()
        b -= lr * 2 * error.mean()
    return ((w * x + b - y) ** 2).mean()

print("Loss after 200 steps:")
for lr in [0.001, 0.01, 0.02, 0.03]:
    print(f"  learning rate {lr:<5}: {train(x, y, lr):.4g}")

z = (x - x.mean()) / x.std()              # scaled distance
print(f"  scaled x, rate 0.1 : {train(z, y, 0.1):.4g}")

sgd = make_pipeline(StandardScaler(), SGDRegressor(random_state=0))
sgd.fit(x.reshape(-1, 1), y)
print("SGDRegressor prediction for 5 km:", sgd.predict([[5]]).round(2))

Output

Loss after 200 steps:
  learning rate 0.001: 10.96
  learning rate 0.01 : 6.035
  learning rate 0.02 : 4.503
  learning rate 0.03 : 1.82e+66
  scaled x, rate 0.1 : 3.973
SGDRegressor prediction for 5 km: [22.91]
  • A rate of 0.001 is safe but slow. After 200 steps the loss is still 10.96.
  • A rate of 0.02 makes good progress, but 0.03 is too big. Each step overshoots the valley and lands higher up the other side, so the loss explodes to about 1066. This is called divergence.
  • After scaling x to mean 0 and standard deviation 1, a rate of 0.1 reaches the best loss (3.973) in only 200 steps. On unscaled data, w and b need very different step sizes; scaling makes the valley round instead of a long narrow ditch.
  • SGDRegressor is scikit-learn’s ready-made gradient descent for linear models. Its prediction for 5 km (22.91) is close to the exact line’s 7.399 + 3.116 × 5 ≈ 22.98.

A practical way to choose: try rates that differ by a factor of 10 (0.001, 0.01, 0.1), watch the loss, and keep the largest rate that still goes down smoothly.

Batch, Stochastic and Mini-Batch

VariantRows used per stepBehaviour
BatchAll rowsSmooth, steady steps; slow on huge datasets
Stochastic (SGD)One rowFast, noisy steps; works on data too big for memory
Mini-batchA small group, often 32 to 256The usual choice for neural networks

Our NumPy code is batch gradient descent: every step uses all 50 rows. SGDRegressor updates the parameters one row at a time.

Common Mistakes

  1. Not scaling features. Gradient descent becomes slow or unstable when columns have very different ranges.
  2. Picking a learning rate once and never checking the loss. Always print or plot the loss over steps.
  3. Stopping too early. A loss that is still falling means the model has not finished learning.
  4. Getting the sign wrong. You subtract the gradient. Adding it walks uphill and the loss grows.

Practice Exercises

Exercise 1. Change gd1.py to stop as soon as the loss improves by less than 0.000001 between steps. Print the step where it stopped.

Show answer
w, b, lr, prev = 0.0, 0.0, 0.02, float("inf")
for step in range(1, 100001):
    error = w * x + b - y
    loss = (error ** 2).mean()
    if prev - loss < 1e-6:
        print("stopped at step", step)
        break
    prev = loss
    w -= lr * 2 * (error * x).mean()
    b -= lr * 2 * error.mean()

Exercise 2. Fit y = w1·x1 + w2·x2 + b with gradient descent. What changes in the code?

Show answer

Store the features in a matrix X of shape (rows, 2) and the weights in a vector w. The prediction becomes X @ w + b and the weight gradient becomes 2 * X.T @ error / len(y). The bias gradient stays 2 * error.mean().

Frequently Asked Questions

Why use gradient descent when linear regression has an exact formula?

The exact formula gets expensive with many features and does not exist for most other models. Neural networks, logistic regression on huge data and many other models are trained with gradient descent or a close relative.

Can gradient descent get stuck?

For linear and logistic regression the loss has a single bowl shape, so it always reaches the bottom with a suitable learning rate. Neural networks have bumpy loss surfaces with many low points, so the result can depend on where training started.

What are Adam and momentum?

They are improved versions of gradient descent. Momentum keeps some of the previous step’s direction to roll through small bumps. Adam also adapts the step size for each parameter. Both are standard in neural network libraries.

Summary

  • Gradient descent repeats: predict, measure the loss, step against the gradient.
  • Too small a learning rate is slow; too large diverges.
  • Scale features so all parameters can use one learning rate.
  • SGDRegressor and SGDClassifier provide it ready-made in scikit-learn.

Next: Text Classification with TF-IDF.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *