Fit a Line by Full-Batch Gradient Descent on Squared Error
Arrays & HashingAuto-graded · 19 test casesLast updated
Implement full-batch gradient descent for a one-feature linear model, using gradients from the old parameters at every step to update the slope and intercept together.
Fit a Line by Full-Batch Gradient Descent
You are given paired observations (x_i, y_i) and asked to fit a straight line prediction = slope * x + intercept by minimizing the mean squared error with plain (full-batch) gradient descent. Write the training loop yourself.
Task
Implement a function that takes:
xs: a list ofnfeature values,ys: a list ofntarget values (same length asxs),step_size: the learning rate,num_steps: how many gradient descent iterations to run.
The function must return the learned parameters as a list [slope, intercept].
Procedure
-
Start with
slope = 0.0andintercept = 0.0. -
The loss is the mean squared error over all samples:
loss = (1/n) * sum((slope * x_i + intercept - y_i)^2) -
In each of the
num_stepsiterations:- Use all samples to compute the gradient of the loss with respect to both parameters, evaluated at the current
slopeandintercept. - Then update both parameters by subtracting
step_sizetimes their respective gradients.
- Use all samples to compute the gradient of the loss with respect to both parameters, evaluated at the current
-
After the final iteration, return
[slope, intercept].
Important details
- The update must be simultaneous: both gradients are computed from the parameter values at the start of the iteration. Do not change the slope and then compute the intercept's gradient using the new slope.
- Run exactly
num_stepsiterations. Do not stop early and do not add any convergence checks, clipping, or feature scaling. - Do not regularize either parameter.
- Return a Python list of two floats, in the order
[slope, intercept]. - Do not guard against divergence: if the step size is too large, the values simply blow up as the arithmetic dictates.
Constraints
xsandyshave the same lengthn, withn >= 1.step_sizeis a positive float.num_stepsis a positive integer.- Values are real numbers (floats or ints).
Examples
Example 1
Input: fit_line_gd([1, 2, 3], [2, 4, 6], 0.01, 1000)
Output: [1.97078250602932, 0.06641823135781669]
Example 2
Input: fit_line_gd([0, 1, 2, 3], [1, 3, 5, 7], 0.05, 500)
Output: [2.0000000067412476, 0.9999999856071559]
Example 3
Input: fit_line_gd([1, 2, 3, 4, 5], [5, 5, 5, 5, 5], 0.01, 1000)
Output: [0.04350115835152537, 4.8429470155081935]
Hints
Hint 1
Write the residual for each sample as slope * x_i + intercept - y_i. Both gradients can be built from these residuals.
Hint 2
The gradient of the mean squared error is (2/n) * sum(residual * x_i) for the slope and (2/n) * sum(residual) for the intercept.
Hint 3
Compute both gradients completely before changing either parameter, so that the update is simultaneous, then apply both updates.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let the residual of sample i be r_i = slope * x_i + intercept - y_i. Differentiating the mean squared error (1/n) * sum(r_i^2) with the chain rule gives:
- derivative with respect to the slope:
(2/n) * sum(r_i * x_i) - derivative with respect to the intercept:
(2/n) * sum(r_i)
Each iteration does the following:
- Loop over all samples, computing
r_ifrom the current(slope, intercept)and accumulating the two sums. - Scale both sums by
2/nto get the gradients. - Subtract
step_sizetimes each gradient from the matching parameter.
Starting from (0, 0), repeat this exactly num_steps times and return [slope, intercept].
Why it is correct
The gradients are the exact derivatives of the loss, so each step moves the parameters in the direction of steepest decrease of the MSE. Because both gradients are fully computed before either parameter is modified, the update is truly simultaneous. Updating the slope first and then reusing it for the intercept's gradient would be a different algorithm (coordinate descent) and would give different numbers. Running a fixed number of iterations with no early stopping makes the output deterministic, so it matches the expected values exactly, including the cases where convergence is only partial (the loss is a convex quadratic, but a small step size leaves the poorly conditioned direction still converging).
Complexity
- Time:
O(n * num_steps), one pass over the data per iteration. - Space:
O(1)extra, since only running sums are kept.
Reference solution
from typing import List
def fit_line_gd(xs: List[float], ys: List[float], step_size: float, num_steps: int) -> List[float]:
n = len(xs)
slope = 0.0
intercept = 0.0
for _ in range(num_steps):
grad_slope = 0.0
grad_intercept = 0.0
# Accumulate using the parameters from the start of this iteration.
for x, t in zip(xs, ys):
residual = slope * x + intercept - t
grad_slope += residual * x
grad_intercept += residual
grad_slope *= 2.0 / n
grad_intercept *= 2.0 / n
# Simultaneous update.
slope -= step_size * grad_slope
intercept -= step_size * grad_intercept
return [slope, intercept]