Linear regression predicts a number, such as a price, a mark or a temperature, by fitting a straight line through the data. It is the simplest and most widely used regression model, and it is easy to interpret: every coefficient tells you how much the prediction changes when one feature increases by one unit. Many advanced models are judged by whether they can beat a well-built linear regression.
In this lesson you will learn
- The equation behind linear regression
- Fitting a model with scikit-learn’s
LinearRegression - Reading the slope and intercept
- Using several features at once
- Measuring errors with MAE, RMSE and R²
The Idea: a Best-Fit Line
With one feature, the model is the line ŷ = w·x + b. Here w is the slope (weight or coefficient), b is the intercept and ŷ (“y-hat”) is the prediction. Training chooses the w and b that make the squared differences between predictions and real values as small as possible, a method called ordinary least squares.
import numpy as np
from sklearn.linear_model import LinearRegression
# Hours studied and exam marks for 8 students
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(-1, 1)
marks = np.array([35, 42, 50, 55, 63, 68, 77, 82])
model = LinearRegression()
model.fit(hours, marks)
print(f"Slope (marks per extra hour): {model.coef_[0]:.2f}")
print(f"Intercept (marks at 0 hours): {model.intercept_:.2f}")
new_hours = np.array([[5.5], [10]])
for h, p in zip(new_hours.ravel(), model.predict(new_hours)):
print(f"Predicted marks for {h} hours: {p:.1f}")
Output
Slope (marks per extra hour): 6.74
Intercept (marks at 0 hours): 28.68
Predicted marks for 5.5 hours: 65.7
Predicted marks for 10.0 hours: 96.1
- scikit-learn expects
Xas a 2D table (rows × features), so a single feature is reshaped withreshape(-1, 1).ystays 1D. - The slope says each extra hour of study adds about 6.7 marks; the intercept is the predicted mark for zero hours.
- The prediction for 10 hours is 96.1, beyond the range of the data (1 to 8 hours). Predicting outside the training range is called extrapolation and is risky: with a few more hours the line would predict marks above 100.
Multiple Features and Error Metrics
With several features the model becomes ŷ = w₁x₁ + w₂x₂ + … + b, one weight per feature. This example uses scikit-learn’s built-in diabetes dataset, which predicts disease progression after one year from ten measurements.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
X, y = load_diabetes(return_X_y=True, as_frame=True)
print("Features:", list(X.columns))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print(f"MAE: {mean_absolute_error(y_test, pred):.1f}")
print(f"RMSE: {mean_squared_error(y_test, pred) ** 0.5:.1f}")
print(f"R2: {r2_score(y_test, pred):.3f}")
top = sorted(zip(X.columns, model.coef_), key=lambda t: abs(t[1]), reverse=True)[:3]
print("Largest coefficients:", [(name, round(c)) for name, c in top])
Output
Features: ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']
MAE: 42.8
RMSE: 53.9
R2: 0.453
Largest coefficients: [('s1', -931), ('s5', 736), ('bmi', 542)]
| Metric | Meaning | Better when |
|---|---|---|
| MAE (mean absolute error) | Average size of the error, in the target’s units | Lower |
| RMSE (root mean squared error) | Like MAE but punishes large errors more | Lower |
| R² (coefficient of determination) | Share of the variation explained, up to 1.0 | Higher |
- An R² of 0.45 means the model explains under half of the variation in progression. That is typical for medical data, where many causes are not measured.
- Coefficients can only be compared directly when features are on the same scale. This dataset is already scaled, which is why
s1ands5(blood serum measurements) show the largest weights. Large opposite-sign weights on related features usually mean those features are strongly correlated, so read them with care.
When Linear Regression Works Well
- The relationship between features and target is roughly a straight line. If it curves, add features such as squares (polynomial regression) or try a tree-based model.
- Outliers are few; squared errors make a single extreme point pull the whole line.
- Features are not almost duplicates of each other, which makes coefficients unstable. Regularised versions,
RidgeandLasso, handle this better.
Common Mistakes
- Passing a 1D array as
X, which raises “Expected 2D array”. - Trusting predictions far outside the training range.
- Reading coefficients as cause and effect. They show association in this data, not causation.
- Judging the model by training error instead of test error.
Practice Exercises
Exercise 1. Using the study-hours model, how many marks would a student get after 3 hours? Work it out from the slope and intercept.
Show answer
6.74 × 3 + 28.68 ≈ 48.9 marks. You can confirm with model.predict([[3]]).
Exercise 2. Replace LinearRegression with Ridge(alpha=1.0) in the diabetes example and compare R².
Show answer
from sklearn.linear_model import Ridge
model = Ridge(alpha=1.0).fit(X_train, y_train)
print(r2_score(y_test, model.predict(X_test)))
Ridge shrinks the coefficients towards zero. The score changes a little, and the coefficients become smaller and more stable.
Frequently Asked Questions
What is a good R² value?
It depends on the field. Physics experiments may reach 0.99, while predictions about people, such as health or spending, are often useful at 0.3 to 0.6. Compare against a simple baseline, such as always predicting the average.
Can linear regression predict categories?
Not well. For yes/no or category answers, use logistic regression, which outputs probabilities between 0 and 1.
Summary
- Linear regression fits ŷ = w·x + b by minimising squared errors.
- Coefficients show how much the prediction changes per unit of each feature.
- Evaluate with MAE, RMSE and R² on the test set.
- Beware of extrapolation, outliers and correlated features.
Next: Logistic Regression.
