🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Statistics for Data Science & Analytics › Lesson 8
TEC-DATA85-02 · Lesson 8 · 12 clock hours · lab

Correlation and Simple Linear Regression

Objective. Students compute Pearson correlation coefficients, fit a simple linear regression model, interpret coefficients and R-squared, and check residual assumptions.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Correlation and Simple Linear Regression

Why These Tools Matter

Data scientists constantly ask: Do two variables move together, and can one variable predict another? Correlation and simple linear regression are the foundational tools for answering those questions. They appear in every major data analytics credential — Google Data Analytics, CompTIA Data+, IBM Data Science Professional, and Microsoft PL-300 workflows all expect you to interpret and communicate these statistics accurately.

---

Pearson Correlation Coefficient

The Pearson correlation coefficient (r) measures the strength and direction of the linear relationship between two continuous variables. Its value always falls between –1 and +1.

A common rule of thumb: |r| < 0.3 is weak, 0.3–0.7 is moderate, and |r| > 0.7 is strong, though context always matters.

The formula is:

```

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

```

In practice you will use `pandas` or `scipy.stats.pearsonr()` rather than computing this by hand for large datasets.

Important limitation: Correlation measures only linear association. Two variables can have a strong curved relationship yet an r near zero. Always pair a numeric result with a scatter plot.

---

Correlation Matrix and Heat Map

When you have several variables, a correlation matrix shows every pairwise r value in a table. A heat map (seaborn's `heatmap()`) colors each cell so that strong positive correlations appear in one color and strong negative correlations in another. This visualization lets you quickly spot which pairs of variables deserve further analysis and which are essentially unrelated.

```python

import seaborn as sns

corr_matrix = df[cols].corr() # Pearson by default

sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f')

```

---

Simple Linear Regression

Simple linear regression fits a straight line through data to model the relationship between one predictor (X) and one outcome (Y):

```

ŷ = β₀ + β₁x

```

The Ordinary Least Squares (OLS) method finds the line that minimizes the sum of squared differences between observed values (y) and predicted values (ŷ). These differences are called residuals (e = y − ŷ).

In Python you can use either `statsmodels` (for a detailed summary table) or `scikit-learn` (for prediction pipelines).

```python

import statsmodels.formula.api as smf

model = smf.ols('SalePrice ~ GrLivArea', data=df).fit()

print(model.summary())

```

---

Interpreting the Summary Table

The OLS summary provides several key statistics:

---

Residual Diagnostics

OLS regression rests on several assumptions. Violating them can make coefficients unreliable. Always check residuals after fitting.

1. Linearity: Residuals vs. fitted plot should show points scattered randomly around zero — no curve.

2. Constant variance (homoscedasticity): The spread of residuals should be roughly equal across all fitted values. A fan shape signals heteroscedasticity.

3. Normality of residuals: A QQ-plot (quantile-quantile plot) compares residual quantiles to a normal distribution. Points following the diagonal line indicate normality; heavy tails mean departures.

4. Independence: Residuals should not show patterns by time or group.

Common remediations:

---

Data Safety and Integrity Notes

Data science does not involve physical hazards like lockout/tagout, but professional safety still applies:

---

Lab Workflow Summary

1. Load and inspect the Ames housing dataset.

2. Select five variable pairs, compute Pearson r, build a heat map.

3. Fit OLS regression of `SalePrice` on `GrLivArea`.

4. Interpret slope, intercept, R², and p-value in plain English.

5. Plot residuals vs. fitted values and a QQ-plot; write your findings.

Refer to OpenIntro Statistics Chapter 8 for additional examples and derivations.

Key terms10

Pearson correlation coefficient (r)A number between –1 and +1 that measures the strength and direction of the linear relationship between two continuous variables.
Correlation matrixA table showing Pearson r values for every pair of selected variables in a dataset.
Ordinary Least Squares (OLS)A method of fitting a regression line by minimizing the sum of squared residuals (differences between observed and predicted values).
Intercept (β₀)The predicted value of the outcome variable when the predictor equals zero; the point where the regression line crosses the Y-axis.
Slope (β₁)The expected change in the outcome variable for each one-unit increase in the predictor variable.
R-squared (R²)The proportion of variance in the outcome variable explained by the predictor(s); ranges from 0 to 1.
ResidualThe difference between an observed value and the value predicted by the regression model (e = y − ŷ).
HomoscedasticityThe assumption that the variance of residuals is roughly constant across all fitted values; its violation is called heteroscedasticity.
QQ-plot (quantile-quantile plot)A diagnostic graph that compares the quantiles of residuals to the quantiles of a normal distribution to assess the normality assumption.
Heat mapA color-coded grid visualization used to display a correlation matrix, making it easy to spot strong and weak relationships at a glance.

Worked examples4

1. Five houses have the following living area (sq ft) and sale prices ($1,000s): (800, 105), (1200, 150), (1500, 190), (1800, 230), (2100, 275). Calculate the Pearson r by hand.
  1. List x values: 800, 1200, 1500, 1800, 2100. Compute x̄ = (800+1200+1500+1800+2100)/5 = 7400/5 = 1480.
  2. List y values: 105, 150, 190, 230, 275. Compute ȳ = (105+150+190+230+275)/5 = 950/5 = 190.
  3. Compute (xᵢ − x̄) for each: −680, −280, 20, 320, 620.
  4. Compute (yᵢ − ȳ) for each: −85, −40, 0, 40, 85.
  5. Compute (xᵢ − x̄)(yᵢ − ȳ) for each: (−680)(−85)=57800, (−280)(−40)=11200, (20)(0)=0, (320)(40)=12800, (620)(85)=52700. Sum = 57800+11200+0+12800+52700 = 134500.
  6. Compute (xᵢ − x̄)²: 462400, 78400, 400, 102400, 384400. Sum = 1028000.
  7. Compute (yᵢ − ȳ)²: 7225, 1600, 0, 1600, 7225. Sum = 17650.
  8. r = 134500 / √(1028000 × 17650) = 134500 / √(18144200000) = 134500 / 134701 ≈ 0.999.
Answer: r ≈ 0.999, indicating an extremely strong positive linear relationship between living area and sale price in this sample.
2. A simple linear regression of sale price (Y, in $1,000s) on living area (X, in sq ft) produces: intercept β₀ = 20.5, slope β₁ = 0.105. Predict the sale price of a house with 1,650 sq ft, and interpret the slope.
  1. Write the regression equation: ŷ = 20.5 + 0.105 × x.
  2. Substitute x = 1650: ŷ = 20.5 + 0.105 × 1650 = 20.5 + 173.25 = 193.75.
  3. State the predicted price: $193,750 (since Y is in $1,000s, multiply by 1000).
  4. Interpret the slope: For each additional square foot of living area, the model predicts sale price increases by $0.105 thousand ($105).
Answer: Predicted sale price = $193,750. The slope means each additional square foot is associated with a $105 increase in predicted sale price.
3. A regression model has R² = 0.68. Explain what this means and calculate the proportion of variance NOT explained by the model.
  1. R² = 0.68 means the predictor (living area) explains 68% of the variation in sale price.
  2. Proportion unexplained = 1 − R² = 1 − 0.68 = 0.32.
  3. Interpret: 32% of the variation in sale price is due to factors other than living area (e.g., location, age, condition).
Answer: 68% of the variance in sale price is explained by the model; 32% remains unexplained by living area alone.
4. You fit a regression model and plot residuals vs. fitted values. The plot shows a fan shape: residuals are tightly clustered at low fitted values but spread widely at high fitted values. Name the assumption being violated and suggest one remediation.
  1. A fan shape (increasing spread) in the residuals vs. fitted plot indicates that residual variance grows as the fitted value grows.
  2. This pattern violates the homoscedasticity assumption (constant variance of residuals).
  3. One common remediation: apply a log transformation to the outcome variable Y. This often stabilizes variance when Y is right-skewed or grows multiplicatively.
  4. After transforming, refit the model and re-examine the residual plot to check whether the fan shape is reduced.
Answer: Violation: heteroscedasticity. Suggested remediation: log-transform the outcome variable (e.g., use log(SalePrice) as Y) and refit the model.

The math in this lesson3

Learners fit a least-squares regression line and interpret slope, intercept and R-squared.
S-ID.6S-ID.7S-ID.8
Brush up in the math halls at newSchoolWorks.com:
In class: Correlation lab: students compute Pearson r between five variable pairs in a housing dataset, produce a correlation matrix heat map with seaborn, and identify the pair with the strongest and weakest linear relationship. · OLS regression lab: using statsmodels or scikit-learn, students fit a regression of house price on square footage, print the summary table, interpret the slope and intercept in context, and calculate a predicted value for a new observation. · Residual diagnostics: students plot residuals vs. fitted values and a QQ-plot; they identify at least one assumption violation if present, describe it in writing, and suggest one remediation (log transform, removing outlier, etc.).
Materials: Jupyter Notebook, pandas, statsmodels, scikit-learn, seaborn; housing dataset (e.g., Ames Iowa housing data, public domain); OpenIntro Statistics Chapter 8
Check: Notebook graded on 12-point rubric: correct correlation matrix (3 pts), correct regression output interpretation (5 pts), valid residual analysis (4 pts); pass mark 75%.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data Analysis and Statistics
1. A Pearson correlation of r = –0.85 between two variables indicates which of the following?
Data Analysis and Statistics
2. In a regression equation ŷ = 15 + 0.08x, where x is square footage and ŷ is price in $1,000s, what does the value 0.08 represent?
Data Analysis and Statistics
3. A regression model produces R² = 0.45. Which statement correctly interprets this result?
Data Analysis and Statistics
4. A QQ-plot of regression residuals shows points that curve sharply away from the diagonal reference line at both ends. What does this indicate?
Data Analysis and Statistics
5. You compute a correlation matrix for six housing variables and find that 'number of bathrooms' and 'sale price' have r = 0.12. What is the most appropriate conclusion?
Data Tools and Programming
6. Which Python function from statsmodels is used to fit an OLS regression model using a formula string such as 'SalePrice ~ GrLivArea'?
Data Analysis and Statistics
7. A residuals-vs-fitted plot shows a distinct U-shaped (curved) pattern. Which regression assumption does this most directly violate?
Data Analysis and Statistics
8. An analyst fits a regression model and notices the residuals fan out (increase in spread) as fitted values increase. Which remediation is most commonly recommended first?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.