v9.1.1
Menu

Simple Linear Regression

easyFREELinear RegressionMachine Learning 1

Implement simple linear regression using the closed-form (least squares) solution.

Given a list of xx values and a list of yy values, compute the slope mm and intercept bb of the best-fit line y=mx+by = mx + b.

The formulas are: m=n∑xiyi−∑xi∑yin∑xi2−(∑xi)2m = \frac{n\sum x_i y_i - \sum x_i \sum y_i}{n\sum x_i^2 - (\sum x_i)^2} b=yˉ−mxˉb = \bar{y} - m\bar{x}

where nn is the number of data points and xˉ\bar{x}, yˉ\bar{y} are the means.

Return a tuple (slope, intercept), both rounded to 4 decimal places.

Example

Input
X = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 5]
Output
(0.6, 2.2)
Reasoning
  • Inputs: X holds the n=5n = 5 positions xi=1,…,5x_i = 1,\dots,5 and y the observed values 2,4,5,4,52, 4, 5, 4, 5 at those positions. We want the line y=mx+by = mx + b minimising squared vertical error.
  • The four sums: ∑xi=15\sum x_i = 15, ∑yi=20\sum y_i = 20, ∑xiyi=2+8+15+16+25=66\sum x_i y_i = 2 + 8 + 15 + 16 + 25 = 66 and ∑xi2=1+4+9+16+25=55\sum x_i^2 = 1 + 4 + 9 + 16 + 25 = 55.
  • Slope: m=5⋅66−15⋅205⋅55−152=330−300275−225=3050=0.6m = \frac{5 \cdot 66 - 15 \cdot 20}{5 \cdot 55 - 15^2} = \frac{330 - 300}{275 - 225} = \frac{30}{50} = 0.6. Each unit of xx adds 0.60.6 to the fitted yy.
  • Intercept: the means are xˉ=3\bar{x} = 3 and yˉ=4\bar{y} = 4, so b=4−0.6×3=2.2b = 4 - 0.6 \times 3 = 2.2.
  • Output: the pair (0.6, 2.2), slope first, each rounded to 4 decimal places.
  • Notice that the line passes through the mean point (3,4)(3, 4). Its predictions 2.8,3.4,4.0,4.6,5.22.8, 3.4, 4.0, 4.6, 5.2 leave residuals −0.8,0.6,1.0,−0.6,−0.2-0.8, 0.6, 1.0, -0.6, -0.2, which sum to zero.

Constraints

  • Input: two lists of equal length (at least 2 elements)
  • Return a tuple (slope, intercept) rounded to 4 decimal places
  • Use only basic Python (no numpy)

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.