⚡0 XP🔥0

Linear Regression

Lesson 3 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Predict numbers with a straight line - the model y = mx + c, the cost function (MSE), gradient descent, scikit-learn LinearRegression, multiple regression, and the metrics MAE, RMSE and R².

Regression predicts a number. Linear regression assumes the target changes in a straight-line way with the input: more study hours → higher marks; bigger flat → higher rent.

The model#

With one feature:

ŷ = m·x + c
  • x - the input (study hours)
  • ŷ ("y-hat") - the prediction (marks)
  • m - the slope (how much ŷ increases per unit of x)
  • c - the intercept (ŷ when x = 0)

With many features: ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b. The weights w and bias b are what the model learns.

How good is a line? The cost function#

For each point, the error (residual) is y - ŷ. Linear regression chooses the line that minimises the Mean Squared Error:

MSE = (1/n) · Σ (yᵢ - ŷᵢ)²

Squaring makes all errors positive and punishes big misses more.

InteractiveFit a line yourself

Drag the sliders to change the slope and intercept, and watch the red error lines and the MSE. Click the chart to add points. Then press Fit best line (the exact least-squares answer) or Train with gradient descent to watch the model learn step by step.

हिंदी में समझें

Linear regression डेटा के बीच से ऐसी सीधी रेखा खींचता है जिससे हर point की दूरी (error) कुल मिलाकर सबसे कम हो। Error को square करके औसत लेते हैं - इसे MSE कहते हैं। Model का काम है slope (m) और intercept (c) ऐसे चुनना कि MSE न्यूनतम हो।

Gradient descent - how models learn#

For linear regression there is an exact formula, but most ML models (logistic regression, neural networks) learn with gradient descent:

  1. Start with random (or zero) parameters.
  2. Compute the error and its gradient - the direction in which the error increases fastest.
  3. Take a small step in the opposite direction: m = m - learning_rate × ∂MSE/∂m.
  4. Repeat until the error stops decreasing.
▶ Try it YourselfPython
Ctrl + Enter to run
Output
epoch    1: m= 13.26 c=  2.60 MSE= 4515.50
epoch   10: m= 12.24 c=  4.51 MSE=  154.06
epoch  100: m=  9.77 c= 18.42 MSE=   36.99
epoch 1000: m=  7.43 c= 31.56 MSE=    0.79
epoch 3000: m=  7.43 c= 31.57 MSE=    0.79

The learning rate controls the step size: too small and training is slow; too large and it overshoots and diverges.

Linear regression with scikit-learn#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
slope m: 7.429
intercept c: 31.571
2.5 hours -> 50.1 marks
5 hours -> 68.7 marks
9 hours -> 98.4 marks

Gradient descent arrived at the same line - scikit-learn just solves it exactly.

▶ Try it YourselfPython
Ctrl + Enter to run

Multiple linear regression and evaluation#

Real problems have many features. The diabetes dataset (built into scikit-learn) predicts disease progression one year later from 10 measurements (age, BMI, blood pressure...):

▶ Try it YourselfPython
Ctrl + Enter to run
Output
MAE : 42.79
RMSE: 53.85
R2  : 0.453
Target range: 37 to 310
strong feature: s1   weight   -931.5
strong feature: s5   weight    736.2
strong feature: bmi  weight    542.4
Metric Meaning Good value
MAE - mean absolute error average size of the error, in target units small
RMSE - root mean squared error like MAE but punishes large errors more small
R² - coefficient of determination share of the variation explained by the model close to 1

An R² of about 0.45 means the 10 measurements explain less than half of the variation - medical outcomes are hard to predict, and a straight line is a simple model. Better features or non-linear models (trees, forests) may do better.

Common Mistake

Linear regression assumes a roughly linear relationship, and it is sensitive to outliers and to strongly correlated features. Always plot your data and the residuals. For many features, regularised versions - Ridge (L2) and Lasso (L1) - reduce overfitting by keeping weights small.

Polynomial regression - curves with a linear model#

If the relationship is curved, add powers of x as new features:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
straight line R2: 0.9467
degree-2 R2     : 1.0
prediction at x=12: 235.5

Summary#

  • Linear regression fits ŷ = w·x + b by minimising MSE.
  • Gradient descent repeatedly steps the parameters against the gradient; the learning rate sets the step size.
  • In scikit-learn: LinearRegression().fit(X, y), then coef_, intercept_, predict.
  • Evaluate with MAE, RMSE and R² on the test set; use polynomial features for curves and Ridge/Lasso to regularise.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Predict marks from study hours

Fit a LinearRegression on hours → marks from the starter. Print the slope and intercept rounded to 2 decimals, and the predicted marks for 6.5 hours rounded to 1 decimal, like:

slope: 7.43
intercept: 31.57
6.5 hours -> 79.9
Expected output:
slope: 7.43
intercept: 31.57
6.5 hours -> 79.9
2

Evaluate a regression model

Using the diabetes dataset, split with test_size=0.2, random_state=42, fit LinearRegression, and compute on the test set mae, rmse and r2. Print each rounded to 2 decimals.

Quick Quiz

Q1.

Linear regression predicts...

Q2.

What does gradient descent do?

Q3.

An R² of 0.92 on the test set means...

Q4.

Which metric is in the same units as the target and punishes large errors more?