How To Implement Simple Linear Regression From Scratch With Python
Linear regression is one of the oldest and most widely-used prediction methods in statistics. It's also one of the best algorithms to build from scratch: the maths is tractable, the code is short, and the mental model transfers directly to more advanced techniques.
In this walkthrough we implement simple linear regression— a single input variable predicting a single output — in pure Python. Every snippet below runs live in your browser via Pyodide. Hit Run and edit anything you like.
The model
Simple linear regression fits a straight line through the data:
y = b0 + b1 * x
We need to estimate two coefficients from the training data — the intercept b0 and the slope b1. The closed-form solution uses the mean, variance and covariance of the inputs and outputs.
1. Mean and variance
Start with two helpers: the arithmetic mean and the sum of squared differences from the mean. We use a tiny five-row contrived dataset so you can verify the numbers by hand.
2. Covariance
Covariance tells us how two variables change together. It generalises variance from one variable to two, and it's the numerator in our slope estimate.
3. Estimating coefficients
With mean, variance and covariance in hand, the slope and intercept fall out directly:
b1 = covariance(x, y) / variance(x) b0 = mean(y) - b1 * mean(x)
4. Fit, predict, evaluate
Wrap it all up: fit the model on the training rows, predict the test rows, then score with root mean squared error (RMSE).
5. Real data: Swedish Auto Insurance
The Swedish Auto Insurance dataset relates the number of claims to the total payment for those claims (in thousands of Swedish Kronor). 63 rows, one input, one output — a perfect fit for simple linear regression. The runner below fetches the CSV over the network, splits 60/40 into train and test, and reports the fitted model and the test RMSE.
Expect an RMSE around 35 thousand Kronor — a solid baseline that any more sophisticated model has to beat.
Extensions
- Try multiple random train/test splits and average the RMSE.
- Extend the algorithm to multivariate linear regression using the normal equation.
- Add a baseline (predict the mean of
y) and confirm your linear model beats it.
Adapted from Jason Brownlee's original tutorial. Python execution is powered by Pyodide, running entirely in your browser — no server required.