Back to the blog

Gradient Descent with Python

Gradient descent is the engine behind training nearly every modern neural network. The idea is surprisingly simple: move iteratively in the direction opposite the gradient of the objective function to descend "downhill" to a minimum.

At each step:

\[x_{n+1} = x_n - \eta \cdot f'(x_n)\]

where \(\eta\) is the learning rate or step size. If it's too small, convergence is slow; if too large, it can oscillate or diverge.

To illustrate, let's minimize \(f(x) = x^2 + 2x - 4\). The analytical minimum is at \(x^* = -1\) with \(f(x^*) = -5\).

# Function to be minimized
def f(x):
    return x**2 + 2*x - 4

# Derivative of the function
def df(x):
    return 2*x + 2

# Beginning of the Gradient Descent algorithm
# ===========================================

# Initial parameters
x0 = 2
learning_rate = 0.1
iterations = 100

for i in range(iterations):
    x0 = x0 - learning_rate*df(x0)

# Showing the final value of x0 and f(x0)
print(f"Value of x0: {x0:.4f}")
print(f"Minimum value of f(x): {f(x0):.4f}")

Running it, we get:

Value of x0: -1.0000
Minimum value of f(x): -5.0000

The method converges to the true minimum in practically the first 20 iterations:

Gradient descent trajectory

Each step divides the distance to the optimum by a factor of \((1 - 2\eta) = 0.8\) (because here \(f''(x) = 2\) is constant). This type of convergence is called linear — exponentially fast in theory, but in real problems with multiple local minima the trajectory can get trapped.

That factor depends on \(\eta\), and the behavior changes with it: depending on its value, the descent creeps, lands in a single step, oscillates around the minimum or diverges.

Animation (needs JavaScript): at η = 0.02 the descent creeps, at 0.5 it reaches the minimum in one step, at 0.9 it oscillates and at 1.05 it diverges.

From 1D to Deep Learning:

The same idea generalizes to vectors: \(\vec{w}_{n+1} = \vec{w}_n - \eta \cdot \nabla L(\vec{w}_n)\), where \(\vec{w}\) are the network weights and \(L\) is the loss function. In practice, variants are used such as:

  • SGD with momentum — accelerates in consistent directions
  • Adam / RMSprop — adjust \(\eta\) individually per parameter
  • Mini-batch — estimates \(\nabla L\) over a random subset of the dataset

Installation:

No libraries required — standard Python is enough. For larger problems:

pip install numpy
Back to the blog