Intermediate: machine learning · The ML workflow, regression and classification · topic 24 of 62 · 35 min
Linear regression and least squares
Explanation
Why start with a line?
Many relationships are roughly straight over the range we care about: a bigger flat costs more, a longer distance takes longer. Linear regression is fast, easy to explain and a strong baseline. Even teams that use complex models usually try it first.
The model
With one feature x, the model is ŷ = w·x + b. ŷ (read "y-hat") is the prediction, w is the weight or slope (how much ŷ rises for each extra unit of x) and b is the bias or intercept (the value of ŷ when x is 0). Training means choosing w and b.
Residuals and least squares
A residual is the error for one example: actual minus predicted, y − ŷ. Some are positive, some negative. To get one number that measures how bad a line is, we square each residual (so negatives do not cancel positives, and big misses count more) and add them up. Least squares means choosing the w and b that make this sum of squared errors as small as possible.
The formula for one feature
- Compute the means x̄ and ȳ.
- w = Σ (x − x̄)(y − ȳ) ÷ Σ (x − x̄)². This is the covariance of x and y divided by the variance of x.
- b = ȳ − w·x̄. The line always passes through the point (x̄, ȳ).
xs = [500, 750, 1000, 1250] # flat area in sq ft
ys = [30, 42, 55, 66] # price in ₹ lakh
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
w = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
b = my - w * mx
print(round(w, 4), round(b, 2))
print(round(w * 1100 + b, 2))More than one feature
Multiple linear regression uses many features: ŷ = w₁x₁ + w₂x₂ + … + b. Each weight is the effect of its feature when the others are held fixed. In scikit-learn it is the same LinearRegression().fit(X, y), and the learned weights are in model.coef_ and the bias in model.intercept_.
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train) # X: area, age, floor
print(model.coef_, model.intercept_)When a line misleads
- Extrapolation: predicting far outside the data range. A line fitted to 500–1,250 sq ft flats says nothing reliable about a 10,000 sq ft bungalow.
- Curved relationships: if the true pattern bends, a straight line is systematically wrong. Plot the residuals; a curve in them is a warning.
- Outliers: one extreme point can pull the line a lot, because errors are squared.
- Correlated features: weights can become unstable and hard to interpret.
Common mistakes
- Reading the slope as cause. A positive slope between ad spend and sales does not prove ads caused the sales.
- Forgetting units. A slope of 0.0484 means ₹ lakh per sq ft, not rupees.
- Fitting when all x values are the same: the variance is 0 and the slope is undefined. Check for it.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Linear regression and least squares · 1/7
Linear regression draws the best straight line through data to predict a number.
Prefer a video by a teacher? Find free videos on “linear regression least squares explained simple” on YouTube ↗
In real life: Pricing used cars
An online used-car marketplace suggests a price when a seller lists a car. A simple version uses linear regression with features like age, kilometres driven, brand and city. The sales team likes it because each weight has a clear meaning ("each extra year lowers the price by about 8%" when the target is the log of price). Newer models may be more accurate, but the linear model remains the explainable baseline.
Practice (0/3 done)
Write fit_line(xs, ys) that returns (w, b) for the least-squares line, each rounded to 4 decimal places. w = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)², b = ȳ − w·x̄. If all x values are equal, raise ValueError.
Write mse(actual, predicted) that returns the mean squared error: the average of (actual − predicted)², rounded to 4 decimal places. Return 0.0 for empty lists.
Write predict_all(w, b, xs) that returns the predictions w·x + b for every x, each rounded to 2 decimal places.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Gradient descent: learning step by stepThe ML workflow, regression and classification · same module
- What machine learning isThe ML workflow, regression and classification · same module
- Regression metrics: MAE, MSE, RMSE and R²Evaluating models
- Gradient boostingk-NN, decision trees and ensembles
- k-nearest neighboursk-NN, decision trees and ensembles
- Overfitting, underfitting and regularisationEvaluating models
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
In ŷ = 3x + 10, what does 3 mean?
Answer: How much ŷ rises when x goes up by 1
3 is the slope (weight). 10 is the intercept.
Why does least squares square the residuals?
Answer: So positive and negative errors do not cancel, and big errors count more
Squaring removes signs and penalises large misses.
Which point does the least-squares line always pass through?
Answer: (x̄, ȳ), the two means
Because b = ȳ − w·x̄, the line goes through the mean point.
A model trained on flats of 400–1,500 sq ft predicts a 9,000 sq ft villa. What is the risk?
Answer: Extrapolation: the line may not hold far outside the training range
Patterns learned in one range may not continue outside it.
In scikit-learn, where are the learned weights of a LinearRegression model?
Answer: model.coef_ and model.intercept_
Fitted attributes end with an underscore: coef_ and intercept_.
Delivery times have a variance of 49 square minutes. What is the standard deviation?Related
Answer: 7 minutes
The SD is the square root of the variance: √49 = 7, back in minutes.
Is logistic regression used for regression or classification?Related
Answer: Classification
It predicts class probabilities; the name is historical.
A delivery model has MAE = 4 minutes. What does that mean?Related
Answer: On average, predictions are 4 minutes away from the actual time
MAE is the average absolute error in the target's units.
At the current weight the gradient of the loss is positive. What should gradient descent do?Related
Answer: Decrease the weight
Positive slope means the loss rises as w rises, so step the other way.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “The ML workflow, regression and classification” before its exam: Gradient descent: learning step by step, Logistic regression and classification.
- Module 5 exam: The ML workflow, regression and classification · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Evaluating models. 62 topics left in the course before the final exam.