Regression and residuals
Regression predicts a numerical quantity, such as the minutes needed to pack an order. A regression model can learn a relationship between a measured input and an outcome. A residual is the observed value minus its prediction. Positive residuals mean the prediction was too low; negative residuals mean it was too high. In this lesson all data are invented and all calculations use small finite numbers.
A first prediction and its error
A packing-time estimator predicts 4 and 10 minutes for two orders. The observed times are 5 and 8 minutes. The signed errors are 5 − 4 = 1 minute and 8 − 10 = −2 minutes. The first order took longer than predicted; the second took less time. The average signed error is −0.5 minutes, but this hides the two magnitudes. Strictly, residual often means an error on fitting data; on held-out data the same subtraction is a prediction error. We use the same sign convention throughout.
def residuals(actual, predicted): if len(actual) != len(predicted): raise ValueError('Lengths must match') return [y - p for y, p in zip(actual, predicted)]
print(residuals([5, 8], [4, 10]))print(residuals([3, 3], [3, 3]))How a linear model produces a prediction
A one-feature line has the form prediction = intercept + slope × x. If x is the number of boxes and y is time in minutes, slope is measured in minutes per box, and intercept in minutes. For a slope of 2 and intercept of 1, packing three boxes gives 7 minutes. The intercept is the predicted value at x = 0, not automatically a physically meaningful setup time. A line can be used for numeric outputs even when the input counts are discrete. A multifeature linear model adds one coefficient times each feature, and an intercept.
Fit the coefficients from training data
Ordinary least squares selects coefficients that minimize the sum of squared training residuals. With one feature and an intercept, slope equals sum((x − mean(x)) × (y − mean(y))) divided by sum((x − mean(x))²). Intercept equals mean(y) − slope × mean(x). This follows from the squared-loss objective in Chapter 7; detailed derivation and numerical solvers belong to the ML track. If all x values are identical, the denominator is zero: the slope is not uniquely identifiable with an intercept. Our teaching helper raises an error instead of inventing a coefficient. A constant prediction remains possible. Use small numeric inputs only; production libraries address numerical conditioning and validation.
def fit_line(xs, ys): if not xs or len(xs) != len(ys): raise ValueError('Matching nonempty data required') x_mean = sum(xs) / len(xs) y_mean = sum(ys) / len(ys) spread = sum((x - x_mean) ** 2 for x in xs) if spread == 0: raise ValueError('At least two distinct x values required') slope = sum((x - x_mean) * (y - y_mean) for x, y in zip(xs, ys)) / spread intercept = y_mean - slope * x_mean return slope, intercept
slope, intercept = fit_line([1, 2, 3], [3, 5, 7])print(slope, intercept)print(intercept + slope * 2.5)print(intercept + slope * 4)Interpret the output and limits
The fitted slope is 2.0 and intercept is 1.0. The prediction for 2.5 boxes (a mathematical interpolation only) is 6.0 minutes; for 4 boxes it is 9.0 minutes. Four is outside the training feature range [1, 3], so this is extrapolation, not evidence of accurate future behavior. A constant target with varying x gives slope zero. A line that fits every training point may still fail on new data. If large orders need a second worker, the relationship may change. Observational association is not proof that adding a box causes exactly two minutes of extra work; staffing and order complexity can confound the relationship.
Common mistakes and next practice
Do not subtract in the opposite order without naming the convention. Do not allow zip to silently truncate mismatched arrays. Fit on training observations only; compare on validation data and reserve final test data as taught in Chapter 16. Predicting a negative packing time is possible with an unconstrained line; detect invalid results and consider a more appropriate model rather than claiming all linear outputs are physical. A point prediction is not a prediction interval. Practice: for observed [5, 8] and predictions [4, 10], report each error and whether it is an overprediction. Then proceed to MAE, MSE and baselines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Regression and residuals quiz
Apply regression concepts to original numerical scenarios.
Actual 5, prediction 4. What is the residual?
Under the lesson convention residual = observed − predicted, what does a negative residual indicate?
For y = 1 + 2x, what is the slope if x counts boxes and y is minutes?
Why does the one-feature least-squares helper with an intercept reject x = [2, 2, 2]?
A line trained on feature values between 1 and 3 inclusive is used at x = 9. What is this use of the line?