What is Gradient Decent in Machine Learning? _ Day 7

Conceptual small, balanced and long step-size paths on a warm ivory desk with navy, sage and terracotta forms.
Conceptual illustration of different step sizes; not a measured loss plot.

Day 7 · Optimization basics

Gradient descent, one careful step at a time

Understand the gradient, choose a learning rate and follow a line-fitting model through its first updates—with checked calculations, readable formulas and the complete original Python example.

Start the checked walkthrough

Published 18 July 2024 · Expanded and checked 16 November 2026
Original lesson preserved in full · Beginner-friendly worked example

Conceptual small, balanced and long step-size paths on a warm ivory desk with navy, sage and terracotta forms.
Small, balanced and long steps: a conceptual illustration of learning rates. The measured results appear in the computed charts below.

Understand the directionSee why each update moves opposite the loss gradient.

Check the numbersFollow two updates and compare three learning rates.

Connect math and codeRead all original formulas, tables, Python and the original plot.

Checked worked example

Gradient descent, explained one update at a time

Gradient descent improves a model by repeatedly measuring how its current parameters affect the loss, then moving those parameters in the opposite direction of the gradient. In this lesson, the model is a straight line. The intercept moves the line up or down; the slope changes its tilt. A learning rate controls how far each update moves.

Use the checked calculations in this guide. Several parameter values and costs in the original hand-worked tables are inconsistent with the stated objective and the accompanying Python code. The verified calculations below resolve those discrepancies. The complete original lesson, including its tables, formulas, code and image, remains further down the page.

1. Fix the model and the meaning of the loss

Keep the original three training points: (1, 1), (2, 2) and (3, 3). There are three examples, so m = 3. The model predicts the output from the input using an intercept θ₀ and a slope θ₁.

hθ(x)=θ0+θ1x

The displayed objective in the original lesson divides the sum of squared errors by 2m. This is half the mean squared error, or half-MSE. Ordinary MSE divides by m. Multiplying an objective by a positive constant leaves its minimizing parameters unchanged, but changes its numerical values and gradients. Keep that convention consistent when choosing a learning rate and comparing a table with code.

J(θ)=12m∑i=1m(hθ(xi)−yi)2

Start with θ₀ = 0 and θ₁ = 0. Every prediction is initially zero. The three errors are −1, −2 and −3, giving J = (1 + 4 + 9) / 6 = 7/3 ≈ 2.333333. Ordinary MSE at the same starting point is 14/3 ≈ 4.666667. All costs in this checked guide and its new plots use J, the half-MSE objective.

2. Compute both gradients before changing either parameter

For full-batch gradient descent, use all three training examples for each update. First calculate the predictions and errors using the current parameter pair. Calculate both gradients from that same set of errors. Then update the intercept and slope together.

g0=1m∑i=1m(hθ(xi)−yi)
g1=1m∑i=1m(hθ(xi)−yi)xi
θjnew=θjold−αgj

At the starting point, the intercept gradient is (−1 − 2 − 3) / 3 = −2. The slope gradient is (−1 × 1 − 2 × 2 − 3 × 3) / 3 = −14/3. Both are negative, so subtracting their learning-rate-scaled values increases the two parameters.

Important: do not update θ₀ and then calculate the slope gradient using that newly changed intercept. That would use different errors for the two gradients and would no longer reproduce the simultaneous batch update used here.

3. Follow the first update with α = 0.1

Multiply each initial gradient by 0.1 and subtract it from the corresponding old parameter. The new intercept is 0 − 0.1 × (−2) = 0.2. The new slope is 0 − 0.1 × (−14/3) = 7/15 ≈ 0.466667.

The new predictions are approximately 0.666667, 1.133333 and 1.600000. Compare these with 1, 2 and 3 to get errors of −0.333333, −0.866667 and −1.400000. Squaring those errors, adding them and dividing by 6 gives J = 127/270 ≈ 0.470370. The cost has fallen from approximately 2.333333 to 0.470370 after one update.

4. Repeat from the updated model

The second update starts from θ₀ = 0.2 and θ₁ = 7/15. Its gradients are g₀ = −13/15 ≈ −0.866667 and g₁ = −94/45 ≈ −2.088889. Use those shared, pre-update errors to calculate the next pair together.

The new intercept becomes 43/150 ≈ 0.286667, and the slope becomes 152/225 ≈ 0.675556. Evaluating the cost after that second update gives J ≈ 0.100691. More decimal places are useful for checking calculations, but rounding should happen for display, rather than inside the update loop.

5. Compare the same first two updates at three learning rates

The starting model, dataset, cost convention and update rule stay the same. Only α changes. This makes the comparison meaningful. Each table row reports parameters and cost after the stated number of completed updates.

Verified first and second batch updates; values rounded to six decimal places
Learning rateUpdates completedIntercept θ₀Slope θ₁Cost J (half-MSE)
α = 0.00110.0020000.0046672.307627
α = 0.00120.0039890.0093082.282205
α = 0.110.2000000.4666670.470370
α = 0.120.2866670.6755560.100691
α = 1.012.0000004.66666748.037037
α = 1.02-7.333333-16.444444992.794239

With α = 0.001, the cost decreases slowly because each move is small. With α = 0.1, the first two moves reduce the cost much faster. With α = 1.0, the first move overshoots and the cost increases; later moves grow more extreme. A lower cost on this fixed training example tells us that the line fits these three points better.

6. Check what ten updates actually achieve

Verified results after ten completed batch updates
Learning rateUpdates completedIntercept θ₀Slope θ₁Cost J (half-MSE)
α = 0.001100.0194970.0455242.088696
α = 0.1100.3264830.8560730.007651
α = 1.010-1,390,822.390388-3,161,665.4835813.308614142e+13

At α = 0.1, the cost after ten updates is approximately 0.007651, with θ₀ ≈ 0.326483 and θ₁ ≈ 0.856073. This is a substantial improvement, but it is not the exact best-fitting line yet. For these deliberately simple points, the exact fit is y = x: θ₀ = 0, θ₁ = 1 and J = 0. Further stable updates move toward that solution.

The α = 1.0 cost is written in scientific notation because it has grown to approximately 33.1 trillion. That value is an illustration of divergence, rather than a different definition of the cost. The logarithmic panel in the new convergence figure makes its growth visible alongside the two decreasing curves; the linear panel makes the two stable rates easier to compare.

See the checked calculations

These two plots are computed from the same dataset and simultaneous update rule as the checked tables. They separate a conceptual illustration from numerical evidence.

Computed half mean squared error for learning rates 0.001, 0.1 and 1.0 over ten updates, with a separate stable-rate close-up.
Computed from the original three-point dataset and simultaneous batch-gradient updates; the upper axis is logarithmic. Select the image to inspect its full-size labels.
Verified fitted lines at initialization and after updates one, two and ten for learning rate 0.1, compared with the exact line y equals x.
A reproducible teaching example; learning rate 0.1 is stable for this dataset and loss scaling, not universally optimal. Select the image to inspect its full-size labels.

7. Read “optimal” as an example-specific illustration

The original lesson calls α = 0.1 “optimal.” Here it is a useful stable example, rather than a universal best rate or a demonstrated optimum among every possible rate. The useful step size depends on the objective, the scale of the features and the curvature of the loss. Even switching from half-MSE to ordinary MSE doubles the gradient, so the same numerical α produces a different-sized parameter update.

For readers who want the precise stability check, this particular quadratic has a largest Hessian eigenvalue of approximately 5.546470. Its constant-step, simultaneous batch updates converge from any starting pair when 0 < α < 2 / 5.546470 ≈ 0.360590. This calculation explains why 0.001 and 0.1 are stable here, while 1.0 is too large. It is a property of this unscaled dataset and this objective; it is not a general learning-rate rule for every model or dataset.

8. Match the code history to the plots

The original Python implementation correctly computes the parameter and cost histories for this example. Its stored predictions are calculated before the parameter update, while its parameter and cost histories are stored after that update. Consequently, its prediction line labelled “Iteration 10” uses the model immediately before the tenth update. The new fitted-line figure explicitly shows models after 0, 1, 2 and 10 updates, so the labels, parameters and costs refer to the same moment.

To keep a new implementation consistent, either save predictions, parameters and cost together before each update, or recompute and save all three together after each update. The original code remains intact below for comparison.

9. Carry the method into a real training task

Define the model and objective first, initialize the parameters, calculate predictions and errors, compute the gradients, update the parameters together and monitor the loss. Check whether the loss decreases, whether the gradients and parameters remain finite, and whether the stopping rule is satisfied. A fixed number of updates is a demonstration setting; it does not by itself prove convergence.

This three-point exercise explains optimization mechanics. It does not measure how well a trained model will predict unseen real-world examples. For that question, use an appropriate held-out evaluation set and compare relevant metrics. Training loss and generalization answer different questions.

Further reading: Google’s gradient descent lesson explains the update process, and its hyperparameters lesson explains learning-rate behavior. Cornell’s course notes on quadratic objectives discuss how Hessian eigenvalues affect convergence. The specific numbers in this guide were independently recomputed from the three original points; they are calculations for this example.

The complete original lesson

All original explanations, formulas and code

Every original passage, repeated explanation, formula, table, code line and image is retained below. Clearly marked notes distinguish verified corrections from the original calculations. Read the checked walkthrough above when calculating numerical results.

On a narrow screen, formulas, tables and code have their own horizontal scrolling regions. Focus a region with the keyboard and use the arrow keys to read its full width. The original image also opens at full size.

Mastering Gradient Descent in Machine Learning

Mastering Gradient Descent: A Comprehensive Guide to Optimizing Machine Learning Models

Gradient Descent is a foundational optimization algorithm used in machine learning to minimize a model’s cost function, typically Mean Squared Error (MSE) in linear regression. By iteratively adjusting the model’s parameters (weights), Gradient Descent seeks to find the optimal values that reduce the prediction error.

What is Gradient Descent?

Gradient Descent works by calculating the gradient (slope) of the cost function with respect to each parameter and moving in the direction opposite to the gradient. This process is repeated until the algorithm converges to a minimum point, ideally the global minimum, where the cost function is minimized.

Types of Learning Rates in Gradient Descent:

Too Small Learning Rate

  • Slow Convergence: A very small learning rate makes the algorithm take tiny steps toward the minimum, resulting in a long training process.
  • High Precision: Useful when fine adjustments are needed to avoid overshooting the minimum, but impractical for large-scale problems due to time inefficiency.

Too Large Learning Rate

  • Risk of Divergence: A large learning rate can cause the algorithm to overshoot the minimum, leading to oscillations or divergence where the cost function increases instead of decreases.
  • Fast Exploration: While it speeds up the training process initially, it often leads to instability and failure to converge to the optimal solution.

Optimal Learning Rate

  • Balanced Approach: Strikes a balance between speed and precision, enabling efficient convergence without overshooting.
  • Adaptive Techniques: Often found using methods like learning rate schedules or adaptive optimizers (e.g., Adam, RMSprop) that adjust the learning rate dynamically based on the training progress to achieve the best results.

How to Find the Optimal Learning Rate:

  1. Experimentation: Start with a small learning rate and gradually increase it, monitoring the cost function to see how quickly and stably it converges.
  2. Visualization: Plotting the cost function against the number of iterations can help identify the rate at which the function decreases most efficiently.
  3. Learning Rate Schedulers: Use algorithms that automatically adjust the learning rate during training to find and maintain the optimal rate.

By mastering the use of Gradient Descent and understanding the impact of different learning rates, you can significantly enhance the performance and accuracy of your machine learning models. For an in-depth guide and practical examples, check our detailed example of gradient decent and mathemathics behind it below, it has even visualising for better understanding Gradient Descent in Machine Learning, new Post about gradient decent comes soon too.

Introduction

Question: How can we find the optimal parameters (weights) of a linear regression model to minimize the error between the predicted values and the actual values using gradient descent? Purpose: The purpose of using gradient descent in linear regression is to iteratively adjust the parameters to minimize the cost function, thereby reducing the prediction error and improving the model’s accuracy.

Problem Setup

Consider a simple dataset:

x (Input Feature) y (Actual Output)
1 1
2 2
3 3

We are trying to fit a line through these points using the linear regression model: hθ(x)=θ0+θ1x

Cost Function

The cost function (Mean Squared Error, MSE) is: J(θ0,θ1)=12m∑i=1m(hθ(x(i))−y(i))2 Where:

  • m is the number of training examples.
  • hθ(x(i)) is the prediction.
  • y(i) is the actual value.

Gradient Descent Algorithm

The update rule: θj:=θj−α∂J∂θj Partial derivatives: ∂J∂θ0=1m∑i=1m(hθ(x(i))−y(i)) ∂J∂θ1=1m∑i=1m((hθ(x(i))−y(i))x(i))

Initial Parameters and Learning Rate Scenarios

Initial parameters: θ0=0, θ1=0 Learning rates:

  • Too Small: α=0.001
  • Too Large: α=1.0
  • Optimal: α=0.1

First Iteration Calculations

Initial Step

Initial values: θ0=0, θ1=0

Predictions and Errors for First Iteration

For each x and y pair: x=1: hθ(1)=θ0+θ1·1=0+0·1=0 Error: 0−1=−1 x=2: hθ(2)=θ0+θ1·2=0+0·2=0 Error: 0−2=−2 x=3: hθ(3)=θ0+θ1·3=0+0·3=0 Error: 0−3=−3

Calculate Gradients

∂J∂θ0=13[(−1)+(−2)+(−3)]=13·(−6)=−2 ∂J∂θ1=13[(−1)·1+(−2)·2+(−3)·3]=13(−1−4−9)=13(−14)=−4.67

Update Parameters

Too Small Learning Rate (α=0.001) θ0:=0−0.001·(−2)=0+0.002=0.002 θ1:=0−0.001·(−4.67)=0+0.00467=0.00467 New parameters: θ0=0.002, θ1=0.00467 Too Large Learning Rate (α=1.0) θ0:=0−1.0·(−2)=0+2=2 θ1:=0−1.0·(−4.67)=0+4.67=4.67 New parameters: θ0=2, θ1=4.67 Optimal Learning Rate (α=0.1) θ0:=0−0.1·(−2)=0+0.2=0.2 θ1:=0−0.1·(−4.67)=0+0.467=0.467 New parameters: θ0=0.2, θ1=0.467

Second Iteration Calculations

Using the new parameters from Iteration 1, we repeat the process.

Predictions and Errors for Second Iteration

Too Small Learning Rate (α=0.001) For x=1: hθ(1)=0.002+0.00467·1=0.00667 Error: 0.00667−1=−0.99333 For x=2: hθ(2)=0.002+0.00467·2=0.01134 Error: 0.01134−2=−1.98866 For x=3: hθ(3)=0.002+0.00467·3=0.01601 Error: 0.01601−3=−2.98399

Calculate Gradients

∂J∂θ0=13[(−0.99333)+(−1.98866)+(−2.98399)]=−1.98866 ∂J∂θ1=13[(−0.99333·1)+(−1.98866·2)+(−2.98399·3)]=−4.642

Update Parameters

Too Small Learning Rate (α=0.001) θ0:=0.002−0.001·(−1.98866)=0.002+0.00199=0.00399 θ1:=0.00467−0.001·(−4.642)=0.00467+0.004642=0.009312 New parameters: θ0=0.00399, θ1=0.009312 Too Large Learning Rate (α=1.0) For x=1: hθ(1)=2+4.67·1=6.67 Error: 6.67−1=5.67 For x=2: hθ(2)=2+4.67·2=11.34 Error: 11.34−2=9.34 For x=3: hθ(3)=2+4.67·3=16.01 Error: 16.01−3=13.01

Calculate Gradients

∂J∂θ0=13[(5.67)+(9.34)+(13.01)]=9.34 ∂J∂θ1=13[(5.67·1)+(9.34·2)+(13.01·3)]=25.68

Update Parameters

θ0:=2−1.0·(9.34)=2−9.34=−7.34 θ1:=4.67−1.0·(25.68)=4.67−25.68=−21.01 New parameters: θ0=−7.34, θ1=−21.01 Optimal Learning Rate (α=0.1) For x=1: hθ(1)=0.2+0.467·1=0.667 Error: 0.667−1=−0.333 For x=2: hθ(2)=0.2+0.467·2=1.134 Error: 1.134−2=−0.866 For x=3: hθ(3)=0.2+0.467·3=1.601 Error: 1.601−3=−1.399

Calculate Gradients

∂J∂θ0=13[(−0.333)+(−0.866)+(−1.399)]=−0.866 ∂J∂θ1=13[(−0.333·1)+(−0.866·2)+(−1.399·3)]=−2.087

Update Parameters

θ0:=0.2−0.1·(−0.866)=0.2+0.0866=0.2866 θ1:=0.467−0.1·(−2.087)=0.467+0.2087=0.6757 New parameters: θ0=0.2866, θ1=0.6757

Summary and Conclusion

Recap of All Learning Rates After Two Iterations

Too Small Learning Rate (α = 0.001)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 0.002 0.00467 2.8224
2 0.00399 0.009312 2.8000

Too Large Learning Rate (α = 1.0)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 2.0 4.67 289.4566
2 -7.34 -21.01 130547.34

Optimal Learning Rate (α = 0.1)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 0.2 0.467 2.8224
2 0.2866 0.6757 0.8453

Summary and Conclusion

Too Small Learning Rate (α=0.001):

  • Parameters change very slowly.
  • Requires many iterations to see significant improvement.
  • Slow convergence.

Too Large Learning Rate (α=1.0):

  • Parameters change drastically.
  • Can cause oscillations or divergence.
  • Unstable updates.

Optimal Learning Rate (α=0.1):

  • Balanced parameter updates.
  • Efficient and steady convergence.
  • Effective minimization of the cost function.

By iterating the gradient descent process and adjusting the learning rates, you can observe how different learning rates affect the convergence behavior. Choosing an appropriate learning rate is crucial for the success of the gradient descent algorithm in finding the optimal parameters that minimize the cost function.

Detailed Iteration Tables for Each Learning Rate

To illustrate the effect of different learning rates over more iterations, let’s extend the calculations to 10 iterations for each case.

Too Small Learning Rate (α=0.001)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 0.002 0.00467 2.8224
2 0.00399 0.009312 2.8000
3 0.00596002 0.01393686 2.7777
4 0.00790038 0.01854465 2.7555
5 0.00981127 0.02313539 2.7334
6 0.01169282 0.02770910 2.7113
7 0.01354511 0.03226579 2.6893
8 0.01536825 0.03680549 2.6673
9 0.01716232 0.04132821 2.6455
10 0.01892742 0.04583396 2.6237

Too Large Learning Rate (α=1.0)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 2.0 4.67 289.4566
2 -7.34 -21.01 130547.34
3 168.14 324.67 56204332.45
4 -1869.97 -3789.33 24198619784.67
5 20868.23 42235.23 10431543245643.2
6 -232379.41 -470356.77 4494906542418793
7 2587417.54 5233923.23 1936865214135914561
8 -28861584.66 -58312179.33 834791762445670257163.12
9 322698518.84 652732101.67 359859285416543287659346.23
10 -3609681725.34 -7302558313.33 1550911214587665378479098576.78

Optimal Learning Rate (α=0.1)

Iteration θ0 θ1 Cost Function J(θ0,θ1)
1 0.2 0.467 2.8224
2 0.2866 0.6757 0.8453
3 0.34704 0.81758 0.2536
4 0.38803 0.91167 0.0792
5 0.41538 0.97331 0.0294
6 0.43394 1.01213 0.0122
7 0.44732 1.03505 0.0058
8 0.45711 1.04765 0.0032
9 0.46437 1.05375 0.0021
10 0.46981 1.05693 0.0017

Analysis of the Results

Too Small Learning Rate (α=0.001):

  • The parameters θ0 and θ1 change very slowly.
  • The cost function decreases gradually, showing slow convergence.
  • Even after 10 iterations, significant improvement in the cost function is not observed.

Too Large Learning Rate (α=1.0):

  • The parameters change drastically, leading to unstable updates.
  • The cost function oscillates wildly and increases exponentially, indicating divergence.
  • The algorithm fails to converge to a minimum.

Optimal Learning Rate (α=0.1):

  • The parameters change in a balanced manner, ensuring efficient updates.
  • The cost function decreases steadily and converges to a minimum efficiently.
  • The algorithm finds the optimal parameters in a few iterations, showing effective convergence.

Conclusion

Too Small Learning Rate: Slow convergence and inefficient training. Suitable for highly precise adjustments but impractical for large-scale problems. Too Large Learning Rate: Unstable updates leading to divergence. Not suitable for practical use as it fails to minimize the cost function. Optimal Learning Rate: Efficient and balanced updates, ensuring effective minimization of the cost function. Ideal for practical applications. By observing the detailed iteration tables, we can see how different learning rates impact the convergence behavior of gradient descent. Choosing an appropriate learning rate is crucial for the success of the algorithm in finding the optimal parameters that minimize the cost function.

Note: Do you want to visualize Gradient Descent with Different Learning Rates which we explained?

Code for Visualization


import numpy as np
import matplotlib.pyplot as plt

# Cost function
def cost_function(theta_0, theta_1, X, y):
    m = len(y)
    return (1/(2*m)) * np.sum((theta_0 + theta_1*X - y)**2)

# Gradient descent algorithm
def gradient_descent(X, y, learning_rate, num_iterations):
    m = len(y)
    theta_0 = 0
    theta_1 = 0
    cost_history = []
    theta_history = []
    predictions = []

    for _ in range(num_iterations):
        prediction = theta_0 + theta_1 * X
        error = prediction - y
        theta_0 -= learning_rate * (1/m) * np.sum(error)
        theta_1 -= learning_rate * (1/m) * np.sum(error * X)
        
        cost = cost_function(theta_0, theta_1, X, y)
        cost_history.append(cost)
        theta_history.append((theta_0, theta_1))
        predictions.append(prediction)
    
    return theta_history, cost_history, predictions

# Dataset
X = np.array([1, 2, 3])
y = np.array([1, 2, 3])

# Parameters
num_iterations = 10

# Learning rates
small_learning_rate = 0.001
large_learning_rate = 1.0
optimal_learning_rate = 0.1

# Perform gradient descent for different learning rates
theta_history_small, cost_history_small, predictions_small = gradient_descent(X, y, small_learning_rate, num_iterations)
theta_history_large, cost_history_large, predictions_large = gradient_descent(X, y, large_learning_rate, num_iterations)
theta_history_optimal, cost_history_optimal, predictions_optimal = gradient_descent(X, y, optimal_learning_rate, num_iterations)

# Plotting the cost function history for different learning rates
plt.figure(figsize=(14, 5))

plt.subplot(1, 3, 1)
plt.plot(range(num_iterations), cost_history_small, label='Small Learning Rate (α = 0.001)')
plt.xlabel('Iteration')
plt.ylabel('Cost')
plt.title('Small Learning Rate')
plt.legend()

plt.subplot(1, 3, 2)
plt.plot(range(num_iterations), cost_history_large, label='Large Learning Rate (α = 1.0)')
plt.xlabel('Iteration')
plt.ylabel('Cost')
plt.title('Large Learning Rate')
plt.legend()

plt.subplot(1, 3, 3)
plt.plot(range(num_iterations), cost_history_optimal, label='Optimal Learning Rate (α = 0.1)')
plt.xlabel('Iteration')
plt.ylabel('Cost')
plt.title('Optimal Learning Rate')
plt.legend()

plt.tight_layout()
plt.show()

# Plotting the parameter updates for different learning rates
plt.figure(figsize=(14, 5))

plt.subplot(1, 3, 1)
theta_0_small, theta_1_small = zip(*theta_history_small)
plt.plot(range(num_iterations), theta_0_small, label='theta_0')
plt.plot(range(num_iterations), theta_1_small, label='theta_1')
plt.xlabel('Iteration')
plt.ylabel('Theta Value')
plt.title('Small Learning Rate')
plt.legend()

plt.subplot(1, 3, 2)
theta_0_large, theta_1_large = zip(*theta_history_large)
plt.plot(range(num_iterations), theta_0_large, label='theta_0')
plt.plot(range(num_iterations), theta_1_large, label='theta_1')
plt.xlabel('Iteration')
plt.ylabel('Theta Value')
plt.title('Large Learning Rate')
plt.legend()

plt.subplot(1, 3, 3)
theta_0_optimal, theta_1_optimal = zip(*theta_history_optimal)
plt.plot(range(num_iterations), theta_0_optimal, label='theta_0')
plt.plot(range(num_iterations), theta_1_optimal, label='theta_1')
plt.xlabel('Iteration')
plt.ylabel('Theta Value')
plt.title('Optimal Learning Rate')
plt.legend()

plt.tight_layout()
plt.show()

# Comparing actual vs predicted values
plt.figure(figsize=(14, 5))

plt.subplot(1, 3, 1)
for i in range(num_iterations):
    plt.plot(X, predictions_small[i], label=f'Iteration {i+1}')
plt.scatter(X, y, color='red', label='Actual Values')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Small Learning Rate')
plt.legend()

plt.subplot(1, 3, 2)
for i in range(num_iterations):
    plt.plot(X, predictions_large[i], label=f'Iteration {i+1}')
plt.scatter(X, y, color='red', label='Actual Values')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Large Learning Rate')
plt.legend()

plt.subplot(1, 3, 3)
for i in range(num_iterations):
    plt.plot(X, predictions_optimal[i], label=f'Iteration {i+1}')
plt.scatter(X, y, color='red', label='Actual Values')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Optimal Learning Rate')
plt.legend()

plt.tight_layout()
plt.show()

Explanation of the Output

This code generates three sets of plots:

  • Cost function history for different learning rates.
  • Parameter updates for different learning rates.
  • Actual vs predicted values for different learning rates.
  • Cost Function History: Shows how the cost function J(θ0,θ1) evolves over 10 iterations for each learning rate.
  • Parameter Updates: Shows how the parameters θ0 and θ1 evolve over 10 iterations for each learning rate.
  • Actual vs Predicted Values: Compares the predicted values against the actual values for each learning rate over 10 iterations.

Analysis

Too Small Learning Rate (α=0.001):

  • Convergence: Slow convergence with small updates to θ0 and θ1.
  • Cost Function: The cost decreases slowly.
  • Predictions: Predicted values get closer to the actual values very gradually.

Too Large Learning Rate (α=1.0):

  • Convergence: Divergence with large oscillations in parameter values.
  • Cost Function: The cost function oscillates and increases.
  • Predictions: Predicted values do not stabilize and vary widely, failing to converge.

Optimal Learning Rate (α=0.1):

  • Convergence: Balanced updates to θ0 and θ1, efficient convergence.
  • Cost Function: The cost decreases steadily and efficiently.
  • Predictions: Predicted values quickly converge to the actual values, demonstrating effective learning.

Below is the Drawing for comparison as explained :

Original nine-panel gradient descent visualization comparing costs, parameter values and fitted lines for learning rates 0.001, 1.0 and 0.1.
Original visualization retained: columns compare the three learning rates; rows show cost, parameter values and predictions. Refer to the checked supplementary figures and notes when interpreting its labels and iteration numbering. Open the full-size original image.

Common questions

Gradient descent questions, answered

What is gradient descent in machine learning?

Gradient descent is an iterative optimization method. It computes the gradient of a loss function with respect to model parameters and moves the parameters in the opposite direction, using a learning rate to control each step.

What does the learning rate control?

The learning rate scales the parameter update. A small rate can make progress slow; a rate that is too large can cause overshooting or divergence. A useful value depends on the dataset, feature scales and objective.

Why does this example divide the squared errors by 2m?

The objective is half the mean squared error: the sum of squared errors divided by twice the number of examples. The factor of one half simplifies its derivatives. Its cost values and gradients differ from ordinary MSE, although both objectives have the same minimizing parameters.

What are the correct first two updates for learning rate 0.1?

Starting with both parameters at zero on the points (1, 1), (2, 2) and (3, 3), the first simultaneous update gives an intercept of 0.2, slope of approximately 0.466667 and half-MSE of 0.470370. The second gives an intercept of approximately 0.286667, slope of 0.675556 and half-MSE of 0.100691.

Is a learning rate of 0.1 always optimal?

No. It is a stable illustration for the three-point dataset and half-MSE objective used here. The exact fitted line is y = x. Ten updates at 0.1 improve the fit substantially but do not yet reach that exact solution.

What is the difference between batch, stochastic and mini-batch gradient descent?

Batch gradient descent uses the entire training set for each update. Stochastic gradient descent uses one example at a time. Mini-batch gradient descent uses a subset. Day 8 explains their behavior; this Day 7 example uses full-batch updates.

Continue the series

Next: which data does each update use?

You have now followed full-batch updates using all three examples. Next, compare batch, stochastic and mini-batch gradient descent, and see how their update sizes change the training process.

Editorial note: the additional calculations were checked using exact rational arithmetic, an independent NumPy implementation and the original Python routine. The new charts use those computed results. The original lesson remains available inline for comparison.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store