Linear Regression and the Loss Function
Fit a line y = wx + b to data, interpret the weight and bias, measure fit with mean squared error, and extend the idea to many features.
Welcome back!
Step 1 of 12Learn
Drawing the best line
A coffee shop records daily temperature and iced-drink sales. On a 60°F day it sells about 40 iced drinks; at 80°F about 100; at 90°F about 130. Plotted, the points rise roughly along a straight line.
Linear regression models that relationship as
ŷ = w·x + b
- x is the feature (temperature).
- ŷ ("y-hat") is the predicted value (iced drinks).
- w is the weight or slope: how much ŷ changes for each one-unit increase in x.
- b is the bias or intercept: the prediction when x = 0.
Suppose training finds w = 3 and b = −140. The model predicts ŷ = 3 × 80 − 140 = 100 drinks at 80°F. The weight has a direct meaning: each extra degree adds about 3 iced drinks. The intercept, −140 drinks at 0°F, is meaningless on its own; it's just where the line crosses the axis, far outside the data. That illustrates a key caution: linear models should not be trusted far outside the range of the training data.
With several features, the idea extends naturally:
ŷ = w₁x₁ + w₂x₂ + … + wₙxₙ + b
For house prices: ŷ = 150 × sqft + 10,000 × bedrooms − 2,000 × age + 50,000. Each weight is the change in predicted price per unit of that feature, holding the other features constant.
Linear regression is fast, easy to interpret and a strong baseline. It underfits curved relationships, but you can add transformed features, such as x², to capture curves while keeping the model linear in its weights.
Step 2 of 12Chart
Iced drinks sold vs. temperature
A week of coffee-shop data. The points almost line up, which is why a straight line is a reasonable model.
| Point | Temperature (°F) | Iced drinks |
|---|---|---|
| Mon | 60 | 40 |
| Tue | 64 | 50 |
| Wed | 70 | 68 |
| Thu | 75 | 86 |
| Fri | 80 | 100 |
| Sat | 85 | 117 |
| Sun | 90 | 130 |
Step 3 of 12Explore
Fit a line by hand
The data points in the coffee example are roughly (60, 40), (80, 100) and (90, 130). Adjust the weight and bias so the line passes close to all three. The readouts show the predictions at 60°F, 80°F and 90°F.
- Prediction at 60°F (actual about 40)
- 60
- Prediction at 80°F (actual about 100)
- 100
- Prediction at 90°F (actual about 130)
- 120
- Mean squared error on the 3 points
- 166.7
Step 4 of 12Practice · Work it out
A model for house prices is ŷ = 150·sqft + 20,000·bedrooms + 40,000. What price does it predict, in dollars, for a 1,600-square-foot house with 3 bedrooms?
Step 5 of 12Learn
Measuring "best": the loss function
Many lines can be drawn through a cloud of points. To choose the best one, we need a number that scores how wrong a line is. That number is the loss.
For each training example, the residual is the difference between the actual value and the prediction: y − ŷ. Linear regression usually uses the mean squared error:
MSE = (1/n) × Σ (yᵢ − ŷᵢ)²
Square each residual, then average. Why square?
- Squaring makes every error positive, so overestimates and underestimates don't cancel.
- It punishes large errors much more than small ones: an error of 10 counts 100 times as much as an error of 1. That's useful when big misses are costly, but it also makes MSE sensitive to outliers.
- It produces a smooth bowl-shaped loss that is easy to minimize with calculus.
Worked example with three points, predictions versus actual:
| Actual y | Predicted ŷ | Residual | Squared |
|---|---|---|---|
| 40 | 44 | −4 | 16 |
| 100 | 98 | 2 | 4 |
| 130 | 127 | 3 | 9 |
MSE = (16 + 4 + 9) ÷ 3 ≈ 9.67. RMSE = √9.67 ≈ 3.1 drinks, which is back in the original units.
Training linear regression means finding the w and b that minimize MSE. For linear regression there's even a direct formula (the "normal equation") that computes the exact minimum. For most other models no such formula exists, so we use an iterative method, gradient descent, covered in the next lesson.
Step 6 of 12Practice · Chart
Squaring makes big errors dominate
Tap the residual that contributes most of the MSE.
Tap the bar that answers the question, then press Check.
Step 7 of 12Practice · Code challenge
Write mse(actual, predicted) that takes two arrays of equal length and returns the mean squared error.
mse([3, 5], [2, 7])mse([1, 2, 3], [1, 2, 3])mse([0, 0], [3, -1])mse([10, 20, 30, 40], [12, 18, 30, 44])
Step 8 of 12Note
Step 9 of 12Learn
Assumptions and pitfalls
Linear regression is simple, but a few common pitfalls can mislead you.
Nonlinear relationships. If sales rise with temperature up to 85°F and then fall because it's too hot to go out, a straight line misses the pattern. Plot residuals against predictions: if they form a curve instead of random scatter, the model is missing structure. Adding features such as x² or using a nonlinear model helps.
Outliers. Because MSE squares errors, a single extreme point can drag the line toward it. Investigate outliers; consider MAE or a robust loss if they are genuine but rare.
Correlated features (multicollinearity). If two features carry nearly the same information, such as square feet and square meters, or total rooms and bedrooms, the model can split the effect between them in unstable ways. Predictions may still be fine, but individual weights become unreliable to interpret.
Extrapolation. Predictions far outside the training range, like the −140 drinks at 0°F, are unreliable.
Correlation is not causation. Ice cream sales and drowning incidents rise together because both rise in summer. A model using ice cream sales to predict drownings may predict well, but banning ice cream would save nobody. Use regression weights to describe patterns, and use experiments or careful causal methods to make claims about cause.
Despite these caveats, linear regression is often the first model to try on a numeric target. It sets a baseline, shows which features matter, and is easy to explain to people who must trust its predictions.
Step 10 of 12Practice · Select all that apply
A residual plot for a linear regression model shows a clear U-shaped curve instead of random scatter. Which responses are reasonable? Select all that apply.
Select all that apply.
Step 11 of 12Practice · True or false
A linear regression model trained on houses between 800 and 3,000 square feet can be trusted to predict the price of a 12,000-square-foot mansion.
Step 12 of 12Practice · Choose one
Why does linear regression typically square the residuals instead of simply adding them up?
Lesson complete!