⚡0 XP🔥0

Correlation and Linear Regression

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

Scatter plots, covariance, Pearson's correlation coefficient r, correlation vs causation, fitting a least-squares line, interpreting slope and intercept, R², residuals and making predictions in Python.

Looking at relationships#

Does studying more improve marks? Do bigger advertising budgets bring more sales? Is a car's price related to its age? Start with a scatter plot.

▶ Try it YourselfPython
Ctrl + Enter to run

Describe a scatter plot by its direction (positive / negative), form (straight line or curve), strength (how tightly the points follow the pattern) and outliers.

Covariance and correlation#

Covariance shows the direction of the relationship, but its size depends on the units. Pearson's correlation coefficient r standardises it to the range −1 to +1:

r = Σ(x − x̄)(y − ȳ) ÷ √[ Σ(x − x̄)² · Σ(y − ȳ)² ]

r Meaning
+1 perfect positive straight line
0.7 to 0.9 strong positive
0.3 to 0.7 moderate
around 0 no linear relationship
−1 perfect negative straight line
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

r only measures straight-line relationships. The U-shaped data above has a strong relationship but r close to 0. Always plot the data first.

Correlation is not causation#

A high correlation can come from:

  • causation - x really changes y;
  • a confounder - a third variable drives both (summer heat → ice-cream sales and swimming accidents);
  • reverse causation - y changes x;
  • coincidence - with enough variables, some will correlate by chance.
हिंदी में समझें

Correlation ≠ Causation. गर्मियों में आइसक्रीम की बिक्री और डूबने की घटनाएं दोनों बढ़ती हैं - पर आइसक्रीम डूबने का कारण नहीं है। असली कारण तीसरी चीज़ है: गर्मी। इसलिए दो चीज़ें साथ-साथ बढ़ें तो तुरंत यह न मानें कि एक दूसरे को चला रही है।

Simple linear regression#

Regression fits the line ŷ = a + b·x that best predicts y from x. Least squares chooses a and b to minimise the sum of squared residuals (actual − predicted):

b = Σ(x − x̄)(y − ȳ) ÷ Σ(x − x̄)², a = ȳ − b·x̄

▶ Try it YourselfPython
Ctrl + Enter to run

Interpreting the line#

  • Slope b ≈ 6.26 - each extra hour of study is associated with about 6.3 more marks.
  • Intercept a ≈ 29.6 - predicted marks at 0 hours (only meaningful if x = 0 is realistic).
  • R² ≈ 0.996 - the line explains 99.6% of the variation in marks in this (made-up, very tidy) data. Real data is much noisier.
Tip

Check the residuals: they should look like random noise around 0. A pattern (a curve, or spread that grows) means a straight line is the wrong model.

Common Mistake

Don't extrapolate far outside your data. The line predicts 155 marks for 20 hours a day - impossible! A model is only trustworthy in the range it was fitted on.

From here to machine learning#

Linear regression with many inputs (price = a + b₁·area + b₂·bedrooms + b₃·age) is multiple regression - the first model in every machine learning course. In scikit-learn:

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X, y)       # X: table of inputs, y: target
model.coef_, model.intercept_, model.score(X, y)   # slopes, intercept, R²

Summary#

  • Plot first; describe direction, form, strength and outliers.
  • Pearson's r measures linear association from −1 to +1; correlation ≠ causation.
  • Least squares: b = Σ(x−x̄)(y−ȳ)/Σ(x−x̄)², a = ȳ − b·x̄.
  • Slope = change in y per unit of x; R² = share of variation explained; check residuals; don't extrapolate.

Practice Exercises

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

1

Study hours and marks

Using the formulas (NumPy is fine, but don't use np.polyfit), compute:

  • r - Pearson's correlation between hours and marks
  • b (slope) and a (intercept) of the least-squares line marks = a + b × hours
  • pred9 - the predicted marks for 9 hours of study

Print:

r = 0.9980
marks = 29.57 + 6.26 x hours
9 hours -> 85.9 marks
Expected output:
r = 0.9980
marks = 29.57 + 6.26 x hours
9 hours -> 85.9 marks
2

Advertising budget

A shop's monthly advertising spend (Rs thousand) and sales (Rs thousand) are given. Fit the line with np.polyfit(ad, sales, 1) (it returns [slope, intercept]), store them in b and a, and print the forecast for a budget of 40:

Forecast for 40: 302.7

Expected output:
Forecast for 40: 302.7

Quick Quiz

Q1.

Pearson's r = -0.85 between hours of TV and exam marks means...

Q2.

Ice-cream sales and drowning cases are strongly correlated. The most likely explanation is...

Q3.

A fitted line is marks = 30 + 6.3 × hours. What does 6.3 mean?

Q4.

R² = 0.81 means...

Q5.

Least squares chooses the line that minimises...