How to Fit a Regression Line by Least Squares

Fits the line y = ax + b that best matches the points by least squares. The slope is the covariance ÷ the variance of x, and the intercept is ȳ − a·x̄. R² measures how well the line fits.

A regression line is the straight line y=ax+by = ax + b that best fits a cloud of points. "Best" means that the sum of the squared vertical gaps between the points and the line is as small as possible — the method of least squares.

a=sxyσx2b=yˉaxˉa = \dfrac{s_{xy}}{\sigma_x^2} \qquad b = \bar{y} - a\bar{x}

The slope aa is the covariance divided by the variance of xx. The intercept bb follows from the fact that the line always passes through the point (xˉ,yˉ)(\bar{x}, \bar{y}).

Example

With xx = 1, 2, 3, 4, 5 and yy = 2, 4, 5, 4, 5, we have xˉ=3\bar{x} = 3, yˉ=4\bar{y} = 4, a covariance of 1.2 and a variance of xx equal to 2.

a=1.22=0.6b=40.6×3=2.2a = \dfrac{1.2}{2} = 0.6 \qquad b = 4 - 0.6 \times 3 = 2.2

The regression line is y=0.6x+2.2y = 0.6x + 2.2, so an xx of 6 predicts a yy of 5.8.

R squared

The coefficient of determination R2R^2 is the square of the correlation coefficient. It is the share of the variation in yy that the line accounts for.

Here r=0.7746r = 0.7746, so R2=0.6R^2 = 0.6: the line explains 60% of the variation in yy.

Watch out