Machine learning algorithms › Linear models
What is linear regression? A gentle guide to fitting lines
What linear regression is, how least squares picks the weights, how to read coefficients and R², and when it fits or falls short, shown with code I ran.
When you start learning machine learning, linear regression is one of the first names you’ll run into. Google’s Machine Learning Crash Course opens its section on models with linear regression, and people building more complex models often fit a linear regression first to get a baseline score. Still, if someone asks what it actually is, perhaps “drawing a straight line through the points” is the only answer that comes to mind.
Linear regression is a model that predicts a continuous number by multiplying each feature by a weight, adding them up, and adding an intercept. A feature is an input value used for the prediction, and the intercept is what the model predicts when every feature is zero, so in words, prediction = weight × feature + intercept. The weights are chosen so that the sum of the squared differences between the predictions and the actual values is as small as possible. That’s why the method is called least squares.
Where least squares and the name “regression” came from
The idea of least squares came out of astronomy in the early 1800s. In 1805, Adrien-Marie Legendre published a book on computing the orbits of comets. In its appendix, he introduced this method and called it the method of least squares (méthode des moindres quarrés). Four years later, Carl Friedrich Gauss used the same principle in Theoria motus corporum coelestium and wrote that he had been using it since 1795. In a 1981 paper, Stephen Stigler calls the question of who came first the most famous priority dispute in the history of statistics.
The name “regression” comes from Francis Galton’s work on heredity (Stanton, 2001). In his 1886 paper Regression towards Mediocrity in Hereditary Stature, Galton wrote that a child’s deviation in height from the average was, on average, two-thirds of the parents’ deviation. Children of tall parents tended to be less tall and children of short parents less short, moving back toward the average, and that is what he called regression.
Trying it on the diabetes dataset
Let’s try it on the diabetes dataset that ships with scikit-learn. Each of its 442 patients has 10 features, including age, sex, BMI, blood pressure, and six blood serum measurements, and the label is a number that measures how far the disease progressed one year later. According to the docs, each feature column has been mean centered and divided by its standard deviation times the square root of the number of patients, which is why the values look so small.
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True, as_frame=True)
print(X.shape, X["bmi"].head(3).round(3).tolist())
# Keep 25% of the patients aside as a test set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
print(len(X_train), len(X_test))
(442, 10) [0.062, -0.051, 0.044]
331 111
That leaves 331 patients to learn from and 111 for testing. Now let’s train a simple linear regression that uses only BMI and a multiple linear regression that uses all 10 features. For comparison, we’ll also score a model that always answers the average.
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score, root_mean_squared_error
def evaluate(name, model, cols):
model.fit(X_train[cols], y_train) # find the weights on the training set
pred = model.predict(X_test[cols])
print(f"{name:<9} R2 {r2_score(y_test, pred):6.3f} "
f"RMSE {root_mean_squared_error(y_test, pred):.1f} "
f"MAE {mean_absolute_error(y_test, pred):.1f}")
return model
evaluate("mean only", DummyRegressor(), ["bmi"]) # always guesses the average
simple = evaluate("bmi only", LinearRegression(), ["bmi"])
multi = evaluate("all 10", LinearRegression(), list(X.columns))
print(f"bmi only: weight {simple.coef_[0]:.1f}, intercept {simple.intercept_:.1f}")
print("all 10:", " ".join(f"{c} {w:.0f}" for c, w in zip(X.columns, multi.coef_)))
mean only R2 -0.014 RMSE 74.9 MAE 65.5
bmi only R2 0.317 RMSE 61.4 MAE 49.8
all 10 R2 0.485 RMSE 53.4 MAE 41.5
bmi only: weight 975.3, intercept 152.1
all 10: age 48 sex -242 bmi 532 bp 382 s1 -919 s2 508 s3 117 s4 269 s5 696 s6 26
The BMI-only model is the straight line prediction = 975.3 × BMI + 152.1. Using all ten features raised the test R² from 0.317 to 0.485.
The numbers that tell you how close the predictions are
A regression model is judged by its errors, the gaps between the predictions and the actual values. Here are four common measures from scikit-learn’s regression metrics docs.
| Metric | What it measures | How to read it |
|---|---|---|
| MSE | The average of the squared errors | What least squares minimizes, but in squared units |
| RMSE | The square root of the MSE | Same units as the label, sensitive to large errors |
| MAE | The average of the absolute errors | Same units as the label, less swayed by large errors |
| R² (coefficient of determination) | How much the error shrank compared with answering the average | 1 is best, and 0 is no better than the average |
So the multiple regression’s RMSE of 53.4 and MAE of 41.5 mean it misses the disease progression score by roughly 40 to 50 points. R² is best at 1, but the docs point out that it can also be negative, because a model can be arbitrarily worse. The “mean only” row is one example. It answered the training set’s average, which differed a little from the test set’s average, so it scored -0.014.
How to read the coefficients
A coefficient in a multiple regression tells you how much the prediction changes when that feature goes up by 1 while the other features stay the same. But the BMI weight of 532 is hard to read that way. According to the load_diabetes docs, every feature lies between -0.2 and 0.2, so BMI never actually goes up by 1. The size of a coefficient depends on the feature’s units and scale, so let’s ask for the original units with scaled=False and train again.
# Same patients, original units (BMI in kg/m^2)
raw = load_diabetes(as_frame=True, scaled=False).data
raw_train, raw_test = raw.loc[X_train.index], raw.loc[X_test.index]
for cols in (["bmi"], list(X.columns)):
m = LinearRegression().fit(raw_train[cols], y_train)
r2 = r2_score(y_test, m.predict(raw_test[cols]))
print(f"{len(cols):>2} features: bmi weight {m.coef_[cols.index('bmi')]:.2f}, R2 {r2:.3f}")
1 features: bmi weight 10.51, R2 0.317
10 features: bmi weight 5.73, R2 0.485
Now you can say that each extra 1 kg/m² of BMI raises the prediction by 10.51 points. In the 10-feature model, two patients who match on the other nine features but differ by 1 in BMI are predicted 5.73 points apart. Only the units changed, so R² stays the same. Perhaps the weight is larger when BMI is used alone because it also picks up the share of other features that move along with it.
Two ways to find the weights
A least squares problem can be solved in a single calculation. If you add a column of ones to the feature table, the intercept becomes that column’s weight, and NumPy’s lstsq returns the weights that minimize the sum of squared errors right away.
import numpy as np
# A column of ones turns the intercept into one more weight
A = np.column_stack([np.ones(len(X_train)), X_train])
w, *_ = np.linalg.lstsq(A, y_train, rcond=None)
print("numpy intercept", round(w[0], 1), "bmi weight", round(w[3], 1))
print("same as scikit-learn:", np.allclose(w, [multi.intercept_, *multi.coef_]))
numpy intercept 151.7 bmi weight 532.0
same as scikit-learn: True
As the output shows, it’s the same answer scikit-learn gave. The other way, gradient descent, nudges the weights a little at a time to lower the loss, and it’s mostly used when the data is very large or the model can’t be solved in one step.
What “linear” means, and what residuals show
The “linear” in linear regression means linear in the weights. As long as the prediction is a weighted sum, you can add polynomial features such as x squared to fit a curve, and it’s still linear regression, solved the same way (polynomial regression docs). Residuals, the actual values minus the predictions, tell you whether you need that curve. If the relationship bends into a U, the residuals of a straight line run positive at both ends and negative in the middle.
Residuals also reveal outliers. Because least squares squares the errors, a single point that’s far off can easily pull the whole line toward it. Here’s what happens when one of ten points is recorded wrong.
x = np.arange(1, 11).reshape(-1, 1)
y_toy = 2.0 * x.ravel() + 1 # ten points on the line y = 2x + 1 (slope 2)
y_toy[-1] = 0 # one value recorded wrong (should be 21)
bad = LinearRegression().fit(x, y_toy)
print(f"slope {bad.coef_[0]:.2f}")
print("residuals", (y_toy - bad.predict(x)).round(1) + 0)
slope 0.85
residuals [ -3.1 -1.9 -0.8 0.4 1.5 2.7 3.8 5. 6.1 -13.7]
That one point pulled the slope from 2 down to 0.85. In the residuals, that point sticks out at -13.7, and even the nine good points lean to one side, negative at the start and positive at the end. That’s why I’d suggest lining up the residuals after training and checking for patterns or points that stick out.
Regression in statistics and in machine learning
With the same linear regression, statistics cares more about interpreting the coefficients and drawing inferences from them, so the OLS summary in statsmodels attaches a standard error, a p-value, and a confidence interval to each coefficient. Machine learning, on the other hand, looks first at how well the model predicts new data, so it scores the model on a test set, and scikit-learn’s LinearRegression gives you no p-values. Of course, either way a coefficient only shows how things move together, not cause and effect.
When it fits and when it doesn’t
Linear regression fits well when the relationship is roughly a straight line, and when you need to explain how much each feature moves the prediction. It trains fast and gives the same result every time, so it also makes a good baseline. In the example above, the question for any other model is whether it can get below an RMSE of 53.4.
On the other hand, if the relationship bends sharply, it can’t follow the shape unless you build such features yourself, and outliers pull it around easily. Multicollinearity, where features are strongly tangled with each other, also calls for care. In the training data, s1 (total cholesterol) and s2 (LDL) have a correlation of 0.89, and in the multiple regression their weights were -919 and 508, large and opposite in sign. When I changed random_state to 0, the weight for s1 became -560, and scikit-learn’s least squares docs note that in this situation the estimates become highly sensitive to random errors in the target values. That’s why people sometimes add regularization, a penalty on the size of the coefficients. Ridge shrinks the coefficients toward zero so they swing less, and Lasso sets some coefficients exactly to zero, which drops those features.
If you’re trying it for the first time
If you’re new to this, I’d suggest pasting the code blocks above into one file in order, running it, and then changing one thing at a time. With the same random_state=0, the test R² of the multiple regression dropped from 0.485 to 0.359. Because a score measured on 111 test patients can move this much, people often use cross-validation, which splits the data several ways and averages the scores. The functions and attributes are listed in the LinearRegression docs. I ran these examples on November 2, 2026 with Python 3.13.12, scikit-learn 1.9.1, NumPy 2.5.4, and pandas 3.1.0.
AI tools helped with the research for this post.