Skip to main content
Correlation and Regression

Correlation and Regression: Relationships and Predictions

The House Price Question

You’re a real estate analyst. A client asks: “I’m looking at a house with 2,500 square feet. What should I expect to pay?” You have data on recent sales. Can you use the relationship between size and price to make predictions? This is where statistics becomes prediction - the first step toward machine learning.
Estimated Time: 4-5 hours
Difficulty: Intermediate
Prerequisites: Modules 1-5 (especially Probability and Distributions)
What You’ll Build: House price predictor, multi-variable regression model
🔗 ML Connection: Regression is the foundation of ALL supervised learning:Linear regression IS a 1-layer neural network. Master this, and you understand deep learning’s core!

Correlation: Measuring Relationships

Correlation measures the strength and direction of a linear relationship between two variables. Analogy: Think of correlation as measuring how well two dancers are synchronized. A correlation of +1 means they are moving in perfect unison — when one steps forward, the other does too, in exact proportion. A correlation of -1 means they are perfectly mirrored — when one steps forward, the other steps back. A correlation of 0 means they are dancing independently, like strangers at a concert.

The Pearson Correlation Coefficient

r=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2i=1n(yiyˉ)2r = \frac{\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i - \bar{x})^2} \cdot \sqrt{\sum_{i=1}^{n}(y_i - \bar{y})^2}} The value ranges from -1 to +1:
Correlation Coefficient Visualization
Output:
Nearly perfect positive correlation. As square footage increases, so does price.
Scatter Plot with Correlation

Correlation Does Not Imply Causation

This is perhaps the most important phrase in all of statistics.
Three possibilities when A and B are correlated:
  1. A causes B
  2. B causes A
  3. A third variable C causes both
To establish causation, you need:
  • Controlled experiments (A/B testing)
  • Time sequence (cause before effect)
  • Plausible mechanism
  • Ruling out confounders
Statistical Mistake in ML — Confusing Predictive Power with Causal Relationships: In ML, a feature that is highly correlated with the target can be an excellent predictor without being a cause. For example, the number of fire trucks at a scene is highly correlated with the damage amount — but sending fewer trucks would not reduce damage. This distinction matters when you use ML models to inform interventions. If a churn model finds that “sent a cancellation survey” strongly predicts churn, removing the survey will not reduce churn — the survey was a symptom, not a cause. Always ask: “If we changed this feature, would the outcome actually change?”

Simple Linear Regression: The Line of Best Fit

Linear regression finds the line that best predicts Y from X. The equation: y^=β0+β1x\hat{y} = \beta_0 + \beta_1 x Where:
  • y^\hat{y} = predicted value
  • β0\beta_0 = intercept (value of y when x = 0)
  • β1\beta_1 = slope (change in y for each unit change in x)

Finding the Best Line

We minimize the sum of squared errors (residuals): SSE=i=1n(yiy^i)2=i=1n(yiβ0β1xi)2\text{SSE} = \sum_{i=1}^{n}(y_i - \hat{y}_i)^2 = \sum_{i=1}^{n}(y_i - \beta_0 - \beta_1 x_i)^2 The optimal coefficients: β1=(xixˉ)(yiyˉ)(xixˉ)2=rsysx\beta_1 = \frac{\sum(x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2} = r \cdot \frac{s_y}{s_x} β0=yˉβ1xˉ\beta_0 = \bar{y} - \beta_1 \bar{x}
Output:

Interpreting the Coefficients

  • Intercept (16.67): Theoretical price for a 0 sqft house (not meaningful here)
  • Slope (0.1676): Each additional square foot adds $167.60 to the price

Making Predictions

Output:

Evaluating Regression Models

R-Squared (Coefficient of Determination)

measures how much of the variance in Y is explained by X. R2=1SSresidualSStotal=1(yiy^i)2(yiyˉ)2R^2 = 1 - \frac{\text{SS}_{\text{residual}}}{\text{SS}_{\text{total}}} = 1 - \frac{\sum(y_i - \hat{y}_i)^2}{\sum(y_i - \bar{y})^2}
Output:

Residual Analysis

Residuals = Actual - Predicted. Good models have residuals that:
  1. Are randomly scattered (no pattern)
  2. Have constant variance (homoscedasticity)
  3. Are approximately normally distributed

Multiple Linear Regression

Real house prices depend on more than just size. Let’s add more features. y^=β0+β1x1+β2x2+...+βpxp\hat{y} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_p x_p

Example: Price from Size, Bedrooms, and Age

Output:

Interpreting Multiple Regression

  • Each sqft adds $142.50 holding other variables constant
  • Each bedroom adds $21,893 holding other variables constant
  • Each year of age reduces price by $3,125 holding other variables constant
Analogy for “holding other variables constant”: Imagine you are at a buffet and you want to know how much each item costs. Multiple regression is like saying: “If I add one more scoop of mashed potatoes (bedrooms), and keep everything else on my plate the same, how much more does my plate cost?” Each coefficient isolates the contribution of one feature while keeping all others fixed. This is the same concept as partial derivatives in calculus — and it is exactly what neural network backpropagation computes for each weight.
ML Application — Feature Engineering Insight: In multiple regression, the coefficient for a feature depends on what OTHER features are in the model. Add a strongly correlated feature and both coefficients may change dramatically (multicollinearity). In ML, this manifests as unstable feature importance rankings across different random seeds or cross-validation folds. If your feature importances are not stable, suspect multicollinearity and consider removing redundant features or using regularization.

Feature Scaling and Standardization

When features have different scales, it’s hard to compare coefficients.

Polynomial Regression: Non-Linear Relationships

What if the relationship isn’t a straight line?

Assumptions of Linear Regression

For valid inference, linear regression assumes:

Mini-Project: House Price Predictor

Build a complete house price prediction system:
Output:

Practice Exercises

Exercise 1: Fuel Efficiency


Interview Questions

Question: In a salary prediction model, the coefficient for years_experience is 5000 and for has_phd (0/1) is 15000. How do you interpret these?
Answer:
  • years_experience = 5000: Each additional year of experience is associated with $5,000 higher salary, holding other variables constant
  • has_phd = 15000: Having a PhD is associated with $15,000 higher salary compared to not having a PhD, holding experience constant
Important caveats:
  1. These are associations, not necessarily causal
  2. “Holding constant” means comparing people with same values for other predictors
  3. For categorical variables like has_phd, the interpretation is relative to the reference category (no PhD)
Question: Your model predicting delivery time has R-squared = 0.65. A colleague says “65% accuracy isn’t good enough.” Is this correct?
Answer: No, this is a common misconception.R-squared = 0.65 means the model explains 65% of the variance in delivery time, not that it’s “65% accurate.”This could be quite good depending on context:
  • For predicting human behavior, R-squared = 0.65 is excellent
  • Remaining 35% of variance might be inherently unpredictable (traffic, weather)
  • Check RMSE to understand actual prediction error in meaningful units
Question: Data shows strong correlation (r=0.85) between ice cream sales and sunburns. Should we stop selling ice cream to prevent sunburns?
Answer: No! This is a classic example of confounding.Both ice cream sales and sunburns are caused by a lurking variable: hot, sunny weather.
To establish causation, you need:
  1. Controlled experiment: Randomly assign ice cream consumption
  2. Time ordering: Cause must precede effect
  3. Plausible mechanism: Biological/logical pathway
  4. Rule out confounders: Account for all alternative explanations
Question: You’re predicting house prices with both square_feet and num_rooms. The individual p-values are high (not significant), but the model R² is 0.85. What’s happening?
Answer: This is likely multicollinearity - the predictors are highly correlated with each other.When predictors are correlated:
  • The model can still predict well (good R²)
  • But individual coefficient estimates become unstable
  • Standard errors inflate, making p-values high
  • Hard to isolate the effect of each variable
Solutions:
  1. Remove one predictor: Use only square_feet OR num_rooms
  2. Create composite variable: rooms_per_sqft
  3. Use regularization: Ridge regression handles multicollinearity
  4. VIF check: Variance Inflation Factor > 10 indicates problems

Practice Challenge

Create a production-ready regression analysis for house prices:
Full Solution:

📝 Practice Exercises

Exercise 1

Calculate correlation and simple linear regression

Exercise 2

Build and interpret multiple regression models

Exercise 3

Evaluate model performance with R² and RMSE

Exercise 4

Real-world: House price prediction system

Key Takeaways

Correlation

  • Measures linear relationship strength (-1 to 1)
  • Correlation is not causation
  • High correlation can be spurious

Simple Regression

  • Predicts Y from single X
  • y = β₀ + β₁x
  • Minimize sum of squared errors

Multiple Regression

  • Predicts Y from multiple X variables
  • Coefficients show effect holding others constant
  • Standardize to compare importance

Evaluation

  • R² = variance explained
  • RMSE = typical error size
  • Check assumptions via residual plots

Common Pitfalls

Regression Mistakes to Avoid:
  1. Causation from Correlation - Regression shows association, not causation; beware of confounders
  2. Ignoring Multicollinearity - Highly correlated predictors make coefficients unstable and uninterpretable
  3. Extrapolating Beyond Data - Models are only valid within the range of training data
  4. Ignoring Residual Patterns - Non-random residuals indicate model misspecification
  5. Misinterpreting R² - R² is not accuracy; 0.65 doesn’t mean “65% correct”
  6. Forgetting to Scale - For comparing coefficient importance, standardize your features first

Connection to Machine Learning

ML Connection: Linear regression is the simplest neural network—one layer with linear activation. Understanding regression gives you intuition for how all deep learning works: find coefficients (weights) that minimize a loss function using gradient-based optimization.
Coming up next: We’ll connect all these statistical concepts to Machine Learning - seeing how statistics powers the algorithms that learn from data.

Next: From Statistics to ML

See how statistics becomes machine learning

Interview Deep-Dive

Strong Answer:
  • R-squared of 0.45 means the model explains 45% of the variance in the target variable. Whether that is “terrible” depends entirely on the domain and the alternative.
  • In physical sciences (modeling a chemical reaction), R-squared of 0.45 would indeed be poor because the underlying relationships are deterministic and we expect R-squared above 0.9. But in social sciences, economics, and most business prediction problems, R-squared of 0.45 is often quite good because human behavior has enormous inherent unpredictability.
  • The right question is not “is 0.45 high enough?” but “is this model useful?” If you are predicting customer lifetime value and the model correctly identifies the top 20% of customers with 80% precision, it is delivering massive business value regardless of the R-squared number.
  • I would also check: What is RMSE in practical units? If the model predicts delivery time with RMSE of 5 minutes and the business only needs accuracy within 10 minutes, then R-squared is irrelevant — the model is accurate enough. R-squared is a summary statistic about variance explained; business impact depends on whether the predictions are actionable.
Follow-up: Can you have a model that is useful for prediction but has low R-squared, and vice versa?Absolutely. Low R-squared, useful model: a model predicting whether a user will click an ad might explain only 5% of variance (because individual clicks are inherently noisy), but if it correctly ranks users by click probability and the top-ranked 10% clicks at 3x the average rate, the ad targeting system generates millions in revenue. The model captures signal in the mean, even though individual outcomes are unpredictable. High R-squared, useless model: a model predicting yesterday’s stock price from today’s stock price will have R-squared near 0.99 because prices are highly autocorrelated. But it is useless for trading because it does not predict the future. Similarly, a model with R-squared=0.95 that is overfit to training data will have high in-sample R-squared but fail completely on new data. The lesson: R-squared measures in-sample fit, not predictive value, and certainly not business utility.
Strong Answer:
  • I use this analogy: “Imagine I show you data proving that cities with more fire stations have more fires. Does that mean fire stations cause fires? Obviously not — bigger cities have both more fires and more fire stations. The city size is the hidden third factor driving both.”
  • A regression coefficient tells you the association between X and Y after controlling for other variables in the model. But it cannot prove causation because there might be confounders you did not include. If your model predicts that “customers who use the mobile app spend 30% more,” the regression is telling you truth — app users do spend more. But it is not telling you that making someone download the app will cause them to spend more. The likely explanation is that already-engaged customers both use the app and spend more.
  • To establish causation from a regression, you need either a randomized experiment (assign some users to the app randomly) or a carefully designed observational study with an instrumental variable or regression discontinuity design.
  • I always warn stakeholders: “This model tells us what is associated with higher revenue. It does not tell us what to change to increase revenue. For that, we need experiments.”
Follow-up: Can you describe a situation where you would use an instrumental variable to establish causation from observational data?A classic example: you want to know if education causes higher earnings, but people who pursue more education might inherently be more ambitious or talented (confounders). An instrumental variable approach uses something that affects education but does not directly affect earnings — for example, proximity to a college. People who grew up near a college are more likely to attend (the instrument is relevant) but distance from a college should not directly affect your earning potential (the exclusion restriction). By using distance as an instrument, you can isolate the causal effect of education on earnings that is not contaminated by the confounder. In tech, a common IV example is using a randomized encouragement design: you randomly encourage some users to adopt a feature (the instrument), then measure the outcome. The encouragement affects adoption without directly affecting the outcome, allowing you to estimate the causal effect of adoption.
Strong Answer:
  • This is almost certainly multicollinearity. The new feature is correlated with one of the existing features. When both are in the model, the coefficient estimates become unstable because the model cannot cleanly separate their individual effects. A sign flip means the partial effect (holding the new variable constant) is different from the marginal effect (ignoring it).
  • A concrete example: predicting house price with square footage and number of rooms. Both are highly correlated (bigger houses have more rooms). With only square footage, its coefficient is positive and strong. Add number of rooms, and the square footage coefficient might shrink or even flip negative, because the model is now trying to ask “holding number of rooms constant, what is the effect of more square footage?” — which is a bizarre question since you cannot really add square footage without adding rooms.
  • To diagnose this, I would compute the Variance Inflation Factor (VIF) for each predictor. VIF above 5 suggests concerning multicollinearity, above 10 is severe.
  • The solution depends on the goal. For prediction, multicollinearity does not matter — the model still predicts well. For interpretation, it is a serious problem. Solutions include dropping one of the correlated features, combining them into a composite, using PCA to create orthogonal features, or switching to a regularized model like Ridge regression which handles multicollinearity gracefully.
Follow-up: Why does Ridge regression help with multicollinearity while OLS does not?In OLS, the coefficient estimates minimize the sum of squared residuals. When features are highly correlated, many different combinations of coefficients produce nearly the same fit, so the estimates are unstable — small changes in data cause large swings in coefficients. Ridge regression adds a penalty term (lambda times the sum of squared coefficients) to the objective function. This penalty shrinks coefficients toward zero and, critically, prevents them from taking extreme values to compensate for each other. The result is that correlated features get more similar, moderate coefficients rather than one huge positive and one huge negative coefficient. The tradeoff is a small increase in bias (the coefficients are shrunk from their OLS values) in exchange for a large reduction in variance. For multicollinear data, this tradeoff almost always improves both interpretability and out-of-sample prediction.