Skip to content

Intermediate: machine learning · The ML workflow, regression and classification · topic 24 of 62 · 35 min

Linear regression and least squares

Explanation

Linear regression fits a straight line, y = w·x + b, through data to predict a number. The best line is the one with the smallest total squared error (least squares). For one feature, the slope is the covariance of x and y divided by the variance of x. The slope tells you how much y changes when x goes up by one.

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

  1. Compute the means x̄ and ȳ.
  2. w = Σ (x − x̄)(y − ȳ) ÷ Σ (x − x̄)². This is the covariance of x and y divided by the variance of x.
  3. b = ȳ − w·x̄. The line always passes through the point (x̄, ȳ).
python
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))
Shows 0.0484 5.9, then 59.14. Each extra square foot adds about ₹0.0484 lakh (₹4,840); a 1,100 sq ft flat is predicted at about ₹59.14 lakh.

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_.

python
from sklearn.linear_model import LinearRegression

model = LinearRegression().fit(X_train, y_train)   # X: area, age, floor
print(model.coef_, model.intercept_)
Shown only. The coefficients are only comparable if the features are on similar scales.

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

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)

Task 1 · Code · Python

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.

Task 2 · Code · Python

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.

Task 3 · Code · Python

Write predict_all(w, b, xs) that returns the predictions w·x + b for every x, each rounded to 2 decimal places.

Quick quiz

Question 1

1.In ŷ = 3x + 10, what does 3 mean?

Question 2

2.Why does least squares square the residuals?

Question 3

3.Which point does the least-squares line always pass through?

Question 4

4.A model trained on flats of 400–1,500 sq ft predicts a 9,000 sq ft villa. What is the risk?

Question 5

5.In scikit-learn, where are the learned weights of a LinearRegression model?

Read more (free)

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.

From Spread: range, variance and standard deviation

Is logistic regression used for regression or classification?Related

Answer: Classification

It predicts class probabilities; the name is historical.

From Logistic regression and classification

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.

From Regression metrics: MAE, MSE, RMSE and R²

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.

From Gradient descent: learning step by step

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

  1. 2 more topics in “The ML workflow, regression and classification” before its exam: Gradient descent: learning step by step, Logistic regression and classification.
  2. Module 5 exam: The ML workflow, regression and classification · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Evaluating models. 62 topics left in the course before the final exam.

← Previous: The ML workflow end to end