Fit a Line by Batch Gradient Descent with Standardized Input
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Implement full-batch gradient descent for a one-feature least-squares line, standardizing the input, and map the learned parameters back to the original scale.
You are given two equal-length lists of numbers: inputs xs and targets ys. Fit the line y_hat = slope * x + intercept using batch gradient descent, written by hand. Do not call any library routine that fits the line for you.
Return [slope, intercept] in the original units of xs and ys.
Procedure
Follow this procedure so that your results match the expected values.
- Loss. Use mean squared error,
L = (1/n) * sum((pred_i - y_i)^2). - Edge cases.
- If
xsis empty, return[0.0, 0.0]. - Let
mean_xbe the mean ofxsandsd_xthe population standard deviation (divide byn). Ifsd_x == 0, every input is identical and the slope cannot be determined. Return[0.0, mean(ys)].
- If
- Standardize the input. Compute
z_i = (x_i - mean_x) / sd_x. Run gradient descent onz, not onx, so that one fixed step size is stable whatever the magnitude of the inputs. - Gradient descent on the standardized data.
- Start with
w = 0.0andb = 0.0. - Perform exactly
1000iterations with learning rate0.1. - In each iteration, compute
error_i = w * z_i + b - y_ifor every example using the currentwandb. Then update both parameters at once:grad_w = (2/n) * sum(error_i * z_i)grad_b = (2/n) * sum(error_i)w -= 0.1 * grad_wb -= 0.1 * grad_b
- Start with
- Convert back to the original scale.
slope = w / sd_xintercept = b - slope * mean_x
- Return
[slope, intercept].
With these settings the procedure converges to the ordinary least-squares line, so the result should agree with the closed-form fit up to floating-point error.
Constraints
0 <= len(xs) == len(ys) <= 1000- Values in
xsandysare finite real numbers of moderate magnitude (about|v| <= 1000). - Return a list of two floats:
[slope, intercept]. - Use only the Python standard library.
Examples
Example 1
Input: fit_line_gd([1, 2, 3, 4], [3, 5, 7, 9])
Output: [1.9999999999999991, 1]
Example 2
Input: fit_line_gd([0, 1, 2, 3, 4], [5, 4, 3, 2, 1])
Output: [-0.9999999999999999, 4.999999999999999]
Example 3
Input: fit_line_gd([1, 2, 3, 4, 5], [2, 3, 5, 4, 6])
Output: [0.8999999999999997, 1.2999999999999998]
Hints
Hint 1
Differentiate the mean squared error with respect to the slope and the intercept. Each gradient is a sum over all examples of the prediction error, multiplied by the input for the slope and by 1 for the intercept.
Hint 2
A fixed learning rate is only safe when the input has a sensible scale. Standardize the input (subtract the mean, divide by the standard deviation) before descending, so the loss surface is well conditioned.
Hint 3
To undo the standardization, substitute z = (x - mean_x) / sd_x into w*z + b. The slope becomes w / sd_x and the intercept becomes b - slope * mean_x. Do not forget the empty-input and constant-input cases.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The loss is the mean squared error L(w, b) = (1/n) * sum((w*z_i + b - y_i)^2). Its partial derivatives are:
dL/dw = (2/n) * sum(err_i * z_i)dL/db = (2/n) * sum(err_i)
where err_i = w*z_i + b - y_i.
Plain gradient descent on raw x can converge slowly or diverge, because the curvature in the w direction scales with the size of x. To avoid this, the solution first standardizes the input to z = (x - mean_x) / sd_x. Then z has mean 0 and variance 1, and the loss surface is a round bowl. Its Hessian is 2 * I, so each gradient step with rate 0.1 shrinks the distance to the optimum by a factor of 0.8. After 1000 iterations the remaining error is negligible (about 0.8^1000), so the result equals the least-squares solution up to floating-point rounding.
After training, the line in standardized space is w*z + b = (w/sd_x)*x + (b - (w/sd_x)*mean_x). This gives:
slope = w / sd_xintercept = b - slope * mean_x
Edge cases
- Empty input: return
[0.0, 0.0]. - Constant
xs: the standard deviation is 0, so standardizing would divide by zero and the slope is not identifiable. The minimum-MSE line is flat, so return[0.0, mean(ys)].
Complexity
- Time:
O(iterations * n), which isO(1000 * n)with a fixed iteration count. - Space:
O(n)for the standardized inputs.
Reference solution
from typing import List
import math
def fit_line_gd(xs: List[float], ys: List[float]) -> List[float]:
n = len(xs)
if n == 0:
return [0.0, 0.0]
mean_x = sum(xs) / n
variance = sum((v - mean_x) ** 2 for v in xs) / n
sd_x = math.sqrt(variance)
if sd_x == 0.0:
return [0.0, sum(ys) / n]
z = [(v - mean_x) / sd_x for v in xs]
w = 0.0
b = 0.0
lr = 0.1
for _ in range(1000):
grad_w = 0.0
grad_b = 0.0
for zi, yi in zip(z, ys):
err = w * zi + b - yi
grad_w += err * zi
grad_b += err
grad_w *= 2.0 / n
grad_b *= 2.0 / n
w -= lr * grad_w
b -= lr * grad_b
slope = w / sd_x
intercept = b - slope * mean_x
return [slope, intercept]