PIXELBANKv8.2.1
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=1ni=1n(yi(wxi+b))2MSE = \frac{1}{n} \sum_{i=1}^{n} (y_i - (w \cdot x_i + b))^2

The gradients are: MSEw=2ni=1nxi(yi(wxi+b))\frac{\partial MSE}{\partial w} = \frac{-2}{n} \sum_{i=1}^{n} x_i(y_i - (w \cdot x_i + b)) MSEb=2ni=1n(yi(wxi+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 MSEw\frac{\partial MSE}{\partial w} and MSEb\frac{\partial MSE}{\partial b} using the given formulas: MSEw=2ni=1nxi(yi(wxi+b))\frac{\partial MSE}{\partial w} = \frac{-2}{n} \sum_{i=1}^{n} x_i(y_i - (w \cdot x_i + b)) and MSEb=2ni=1n(yi(wxi+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αMSEww = w - \alpha \cdot \frac{\partial MSE}{\partial w} and b=bαMSEbb = 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=1ni=1n(yi(wxi+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
Editor

Test Results

0/0
Run code to see test results.