Simple regression by hand
Quick answer
Simple linear regression models a numeric response as b + w*x using one predictor. The least-squares slope measures the fitted change in target per one-unit change in x; the intercept is the predicted value at x=0. Both are estimated from training observations, not from the test set. All code examples run locally in Python 3.13.5; library examples use scikit-learn 1.8.0 or NumPy 2.3.5. ByteMind package execution is unverified.
Calculate centered sums
x=[0,1,2,3]y=[1,4,5,8]xbar=sum(x)/len(x); ybar=sum(y)/len(y)sxx=sum((t-xbar)**2 for t in x)sxy=sum((t-xbar)*(v-ybar) for t,v in zip(x,y))w=sxy/sxx; b=ybar-w*xbarprint(round(w,2), round(b,2))print(round(b+4*w,2))Expected output:
2.2 1.210.0The fitted prediction at 4 is 10; its reliability outside training support is not established.
How it works
Set the intercept derivative to zero: b = mean(y) - wmean(x). Substitute this into the slope equation to obtain w = sum((x_i-xbar)(y_i-ybar))/sum((x_i-xbar)**2). The denominator is zero exactly when all x values are equal; then infinitely many slope/intercept pairs predict the same training mean. A constant mean prediction is a valid fallback, not evidence of a uniquely estimated slope. For x=[0,1,2,3], y=[1,4,5,8], xbar=1.5, ybar=4.5, centered cross-product=11 and centered squared sum=5. The fitted slope is 2.2 and intercept 1.2. The line passes through (xbar,ybar). Centered sums avoid subtracting two large nearly equal raw moments, though floating point limits still apply. Slope units are target units per feature unit. An intercept outside the observed feature range may have little practical meaning.
Check with scikit-learn
from sklearn.linear_model import LinearRegressionm=LinearRegression().fit([[0],[1],[2],[3]],[1,4,5,8])print(round(float(m.coef_[0]),2),round(float(m.intercept_),2))print(round(float(m.predict([[4]])[0]),2))Expected output:
2.2 1.210.0The library agrees with the centered-sum derivation to the shown precision.
Common mistakes
Do not fit a line through the first and last observations and assume that minimizes all residuals. Do not divide by zero or silently report a uniquely determined slope when x is constant.
Practice and next steps
Fit x=[1,2,3], y=[2,4,6] by hand, then predict at x=4. Explain why a prediction far outside this range is extrapolation. Complete the chapter knowledge check and coding exercise. Next: Multiple regression and intercept.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Simple regression by hand — knowledge check
Apply simple regression by hand to small regression fixtures.
Which denominator appears in the centered slope formula?
A line with slope 3 and intercept -2 predicts what at x=4?
If all x values equal 5, what happens to the slope?
Where does a fitted OLS line with intercept pass?
A slope in seconds per kilogram describes what?