1. Home
  2. Explore
  3. Mathematics
  4. Gradient Descent

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Gradient Descent

Gradient Descent for Parameter Optimization

What Gradient Descent Does

Gradient descent is an optimization algorithm used to find parameter values that minimize a loss function. It is widely used in:

  • Statistics

  • Machine learning

  • Data science

  • Numerical optimization

Many statistical and machine-learning methods involve optimizing parameters:

  • Linear regression: estimates an intercept and one or more slopes.

  • Logistic regression: estimates parameters that define a nonlinear prediction curve.

  • t-SNE: optimizes the arrangement of points into clusters.

  • Neural networks and other models: optimize potentially thousands or millions of parameters.

The central idea is general:

Gradient descent repeatedly changes model parameters in the direction that decreases the loss function.

Although the example here uses a line and the sum of squared residuals, the same strategy applies to many other models and loss functions.


Example: Fitting a Line to Data

Suppose a data set records:

  • Weight on the xxx-axis

  • Height on the yyy-axis

A linear model has the form:

predicted height=b+mx\text{predicted height} = b + mxpredicted height=b+mx

where:

  • bbb is the intercept

  • mmm is the slope

  • xxx is weight

  • yyy is observed height

For example, if a person weighs 1.51.51.5, the fitted line may predict a height of approximately 1.91.91.9.

The goal is to find the values of bbb and mmm that produce the best-fitting line.

The example uses the following three observations:

  • (x1,y1)=(0.5,1.4)(x_1,y_1)=(0.5,1.4)(x1​,y1​)=(0.5,1.4)

  • (x2,y2)=(2.3,1.9)(x_2,y_2)=(2.3,1.9)(x2​,y2​)=(2.3,1.9)

  • (x3,y3)=(2.9,3.2)(x_3,y_3)=(2.9,3.2)(x3​,y3​)=(2.9,3.2)

Initially, the slope is fixed at its least-squares estimate:

m=0.64m=0.64m=0.64

Gradient descent is first used to estimate only the intercept. Later, it estimates both the intercept and the slope.


Using Gradient Descent to Estimate the Intercept

1. Choose an Initial Intercept

Gradient descent needs a starting point. The initial value does not need to be accurate; it only gives the algorithm a parameter value to improve.

In the example:

b=0b=0b=0

With the slope fixed at 0.640.640.64, the initial line is:

y^=0+0.64x\hat{y}=0+0.64xy^​=0+0.64x

where y^\hat{y}y^​ represents predicted height.


2. Measure the Model’s Error

The quality of the line is evaluated using the sum of squared residuals.

A residual is the difference between an observed value and its predicted value:

residual=y−y^\text{residual}=y-\hat{y}residual=y−y^​

The loss function is:

L(b)=∑i=1n(yi−y^i)2L(b)=\sum_{i=1}^{n}(y_i-\hat{y}_i)^2L(b)=∑i=1n​(yi​−y^​i​)2

Because the slope is fixed at 0.640.640.64, the prediction for each observation is:

y^i=b+0.64xi\hat{y}_i=b+0.64x_iy^​i​=b+0.64xi​

Thus, the loss function is:

L(b)=∑i=13(yi−(b+0.64xi))2L(b)=\sum_{i=1}^{3}\left(y_i-(b+0.64x_i)\right)^2L(b)=∑i=13​(yi​−(b+0.64xi​))2

In machine-learning terminology, the sum of squared residuals is a type of loss function.

Calculating the first residual

For the first person:

  • Weight: x1=0.5x_1=0.5x1​=0.5

  • Observed height: y1=1.4y_1=1.4y1​=1.4

When b=0b=0b=0:

y^1=0+0.64(0.5)=0.32\hat{y}_1=0+0.64(0.5)=0.32y^​1​=0+0.64(0.5)=0.32

The residual is:

r1=1.4−0.32=1.08r_1=1.4-0.32=1.08r1​=1.4−0.32=1.08

Rounded to one decimal place, this is approximately 1.11.11.1.

The other residuals are approximately:

r2=0.4r_2=0.4r2​=0.4

and

r3=1.3r_3=1.3r3​=1.3

Squaring and adding the residuals produces a sum of squared residuals of approximately:

L(0)=3.1L(0)=3.1L(0)=3.1

A smaller loss indicates a better-fitting line.


3. Visualizing the Loss

The loss can be calculated for many different intercept values.

  • The horizontal axis represents different values of bbb.

  • The vertical axis represents the sum of squared residuals, L(b)L(b)L(b).

Each possible intercept corresponds to a point on the loss curve.

For example:

  • b=0b=0b=0 produces one loss value.

  • b=0.25b=0.25b=0.25 produces another.

  • b=0.5b=0.5b=0.5 produces another.

  • Larger intercepts produce additional points.

The optimal intercept is the value that produces the lowest point on the curve.

Trying many possible values manually is called a plug-and-chug approach. Although it can eventually find a good value, it is inefficient because it may require a large number of calculations.

Gradient descent is more efficient because it takes large steps when far from the minimum and progressively smaller steps when close to it.


The Derivative and the Direction of Improvement

Why the Derivative Is Useful

The derivative of the loss function gives the slope of the loss curve at a particular parameter value.

For the intercept, the derivative is:

dLdb=ddb[(1.4−(b+0.64(0.5)))2+(1.9−(b+0.64(2.3)))2+(3.2−(b+0.64(2.9)))2]\frac{dL}{db} = \frac{d}{db} \left[ (1.4-(b+0.64(0.5)))^2 + (1.9-(b+0.64(2.3)))^2 + (3.2-(b+0.64(2.9)))^2 \right]dbdL​=dbd​[(1.4−(b+0.64(0.5)))2+(1.9−(b+0.64(2.3)))2+(3.2−(b+0.64(2.9)))2]

Using the chain rule, the derivative of each squared residual has the general form:

ddb(yi−(b+mxi))2=−2(yi−(b+mxi))\frac{d}{db}\left(y_i-(b+mx_i)\right)^2 = -2\left(y_i-(b+mx_i)\right)dbd​(yi​−(b+mxi​))2=−2(yi​−(b+mxi​))

Therefore:

dLdb=−2∑i=13(yi−(b+0.64xi))\frac{dL}{db} = -2\sum_{i=1}^{3}\left(y_i-(b+0.64x_i)\right)dbdL​=−2∑i=13​(yi​−(b+0.64xi​))

The derivative tells gradient descent:

  • Whether the intercept should increase or decrease

  • How strongly the intercept should be changed

Interpreting the derivative

At b=0b=0b=0:

dLdb≈−5.7\frac{dL}{db}\approx -5.7dbdL​≈−5.7

This means the loss curve has a strongly negative slope at the current intercept.

The closer the intercept gets to the optimum, the closer the derivative gets to zero.

  • A derivative far from zero indicates that the current parameter is far from optimal.

  • A derivative near zero indicates that the current parameter is near the minimum.


Learning Rate and Step Size

The Learning Rate

The derivative indicates the direction and relative size of the required change, but using the derivative directly could result in steps that are too large.

Gradient descent therefore multiplies the derivative by a small positive number called the learning rate.

The step size is:

step size=learning rate×derivative\text{step size} = \text{learning rate} \times \text{derivative}step size=learning rate×derivative

Let the learning rate be:

α=0.1\alpha=0.1α=0.1

At b=0b=0b=0, the derivative is approximately −5.7-5.7−5.7, so:

step size=0.1(−5.7)=−0.57\text{step size}=0.1(-5.7)=-0.57step size=0.1(−5.7)=−0.57

A large magnitude indicates a relatively large step.

Why the step size must be controlled

If the learning rate is too large:

  • The algorithm may overshoot the minimum.

  • The loss may increase rather than decrease.

  • The algorithm may oscillate or fail to converge.

If the learning rate is too small:

  • The algorithm will move safely but very slowly.

  • It may require many iterations to reach a good solution.

The learning rate controls the balance between speed and stability.


Updating the Intercept

The new parameter is calculated by subtracting the step size from the old parameter:

bnew=bold−step sizeb_{\text{new}}=b_{\text{old}}-\text{step size}bnew​=bold​−step size

For the first iteration:

bnew=0−(−0.57)=0.57b_{\text{new}} = 0-(-0.57) = 0.57bnew​=0−(−0.57)=0.57

The intercept increases from 000 to approximately 0.570.570.57.

This is appropriate because the negative derivative indicates that increasing the intercept will reduce the loss.


Iterative Progress Toward the Minimum

Gradient descent repeats the following process:

  1. Calculate the derivative at the current intercept.

  2. Multiply the derivative by the learning rate.

  3. Subtract the step size from the current intercept.

  4. Recalculate the derivative at the new intercept.

  5. Continue until a stopping condition is reached.

The approximate progression is:

First update

  • Current intercept: 000

  • Derivative: −5.7-5.7−5.7

  • Step size: −0.57-0.57−0.57

  • New intercept: 0.570.570.57

Second update

At b=0.57b=0.57b=0.57:

  • Derivative: approximately −2.3-2.3−2.3

  • Learning rate: 0.10.10.1

  • Step size:

0.1(−2.3)=−0.230.1(-2.3)=-0.230.1(−2.3)=−0.23
  • New intercept:

0.57−(−0.23)=0.800.57-(-0.23)=0.800.57−(−0.23)=0.80

Third update

At b=0.80b=0.80b=0.80:

  • Derivative: approximately −0.9-0.9−0.9

  • Step size:

0.1(−0.9)=−0.090.1(-0.9)=-0.090.1(−0.9)=−0.09
  • New intercept:

0.80−(−0.09)=0.890.80-(-0.09)=0.890.80−(−0.09)=0.89

Later updates

The intercept then approaches the optimum:

  • Approximately 0.920.920.92

  • Approximately 0.940.940.94

  • Approximately 0.950.950.95

Each step becomes smaller because the derivative gets closer to zero.

Gradient descent takes large steps when the loss curve is steep and small steps when the curve is nearly flat.

After six steps, the estimated intercept is approximately:

b=0.95b=0.95b=0.95

This matches the least-squares estimate for the intercept.


Stopping Conditions

Gradient descent does not need to compare its result with a known correct answer. Instead, it uses practical stopping rules.

Minimum Step Size

The algorithm can stop when the step size becomes sufficiently small.

For example, suppose:

dLdb=0.009\frac{dL}{db}=0.009dbdL​=0.009

and:

α=0.1\alpha=0.1α=0.1

Then:

step size=0.1(0.009)=0.0009\text{step size}=0.1(0.009)=0.0009step size=0.1(0.009)=0.0009

If the minimum acceptable step size is 0.0010.0010.001, then:

0.0009<0.0010.0009<0.0010.0009<0.001

The algorithm stops because further changes would be negligible.

A small step size means the derivative is close to zero, indicating that the algorithm is close to the minimum.

Maximum Number of Steps

Gradient descent also uses a maximum iteration limit.

For example:

  • Minimum step size: approximately 0.0010.0010.001 or smaller

  • Maximum number of steps: approximately 100010001000 or more

The maximum prevents the algorithm from running indefinitely if it fails to converge.

The algorithm stops when either:

  1. The step size is sufficiently small, or

  2. The maximum number of steps has been reached.


Summary of One-Parameter Gradient Descent

For estimating the intercept:

  1. Choose a loss function, such as the sum of squared residuals.

  2. Differentiate the loss function with respect to the intercept.

  3. Choose a random initial intercept.

  4. Substitute the current intercept into the derivative.

  5. Calculate the step size using the learning rate.

  6. Update the intercept:

bnew=bold−αdLdbb_{\text{new}}=b_{\text{old}}-\alpha\frac{dL}{db}bnew​=bold​−αdbdL​
  1. Repeat the derivative calculation and update.

  2. Stop when the step size is very small or the iteration limit is reached.


Estimating Both the Intercept and the Slope

Two-Parameter Loss Function

The previous example fixed the slope at 0.640.640.64. Gradient descent can instead estimate both parameters simultaneously.

The prediction equation is:

y^i=b+mxi\hat{y}_i=b+mx_iy^​i​=b+mxi​

The loss function remains the sum of squared residuals:

L(b,m)=∑i=1n(yi−(b+mxi))2L(b,m) = \sum_{i=1}^{n} \left(y_i-(b+mx_i)\right)^2L(b,m)=∑i=1n​(yi​−(b+mxi​))2

Now the loss depends on two parameters:

  • Intercept bbb

  • Slope mmm

The loss can be visualized as a three-dimensional surface:

  • One horizontal axis represents the intercept.

  • Another horizontal axis represents the slope.

  • The vertical axis represents the sum of squared residuals.

The goal is to find the combination of bbb and mmm that gives the lowest point on this surface.


Partial Derivative with Respect to the Intercept

When differentiating with respect to bbb, the slope mmm is treated as a constant.

The derivative is:

∂L∂b=−2∑i=1n(yi−(b+mxi))\frac{\partial L}{\partial b} = -2\sum_{i=1}^{n} \left(y_i-(b+mx_i)\right)∂b∂L​=−2∑i=1n​(yi​−(b+mxi​))

The slope is treated as constant because the derivative is being taken with respect to the intercept.


Partial Derivative with Respect to the Slope

When differentiating with respect to mmm, the intercept bbb is treated as a constant.

Using the chain rule:

∂L∂m=−2∑i=1nxi(yi−(b+mxi))\frac{\partial L}{\partial m} = -2\sum_{i=1}^{n} x_i\left(y_i-(b+mx_i)\right)∂m∂L​=−2∑i=1n​xi​(yi​−(b+mxi​))

The factor xix_ixi​ appears because the prediction contains the product mximx_imxi​.

For the first data point, x1=0.5x_1=0.5x1​=0.5, so its contribution to the slope derivative contains the factor 0.50.50.5.

For the other observations, the corresponding factors are 2.32.32.3 and 2.92.92.9.

This illustrates an important distinction:

  • The intercept derivative measures the residuals directly.

  • The slope derivative weights each residual by its corresponding xxx-value.


The Gradient

When a function has multiple derivatives with respect to multiple parameters, those derivatives form a gradient.

For this model, the gradient is:

∇L=(∂L∂b,∂L∂m)\nabla L = \left( \frac{\partial L}{\partial b}, \frac{\partial L}{\partial m} \right)∇L=(∂b∂L​,∂m∂L​)

The gradient describes the direction of greatest increase in the loss function.

Gradient descent moves in the opposite direction, toward lower loss.

The algorithm is called gradient descent because it uses the gradient to descend toward the lowest point of the loss surface.


Updating Two Parameters

Initial Values

Gradient descent begins with initial guesses for both parameters.

In the example:

b=0b=0b=0

and

m=1m=1m=1

This gives the initial line:

y^=0+1x\hat{y}=0+1xy^​=0+1x

The initial values do not need to be close to the final solution.


Calculating the Two Step Sizes

The derivatives are evaluated at the current values of bbb and mmm.

Each derivative receives its own step size:

stepb=α∂L∂b\text{step}_b = \alpha\frac{\partial L}{\partial b}stepb​=α∂b∂L​
stepm=α∂L∂m\text{step}_m = \alpha\frac{\partial L}{\partial m}stepm​=α∂m∂L​

The learning rate is set to:

α=0.01\alpha=0.01α=0.01

The new parameters are:

bnew=bold−stepbb_{\text{new}} = b_{\text{old}}-\text{step}_bbnew​=bold​−stepb​
mnew=mold−stepmm_{\text{new}} = m_{\text{old}}-\text{step}_mmnew​=mold​−stepm​

Thus, the intercept and slope are updated simultaneously.

After the first update, the algorithm obtains a new line. It then recalculates both derivatives using that new line and repeats the process.


Learning-Rate Sensitivity

The appropriate learning rate may differ depending on the problem.

A learning rate of 0.10.10.1, which worked in the one-parameter example, is too large for the two-parameter example. With that learning rate, gradient descent may fail to reach the correct solution even after many iterations.

This demonstrates that gradient descent can be sensitive to the learning rate.

  • A large learning rate may cause instability or overshooting.

  • A small learning rate may cause slow progress.

  • The scale of the parameters and derivatives affects which learning rate is appropriate.

In practice, learning rates can often be selected automatically by:

  1. Starting with a relatively large learning rate.

  2. Gradually decreasing it during optimization.

This strategy reduces the need to manually choose one perfect learning rate.


Final Two-Parameter Solution

After repeatedly updating both parameters, gradient descent finds the best-fitting line:

b=0.95b=0.95b=0.95

and

m=0.64m=0.64m=0.64

These values match the least-squares solution.

The important result is that gradient descent reaches the same optimum without directly solving the derivative equations for where they equal zero.


Gradient Descent Compared with Least Squares

Least-Squares Optimization

For ordinary linear regression, least squares can often solve directly for the parameter values that minimize the sum of squared residuals.

This involves finding the point where the derivative, or derivatives, equal zero:

dLdθ=0\frac{dL}{d\theta}=0dθdL​=0

where θ\thetaθ represents a model parameter.

Gradient Descent

Gradient descent instead:

  1. Starts from an initial guess.

  2. Calculates the derivative or gradient.

  3. Takes a step toward lower loss.

  4. Repeats until convergence.

Gradient descent is especially useful when:

  • The loss function is complicated.

  • The model has many parameters.

  • A direct algebraic solution is unavailable.

  • The derivative equations cannot be solved easily.

  • The optimization surface is nonlinear or high-dimensional.

The same iterative strategy can optimize models beyond ordinary linear regression.


General Gradient Descent Algorithm

Suppose a model has parameters θ1,θ2,…,θp\theta_1,\theta_2,\ldots,\theta_pθ1​,θ2​,…,θp​ and loss function LLL.

Step 1: Calculate the Gradient

Take the derivative of the loss function with respect to every parameter:

∂L∂θ1,∂L∂θ2,…,∂L∂θp\frac{\partial L}{\partial \theta_1}, \frac{\partial L}{\partial \theta_2}, \ldots, \frac{\partial L}{\partial \theta_p}∂θ1​∂L​,∂θ2​∂L​,…,∂θp​∂L​

Together, these derivatives form the gradient:

∇L=(∂L∂θ1,∂L∂θ2,…,∂L∂θp)\nabla L = \left( \frac{\partial L}{\partial \theta_1}, \frac{\partial L}{\partial \theta_2}, \ldots, \frac{\partial L}{\partial \theta_p} \right)∇L=(∂θ1​∂L​,∂θ2​∂L​,…,∂θp​∂L​)

Step 2: Choose Initial Parameter Values

Select starting values for all parameters. These may be random or otherwise initialized.

Step 3: Evaluate the Gradient

Substitute the current parameter values into the derivatives.

Step 4: Calculate Step Sizes

For each parameter:

stepθj=α∂L∂θj\text{step}_{\theta_j} = \alpha \frac{\partial L}{\partial \theta_j}stepθj​​=α∂θj​∂L​

Step 5: Update the Parameters

For every parameter:

θj,new=θj,old−stepθj\theta_{j,\text{new}} = \theta_{j,\text{old}} - \text{step}_{\theta_j}θj,new​=θj,old​−stepθj​​

Equivalently:

θj,new=θj,old−α∂L∂θj\theta_{j,\text{new}} = \theta_{j,\text{old}} - \alpha \frac{\partial L}{\partial \theta_j}θj,new​=θj,old​−α∂θj​∂L​

Step 6: Repeat

Return to gradient evaluation and continue updating the parameters until:

  • All step sizes are sufficiently small, or

  • The maximum number of iterations is reached.


Loss Functions

The sum of squared residuals is only one possible loss function.

A loss function measures how poorly a model’s predictions fit the data. Different problems require different loss functions.

Examples include:

  • Squared-error loss for many regression problems

  • Logarithmic or cross-entropy loss for classification

  • Other specialized losses for different data types and modeling goals

The choice of loss function changes the derivatives, but the overall gradient-descent process remains the same:

  1. Differentiate the loss function.

  2. Initialize the parameters.

  3. Evaluate the gradient.

  4. Calculate step sizes.

  5. Update the parameters.

  6. Repeat until convergence or the iteration limit.


Stochastic Gradient Descent

Motivation

With only three observations, calculating the derivatives is quick. With millions of observations, calculating the full loss and all derivatives at every iteration can be computationally expensive.

Stochastic gradient descent addresses this problem by using a randomly selected subset of the data at each step.

Instead of calculating the gradient using the entire data set, it calculates an approximate gradient using:

  • One randomly selected observation, or

  • A randomly selected small batch of observations

Advantages

Using a subset of the data:

  • Reduces the time required for each update.

  • Makes optimization feasible for very large data sets.

  • Allows the algorithm to begin making progress without processing all observations first.

The resulting gradient is an approximation of the full-data gradient. Because the subset changes across iterations, the updates may be somewhat noisy, but the algorithm can still move toward a good solution.

Stochastic gradient descent uses randomly selected subsets of data to make gradient calculations faster while preserving the basic logic of gradient descent.


Key Takeaways

Gradient descent minimizes a loss function by repeatedly moving parameters in the direction of lower loss.

  • The loss function measures how well a model fits the data.

  • A derivative gives the slope of the loss with respect to one parameter.

  • A gradient is the collection of derivatives for multiple parameters.

  • The learning rate controls the size of each update.

  • Large derivatives generally produce larger steps.

  • As the optimum is approached, derivatives and step sizes become smaller.

  • Parameters are updated by subtracting the step size:

θnew=θold−α∂L∂θ\theta_{\text{new}} = \theta_{\text{old}} - \alpha \frac{\partial L}{\partial \theta}θnew​=θold​−α∂θ∂L​
  • Gradient descent stops when the step sizes are sufficiently small or when the maximum number of iterations is reached.

  • The method works with one parameter, two parameters, or many parameters.

  • Stochastic gradient descent speeds up optimization by using randomly selected subsets of the data.

  • Gradient descent is broadly useful because it does not require a direct algebraic solution for the minimum.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent