Skip to content

Simple linear regression, step by step

6 min read

Short answer

The least-squares line minimizes the sum of squared vertical errors. Its slope is b=SxySxx=∑(x−xˉ)(y−yˉ)∑(x−xˉ)2b=\dfrac{S_{xy}}{S_{xx}}=\dfrac{\sum(x-\bar x)(y-\bar y)}{\sum(x-\bar x)^2} and its intercept is a=yˉ−bxˉa=\bar y-b\bar x. R2R^2 is the fraction of the variation in yy explained by the line.

Diagramŷ = 1.3 + 0.9x
The fitted line passes through the point of means (3, 4).

Interpreting the numbers

The slope is the predicted change in yy for a one-unit increase in xx. The intercept is the predicted yy at x=0x=0, which may be outside the data and meaningless. The correlation r=SxySxxSyyr=\dfrac{S_{xy}}{\sqrt{S_{xx}S_{yy}}} and R2=r2R^2=r^2 for simple regression.

Why this line

Setting the derivatives of ∑(yi−a−bxi)2\sum(y_i-a-bx_i)^2 with respect to aa and bb to zero gives the formulas above. The same result comes from projecting the vector of yy values onto the span of the constant and xx vectors (least squares in linear algebra).

Worked example

Fit a line to (1,2),(2,3),(3,5),(4,4),(5,6)(1,2),(2,3),(3,5),(4,4),(5,6) and predict yy at x=6x=6.

xˉ=3\bar x=3, yˉ=4\bar y=4. Sxy=(−2)(−2)+(−1)(−1)+0+0+2⋅2=9S_{xy}=(-2)(-2)+(-1)(-1)+0+0+2\cdot2=9 and Sxx=10S_{xx}=10, so b=0.9b=0.9, a=4−2.7=1.3a=4-2.7=1.3. Prediction at 66: 1.3+5.4=6.71.3+5.4=6.7. Also Syy=10S_{yy}=10, so r=0.9r=0.9 and R2=0.81R^2=0.81.

Try it yourself

If r=−0.6r=-0.6 for a fitted line, what is R2R^2 and what does it mean?

Show the answer

R2=0.36R^2=0.36: the line explains 36% of the variation in yy. The negative sign of rr only tells you the slope is negative.

Keep going with practice

Vidi's linear algebra lessons show regression as an orthogonal projection, the geometry behind R².