Linear Regression

Updated · 5 min read
mediumPython 3.13aimachine-learningregressionscikit-learnlinear-models

Linear regression predicts a number as a weighted sum of the features plus a constant: price = w₁ × size + w₂ × bedrooms + w₃ × age + b. Training finds the weights (the coefficients) and constant (the intercept) that make the squared errors as small as possible, the same loss you met in "Derivatives and Gradients". It is simple, fast and easy to explain, so it is often the first model to try for any number.

Fitting a Line Through the Data

Each coefficient: how much the price changes per unit
PartDescription
CoefficientIt is used to say how much the prediction changes when one feature rises by 1, others fixed
InterceptIt is used as the prediction when every feature is 0
Mean absolute error (MAE)It is used to report the average size of the errors, in the label's units
R squaredIt is used to say what share of the variation the model explains, up to 1

Creating the Data

Python
import numpy as np
import pandas as pd
 
rng = np.random.default_rng(7)
n = 200
houses = pd.DataFrame({
    "size": rng.uniform(1.0, 3.5, n).round(2),        # thousands of square feet
    "bedrooms": rng.integers(2, 6, n),
    "age": rng.integers(0, 60, n),                    # years
})
# Made-up Dallas prices in $1,000s: a rule plus noise
houses["price"] = (60 + 140 * houses["size"] + 12 * houses["bedrooms"] - 1.1 * houses["age"]
                   + rng.normal(0, 25, n)).round(0)
houses.to_csv("houses.csv", index=False)
print("Saved", n, "houses")
Output
Saved 200 houses

Example

Python
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
 
houses = pd.read_csv("houses.csv")
X, y = houses[["size", "bedrooms", "age"]], houses["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
 
model = LinearRegression().fit(X_train, y_train)
for name, coef in zip(X.columns, model.coef_):
    print(f"{name:9} {coef:7.1f}")
print(f"intercept {model.intercept_:7.1f}")
 
predicted = model.predict(X_test)
print(f"Average error on unseen houses: ${mean_absolute_error(y_test, predicted):.1f}k")
print(f"R squared: {r2_score(y_test, predicted):.3f}")
 
house = pd.DataFrame([{"size": 2.2, "bedrooms": 3, "age": 15}])
print(f"2,200 sq ft, 3 bedrooms, 15 years old: ${model.predict(house)[0]:.0f}k")
Output
size        139.5
bedrooms     12.5
age          -1.3
intercept    60.6
Average error on unseen houses: $18.5k
R squared: 0.955
2,200 sq ft, 3 bedrooms, 15 years old: $386k

Explanation: The coefficients read like a price list: about $139.5k more per 1,000 square feet, $12.5k more per bedroom, and $1.3k less per year of age. They come close to the made-up rule that generated the data (140, 12 and −1.1), which shows the model found the real pattern despite the noise. On houses it never saw, predictions are off by $18.5k on average, and R squared is 0.955.

When Linear Regression Fits

SituationLinear regression?
Effects add up and change steadilyA good choice
You must explain the predictionA good choice: each coefficient is readable
Strong curves or interactionsAdd features (see the next chapter) or use trees and forests
A category to predictUse classification instead

Common Mistakes

Reading coefficients as causes. They describe the data's pattern, not proof that changing a feature changes the price.

Predicting far outside the training range. A 10,000 sq ft house is beyond what the model learned.

Judging by R squared alone. Also report the error in real units, like dollars.

Interview Corner

How does linear regression make predictions?

As a weighted sum of the features plus an intercept, with weights chosen to minimize the squared errors on the training data.

What does R squared mean?

The share of the variation in the label that the model explains: 1 is perfect, 0 is no better than predicting the average.

Practice

Exercise: drop a feature. Fit the model with only size. How do the error and R squared change? What does that tell you about bedrooms and age?

Check your understanding:

  1. What does the size coefficient of 139.5 mean?
  2. Why did the coefficients come close to 140, 12 and −1.1?
  3. What is the difference between MAE and R squared?

Quick check: linear regression

4 questions
1What does linear regression predict?
2What was the average error on unseen houses?
3What does the age coefficient of −1.3 mean?
4What does R squared of 0.955 mean?

Key Takeaways

Quick reference

NeedCode
ModelLinearRegression().fit(X, y)
Coefficientsmodel.coef_, model.intercept_
Errormean_absolute_error(y_test, predicted)
R squaredr2_score(y_test, predicted)

Was this tutorial helpful?

Lesson 121 of 186