PIXELBANKv9.1.0
Menu

Gradient Descent for Linear Regression

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))

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:
  • We start with the given data points (x,y)(x, y): (1,2)(1, 2), (2,4)(2, 4), (3,6)(3, 6), initial weight w=0.0w = 0.0, bias b=0.0b = 0.0, learning rate α=0.1\alpha = 0.1, and number of iterations =100= 100.
  • We calculate the gradients ∂MSE∂w\frac{\partial MSE}{\partial w} and ∂MSE∂b\frac{\partial MSE}{\partial b} using the given formulas: ∂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)) and ∂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)), and update ww and bb using w=w−α⋅∂MSE∂ww = w - \alpha \cdot \frac{\partial MSE}{\partial w} and b=b−α⋅∂MSE∂bb = b - \alpha \cdot \frac{\partial MSE}{\partial b} for each iteration.
  • We repeat the process of calculating gradients and updating ww and bb for 100100 iterations, which minimizes the 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.
  • After 100100 iterations, we obtain the updated values of ww and bb, which are then rounded to 44 decimal places, resulting in the output (1.9715,0.0647)(1.9715, 0.0647).

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
solution.py

Test Results

0/0
Run code to see test results.
Gradient Descent for Linear Regression - Hard | PixelBank