Linear Regression

How a model turns examples into a line that can predict new numbers.

The Prediction Problem

Imagine you run a small coffee shop. You write down the temperature each day and the number of iced coffees sold. After a few weeks, the pattern feels obvious. Hotter days usually mean more iced coffee.

Supervised learning starts with this kind of table. Each row gives the model an input and the answer that was observed. The inputs are called features. The answer we want to predict is called the target.

TemperatureIced coffees sold
22°C41
27°C58
32°C76

When the target is a continuous number, such as sales, price, distance, or time, the task is called regression. The central question is simple. Given what we have seen before, what number should we predict for a new input?

A first answer is to draw the simplest useful shape through the data. That shape is a line.

Linear Regression

Linear regression assumes that each feature contributes a steady amount to the prediction. If the temperature rises by one degree, the model adds the same amount of expected iced coffee sales each time.

With one feature, the model is the familiar equation for a line.

y^=wx+b\hat{y} = wx + b

The symbol y^\hat{y} means predicted target. The weight ww controls how strongly the input changes the prediction. A positive weight makes the line rise. A negative weight makes it fall. The bias bb is the prediction when the input contributes nothing.

Real datasets often have many features. A house price model might use square footage, number of bedrooms, age, and distance from a station. We collect those feature values in a vector xx and give each feature its own weight.

y^=wTx+b\hat{y}=w^T x+b

The expression wTxw^T x means multiply each feature by its weight, then add the results. The bias shifts the final answer up or down. This is still a line in one dimension, a plane in two dimensions, and a hyperplane when there are more features.

Now the model can make predictions, but we still have not said which line is best. To choose between lines, we need a way to measure how wrong a line is.

Interactive Demo

Drag the line to fit the data
0246810051015

Click anywhere on the plot to add data points.

Your MSE10.02

Move the slope and intercept sliders. The dashed vertical segments are residuals, which are the errors the model makes for each example. Watch the MSE change as the line moves.

The important detail is that the residuals are vertical. For a fixed input xix_i, the model predicts one output y^i\hat{y}_i. The error asks how far that prediction is from the observed target yiy_i.

Loss And MSE

A loss function turns prediction quality into a number. Small loss means the model is close to the data. Large loss means it is missing the pattern.

For one training example, the raw error is the actual value minus the predicted value.

errori=yiy^i\text{error}_i = y_i-\hat{y}_i

If we simply averaged raw errors, positive and negative mistakes could cancel. A prediction that is ten too high and another prediction that is ten too low would look perfect together, even though both are wrong. Squaring fixes that.

(yiy^i)2(y_i-\hat{y}_i)^2

Squaring makes every error non-negative and gives larger mistakes a larger penalty. An error of 22 becomes 44, while an error of 1010 becomes 100100. The model is therefore pushed to avoid big misses.

To judge the whole dataset, we average the squared errors across all nn examples.

MSE=1ni=1n(yiy^i)2\text{MSE}=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2
InputActualPredictionSquared error
132.50.25
254.70.09
376.90.01
MSE=0.25+0.09+0.013=0.13\text{MSE}=\frac{0.25+0.09+0.01}{3}=0.13

This gives training a concrete goal. Find the weights and bias that make MSE as small as possible. For a simple line, there is a direct formula. For models used later in the course, we need a general way to improve parameters step by step.

That need leads naturally to gradient descent. Before we go there, one more question exposes the limit of linear regression. What happens if the output is no longer a continuous number?

Implementation

This minimal implementation uses the closed form solution for one feature. The method is useful for seeing the mechanics, while gradient descent will give us a more general training tool.

import numpy as np

class LinearRegression:
    def __init__(self):
        self.w = 0.0
        self.b = 0.0

    def fit(self, X, y):
        n = len(X)
        numerator = n * np.sum(X * y) - np.sum(X) * np.sum(y)
        denominator = n * np.sum(X ** 2) - np.sum(X) ** 2
        self.w = numerator / denominator
        self.b = (np.sum(y) - self.w * np.sum(X)) / n

    def predict(self, X):
        return self.w * X + self.b

    def mse(self, X, y):
        predictions = self.predict(X)
        return np.mean((y - predictions) ** 2)

X = np.array([1, 2, 3, 4, 5])
y = np.array([2.1, 4.0, 5.8, 8.2, 9.7])

model = LinearRegression()
model.fit(X, y)

print(model.w, model.b)
print(model.predict(6))
print(model.mse(X, y))

Interview Discussion

What problem does linear regression solve?

It predicts a continuous target from input features by assuming the prediction is a linear function of those features.

What do the weights and bias mean?

Each weight says how much one feature changes the prediction when that feature increases by one unit. The bias shifts every prediction up or down.

Why does MSE use vertical distance?

For each fixed input, the model produces one predicted output. The error compares that predicted output with the observed target.

Why square errors?

Squaring prevents cancellation, keeps the loss non-negative, and makes large mistakes much more expensive than small mistakes.

What is a common misconception?

A low training MSE does not automatically mean the model will perform well on new data. Generalisation must be checked on held out examples.

Active Recall

1. In your own words, what makes a problem supervised learning?

2. Write the prediction equation for linear regression with many features.

3. Explain why raw errors can cancel and why squared errors avoid that problem.

4. What does the bias do when all feature values are zero?

5. Suggested exercise. Implement linear regression with gradient descent and plot MSE over time.