v9.1.1
Menu

Gradient Descent for Linear Regression

hardFREELinear RegressionMachine Learning 1

Implement batch gradient descent for simple linear regression.

Given data points (x,y)(x, y), initial weight ww and bias bb, learning rate α\alpha, and number of iterations, update ww and bb to minimize Mean Squared Error:

MSE=1n∑i=1n(yi−(w⋅xi+b))2MSE = \frac{1}{n} \sum_{i=1}^{n} (y_i - (w \cdot x_i + b))^2

The gradients are: ∂MSE∂w=−2n∑i=1nxi(yi−(w⋅xi+b))\frac{\partial MSE}{\partial w} = \frac{-2}{n} \sum_{i=1}^{n} x_i(y_i - (w \cdot x_i + b)) ∂MSE∂b=−2n∑i=1n(yi−(w⋅xi+b))\frac{\partial MSE}{\partial b} = \frac{-2}{n} \sum_{i=1}^{n} (y_i - (w \cdot x_i + b))

Each iteration computes both gradients from the current ww and bb, then updates them together: w←w−α∂MSE∂w,b←b−α∂MSE∂bw \leftarrow w - \alpha \frac{\partial MSE}{\partial w}, \qquad b \leftarrow b - \alpha \frac{\partial MSE}{\partial b}

Return a tuple (w, b) after all iterations, both rounded to 4 decimal places.

Example

Input
X = [1, 2, 3]
y = [2, 4, 6]
w = 0.0, b = 0.0
learning_rate = 0.1, iterations = 100
Output
(1.9715, 0.0647)
Reasoning
  • Inputs: three points (1,2),(2,4),(3,6)(1, 2), (2, 4), (3, 6), so n=3n = 3. They lie exactly on y=2xy = 2x, so the ideal fit is w=2w = 2, b=0b = 0. Start: w=b=0w = b = 0, α=0.1\alpha = 0.1, 100 updates.
  • First update: with w=b=0w = b = 0 every prediction is 00, so the residuals yi−(wxi+b)y_i - (w x_i + b) are just 2,4,62, 4, 6.
  • ∂MSE∂w=−23(1⋅2+2⋅4+3⋅6)=−23⋅28≈−18.6667\frac{\partial MSE}{\partial w} = \frac{-2}{3}(1 \cdot 2 + 2 \cdot 4 + 3 \cdot 6) = \frac{-2}{3} \cdot 28 \approx -18.6667 and ∂MSE∂b=−23(2+4+6)=−8\frac{\partial MSE}{\partial b} = \frac{-2}{3}(2 + 4 + 6) = -8.
  • Stepping against the gradients: w=0−0.1⋅(−18.6667)=1.8667w = 0 - 0.1 \cdot (-18.6667) = 1.8667 and b=0−0.1⋅(−8)=0.8b = 0 - 0.1 \cdot (-8) = 0.8.
  • Later updates: bb overshot, so the residuals turn negative and bb slowly drains toward 0 while ww creeps toward 2.
  • Output: after 100 updates, rounded to 4 decimal places, (w,b)=(w, b) = (1.9715, 0.0647). Notice it hasn't reached (2,0)(2, 0) yet; more iterations get closer.

Constraints

  • X and y are lists of equal length
  • learning_rate > 0, iterations >= 1
  • Initial w and b are given as floats
  • Return tuple (w, b) rounded to 4 decimal places

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.