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 x-axis
Height on the y-axis
A linear model has the form:
where:
b is the intercept
m is the slope
x is weight
y is observed height
For example, if a person weighs 1.5, the fitted line may predict a height of approximately 1.9.
The goal is to find the values of b and m that produce the best-fitting line.
The example uses the following three observations:
(x1,y1)=(0.5,1.4)
(x2,y2)=(2.3,1.9)
(x3,y3)=(2.9,3.2)
Initially, the slope is fixed at its least-squares estimate:
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:
With the slope fixed at 0.64, the initial line is:
where 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:
The loss function is:
Because the slope is fixed at 0.64, the prediction for each observation is:
Thus, the loss function is:
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.5
Observed height: y1=1.4
When b=0:
The residual is:
Rounded to one decimal place, this is approximately 1.1.
The other residuals are approximately:
and
Squaring and adding the residuals produces a sum of squared residuals of approximately:
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 b.
The vertical axis represents the sum of squared residuals, L(b).
Each possible intercept corresponds to a point on the loss curve.
For example:
b=0 produces one loss value.
b=0.25 produces another.
b=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:
Using the chain rule, the derivative of each squared residual has the general form:
Therefore:
The derivative tells gradient descent:
Whether the intercept should increase or decrease
How strongly the intercept should be changed
Interpreting the derivative
At b=0:
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:
Let the learning rate be:
At b=0, the derivative is approximately −5.7, so:
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:
For the first iteration:
The intercept increases from 0 to approximately 0.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:
Calculate the derivative at the current intercept.
Multiply the derivative by the learning rate.
Subtract the step size from the current intercept.
Recalculate the derivative at the new intercept.
Continue until a stopping condition is reached.
The approximate progression is:
First update
Current intercept: 0
Derivative: −5.7
Step size: −0.57
New intercept: 0.57
Second update
At b=0.57:
Derivative: approximately −2.3
Learning rate: 0.1
Step size:
New intercept:
Third update
At b=0.80:
Derivative: approximately −0.9
Step size:
New intercept:
Later updates
The intercept then approaches the optimum:
Approximately 0.92
Approximately 0.94
Approximately 0.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:
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:
and:
Then:
If the minimum acceptable step size is 0.001, then:
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.001 or smaller
Maximum number of steps: approximately 1000 or more
The maximum prevents the algorithm from running indefinitely if it fails to converge.
The algorithm stops when either:
The step size is sufficiently small, or
The maximum number of steps has been reached.
Summary of One-Parameter Gradient Descent
For estimating the intercept:
Choose a loss function, such as the sum of squared residuals.
Differentiate the loss function with respect to the intercept.
Choose a random initial intercept.
Substitute the current intercept into the derivative.
Calculate the step size using the learning rate.
Update the intercept:
Repeat the derivative calculation and update.
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.64. Gradient descent can instead estimate both parameters simultaneously.
The prediction equation is:
The loss function remains the sum of squared residuals:
Now the loss depends on two parameters:
Intercept b
Slope m
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 b and m that gives the lowest point on this surface.
Partial Derivative with Respect to the Intercept
When differentiating with respect to b, the slope m is treated as a constant.
The derivative is:
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 m, the intercept b is treated as a constant.
Using the chain rule:
The factor xi appears because the prediction contains the product mxi.
For the first data point, x1=0.5, so its contribution to the slope derivative contains the factor 0.5.
For the other observations, the corresponding factors are 2.3 and 2.9.
This illustrates an important distinction:
The intercept derivative measures the residuals directly.
The slope derivative weights each residual by its corresponding x-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:
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:
and
This gives the initial line:
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 b and m.
Each derivative receives its own step size:
The learning rate is set to:
The new parameters are:
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.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:
Starting with a relatively large learning rate.
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:
and
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:
where θ represents a model parameter.
Gradient Descent
Gradient descent instead:
Starts from an initial guess.
Calculates the derivative or gradient.
Takes a step toward lower loss.
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 and loss function L.
Step 1: Calculate the Gradient
Take the derivative of the loss function with respect to every parameter:
Together, these derivatives form the gradient:
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 5: Update the Parameters
For every parameter:
Equivalently:
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:
Differentiate the loss function.
Initialize the parameters.
Evaluate the gradient.
Calculate step sizes.
Update the parameters.
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:
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.