All problems
Linear Regression
Problem
Fit a simple linear regression y = a + b*x using least squares.
b = sum((x_i - mean_x) * (y_i - mean_y)) / sum((x_i - mean_x)^2) a = mean_y - b * mean_x
Return [a, b] = [intercept, slope]. If the denominator is 0, return [mean_y, 0.0].
Hint
b is the slope (cov(x,y) / var(x)); a is the intercept that makes the line pass through (mean_x, mean_y).
Test cases
case 1
in: [[1,2,3,4,5],[3,5,7,9,11]]
expected: [1,2]
case 2
in: [[0,1,2,3],[1,3,5,7]]
expected: [1,2]
case 3
in: [[1,2,3],[2,4,6]]
expected: [0,2]
case 4
in: [[5,5,5],[3,4,5]]
expected: [4,0]
Starter codePython
def linear_regression_fit(X, y):
# Returns [intercept, slope]
# Your code here
pass4 test cases · run your code against them in the editor