Linear Regression
Learn how a machine finds a straight line that best describes the relationship between two numerical values, then use that line to make predictions.
The big idea
Find the line that stays as close as possible to the data points.
Imagine you know how many hours students study and their exam marks. Linear Regression learns a line from past examples. You can then use that line to estimate marks for a new number of study hours.
At a glance
What kind of problem does it solve?
One or more numerical features, such as study hours.
A number, such as a predicted exam score.
Supervised: training examples include the correct answers.
A straight line for one input feature.
1. How does it work?
Think of each dot as one real observation.
From examples to a prediction
The blue dots are students from earlier exams. The line is the model's best estimate of the relationship between study time and marks.
The model tries to do three things
It studies pairs of inputs (X) and known outputs (Y).
It chooses a slope and intercept that make prediction errors small.
Put a new X into the equation to estimate Y.
2. Live Linear Regression Playground
Change the data and watch the line, equation, and model scores update.
Scatter plot and best-fit line
Click inside the graph to add a new data point.
Experiment controls
Start with sample data or build your own.
Data table
Observed values and the model's predicted values.
| # | X | Actual Y | Predicted Ŷ | Residual |
|---|
3. The mathematics behind the line
Let's understand where the slope and intercept come from.
The prediction equation
- ŷ (y-hat): the value predicted by the model.
- x: the input feature.
- m: slope; how much the prediction changes when X increases by 1.
- b: intercept; the predicted value when X is 0.
How ordinary least squares finds the line
The model chooses m and b to make the total squared prediction error as small as possible.
For one input feature, the formulas are:
x̄ is the mean of X values. ȳ is the mean of Y values. These formulas describe simple linear regression with one input feature.
What is a residual?
A residual is the difference between the actual value and the predicted value.
If a student's actual mark is 78 and the model predicts 72, the residual is +6. A positive residual means the model predicted too low. A negative residual means it predicted too high.
4. Numerical worked example
Calculate a small model by hand before using a library.
Study hours and exam marks
For this teaching example, use these four observations.
| Student | Hours (X) | Marks (Y) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 3 |
| C | 3 | 5 |
| D | 4 | 4 |
Step-by-step result
Numerator = 4.0; denominator = 5.0; therefore m = 0.8.
b = 3.5 − (0.8 × 2.5) = 1.5.
Predicted marks = 0.8 × study hours + 1.5.
ŷ = (0.8 × 5) + 1.5 = 5.5.
5. How do we evaluate the model?
A line can look good but still make poor predictions. We need measurements.
Mean Absolute Error (MAE)
Average size of the errors. It is easy to explain and uses the same units as Y. Smaller is better.
Mean Squared Error (MSE)
Squares each error, so large mistakes count much more. Smaller is better.
Root Mean Squared Error (RMSE)
Like MSE, but returns to the same units as Y. Smaller is better.
R-squared (R²)
Shows how much of the variation in Y is explained by the model, compared with predicting the mean. Higher is usually better, but it is not proof of a good model.
6. Python implementation
Use scikit-learn to train a Linear Regression model.
Simple Linear Regression with scikit-learn
Copy this example into a Python notebook.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
# X must be 2D: rows are examples, columns are features
X = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([2, 3, 5, 4, 6, 7])
# Keep some examples aside for testing
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.33, random_state=42
)
# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions on unseen test examples
y_pred = model.predict(X_test)
print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)
print("Predictions:", y_pred)
print("MAE:", mean_absolute_error(y_test, y_pred))
print("MSE:", mean_squared_error(y_test, y_pred))
print("R2:", r2_score(y_test, y_pred))
# Predict for a new input: 7 study hours
print("New prediction:", model.predict([[7]])[0])Install the libraries if needed: pip install numpy scikit-learn. This example uses a train/test split so the evaluation is not done on the same rows used for training.
7. Real-life applications
Places where predicting a number can be useful.
House price estimation
Estimate price from size, while remembering that real prices depend on many other things too.
Sales forecasting
Estimate sales from advertising spend or another useful business measure.
Energy use
Estimate electricity use from temperature or operating hours.
Education analysis
Explore how study time relates to exam scores.
8. Knowledge check
Answer one question at a time. Your score and explanations will appear after the final question.
Mini challenge
Use the playground. Generate a positive dataset, then increase the noise. Watch what happens to R². Next, add an outlier and observe how the line changes.