Linear Regression from Scratch

Medium
machine-learning Google Meta

Implement simple linear regression (one feature) using the ordinary least squares closed-form solution. Return the slope and intercept.

Formula

  • slope = sum((xi - x_mean)(yi - y_mean)) / sum((xi - x_mean)^2)
  • intercept = y_mean - slope * x_mean

Example

linear_regression([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
# => (0.6, 2.2)

Test Cases

Python Editor

Output

Click "Run" to see results...