Linear Regression
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
| Part | Description |
|---|---|
| Coefficient | It is used to say how much the prediction changes when one feature rises by 1, others fixed |
| Intercept | It 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 squared | It is used to say what share of the variation the model explains, up to 1 |
Creating the Data
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")Saved 200 housesExample
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")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: $386kExplanation: 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
| Situation | Linear regression? |
|---|---|
| Effects add up and change steadily | A good choice |
| You must explain the prediction | A good choice: each coefficient is readable |
| Strong curves or interactions | Add features (see the next chapter) or use trees and forests |
| A category to predict | Use 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:
- What does the size coefficient of 139.5 mean?
- Why did the coefficients come close to 140, 12 and −1.1?
- What is the difference between MAE and R squared?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Model | LinearRegression().fit(X, y) |
| Coefficients | model.coef_, model.intercept_ |
| Error | mean_absolute_error(y_test, predicted) |
| R squared | r2_score(y_test, predicted) |
Was this tutorial helpful?