Skip to main content

Covariance & Correlation Analysis

Topic - Covariance and correlation evaluate bivariate relationships between numerical variables. While covariance establishes the directional co-movement of two features, Pearson correlation standardizes this relationship into a scale-free metric bounded between -1 and +1, quantifying both direction and linear strength.


1. Intuition & Architectural Flow​

When examining two continuous features (e.g., advertising expenditure vs product sales, or engine displacement vs vehicle fuel efficiency), we must determine whether changes in one variable systematically associate with changes in the other.

Core Intuition​

  • Covariance: If values of XX above its mean consistently coincide with values of YY above its mean, their product of deviations (Xi−Xˉ)(Yi−Yˉ)(X_i - \bar{X})(Y_i - \bar{Y}) is positive. If XX rises while YY falls, the product is negative. However, because covariance is measured in the product of the original units (e.g., USD×kg\text{USD} \times \text{kg}), its raw magnitude is uninterpretable.
  • Correlation: Normalizing the covariance by the product of both individual standard deviations removes the measurement scale, producing a pure, dimensionless number between −1-1 and +1+1.

2. Mathematical Formulations & Derivations​

Covariance​

For two random variables XX and YY:


Cov(X,Y)=σXY=1N∑i=1N(Xi−μX)(Yi−μY)=E[(X−μX)(Y−μY)]\text{Cov}(X, Y) = \sigma_{XY} = \frac{1}{N} \sum_{i=1}^N (X_i - \mu_X)(Y_i - \mu_Y) = \mathbb{E}[(X - \mu_X)(Y - \mu_Y)]

Pearson Correlation Coefficient (rr)​

Karl Pearson defined the correlation coefficient rXYr_{XY} as the ratio of sample covariance to the product of sample standard deviations:

rXY=Cov(X,Y)sX⋅sY=∑i=1n(Xi−Xˉ)(Yi−Yˉ)∑i=1n(Xi−Xˉ)2∑i=1n(Yi−Yˉ)2r_{XY} = \frac{\text{Cov}(X, Y)}{s_X \cdot s_Y} = \frac{\sum_{i=1}^n (X_i - \bar{X})(Y_i - \bar{Y})}{\sqrt{\sum_{i=1}^n (X_i - \bar{X})^2} \sqrt{\sum_{i=1}^n (Y_i - \bar{Y})^2}}

Mathematical Properties of Pearson Correlation​

Click the tabs below to explore its foundational mathematical constraints:


  • By the Cauchy-Schwarz Inequality in linear algebra:

∣⟨u,v⟩∣≤∥u∥⋅∥v∥  ⟹  ∣∑i=1n(Xi−Xˉ)(Yi−Yˉ)∣≤∑(Xi−Xˉ)2∑(Yi−Yˉ)2\lvert \langle u, v \rangle \rvert \le \|u\| \cdot \|v\| \implies \left\lvert \sum_{i=1}^n (X_i - \bar{X})(Y_i - \bar{Y}) \right\rvert \le \sqrt{\sum (X_i - \bar{X})^2} \sqrt{\sum (Y_i - \bar{Y})^2}

  • Therefore, −1.0≤rXY≤+1.0-1.0 \le r_{XY} \le +1.0 holds universally for any valid dataset with non-zero variance.

3. Comparative Taxonomy: Covariance vs Correlation​

DimensionCovariance (Cov(X,Y)\text{Cov}(X, Y))Correlation (rXYr_{XY})
Fundamental GoalMeasures whether two variables vary in the same directionMeasures both the direction and the relative linear strength
Scale & UnitsExpressed in the product of original units (e.g., kg×cm\text{kg} \times \text{cm})Completely dimensionless and unit-free
Numerical Range−∞≤Cov(X,Y)≤+∞-\infty \le \text{Cov}(X, Y) \le +\infty−1.0≤rXY≤+1.0-1.0 \le r_{XY} \le +1.0
Scale DependencyHighly sensitive to unit changes (e.g., meters →\to millimeters inflates covariance by 1,0001,000)Invariant to positive linear scale and origin transformations
Direct ComparabilityCannot compare relationships across different pairs of variablesDirectly comparable across entirely unrelated domains

4. Step-by-Step Numerical Walkthrough​

Academic exams frequently present pairs of raw values and require computing both sample covariance and the Pearson correlation coefficient.

Problem​

A factory monitors raw material imports (XX in metric tons) and finished product exports (YY in metric tons) across 5 production months:

X=[10,11,14,14,21],Y=[12,14,15,16,23]X = [10, 11, 14, 14, 21], \quad Y = [12, 14, 15, 16, 23]

Compute:

  1. Sample means Xˉ\bar{X} and Yˉ\bar{Y}
  2. Sample Covariance Cov(X,Y)\text{Cov}(X, Y)
  3. Sample Standard Deviations sXs_X and sYs_Y
  4. Pearson Correlation Coefficient rXYr_{XY}

Step 1: Calculate Sample Means (n=5n = 5)​

Xˉ=10+11+14+14+215=705=14.0\bar{X} = \frac{10 + 11 + 14 + 14 + 21}{5} = \frac{70}{5} = 14.0

Yˉ=12+14+15+16+235=805=16.0\bar{Y} = \frac{12 + 14 + 15 + 16 + 23}{5} = \frac{80}{5} = 16.0

Step 2: Tabulate Deviations and Cross-Products​

Month iiXiX_iYiY_i(Xi−Xˉ)(X_i - \bar{X})(Yi−Yˉ)(Y_i - \bar{Y})(Xi−Xˉ)2(X_i - \bar{X})^2(Yi−Yˉ)2(Y_i - \bar{Y})^2(Xi−Xˉ)(Yi−Yˉ)(X_i - \bar{X})(Y_i - \bar{Y})
11012−4.0-4.0−4.0-4.016.016.016.016.0+16.0+16.0
21114−3.0-3.0−2.0-2.09.09.04.04.0+6.0+6.0
314150.00.0−1.0-1.00.00.01.01.00.00.0
414160.00.00.00.00.00.00.00.00.00.0
52123+7.0+7.0+7.0+7.049.049.049.049.0+49.0+49.0
Sum (∑\sum)70800.00.074.070.0+71.0

Step 3: Compute Sample Covariance (n−1=4n - 1 = 4)​

Cov(X,Y)=∑(Xi−Xˉ)(Yi−Yˉ)n−1=71.04=17.75 tons2\text{Cov}(X, Y) = \frac{\sum (X_i - \bar{X})(Y_i - \bar{Y})}{n - 1} = \frac{71.0}{4} = 17.75 \text{ tons}^2

Interpretation: The covariance is positive (+17.75+17.75), indicating that raw material imports and finished exports increase together.

Step 4: Compute Standard Deviations​

sX=∑(Xi−Xˉ)2n−1=74.04=18.5≈4.301s_X = \sqrt{\frac{\sum (X_i - \bar{X})^2}{n - 1}} = \sqrt{\frac{74.0}{4}} = \sqrt{18.5} \approx 4.301

sY=∑(Yi−Yˉ)2n−1=70.04=17.5≈4.183s_Y = \sqrt{\frac{\sum (Y_i - \bar{Y})^2}{n - 1}} = \sqrt{\frac{70.0}{4}} = \sqrt{17.5} \approx 4.183

Step 5: Compute Pearson Correlation Coefficient​

rXY=Cov(X,Y)sX⋅sY=17.754.301×4.183=17.7517.991≈+0.9866r_{XY} = \frac{\text{Cov}(X, Y)}{s_X \cdot s_Y} = \frac{17.75}{4.301 \times 4.183} = \frac{17.75}{17.991} \approx +0.9866

Final Conclusion: r≈+0.987r \approx +0.987 indicates a very strong, nearly perfect positive linear association between imports and exports.


5. Implementation Lab​

tip

Implementation Lab: Covariance Matrices & Correlation Analysis in Python

Execute bivariate analysis, covariance matrices, and correlation heatmaps across multivariate datasets.

Open In Colab

Key Experiments to Run:

  • Experiment 1 (Scale Inflation Test): Multiply feature XX by 1,0001,000. Verify that cov(X, Y) multiplies by 1,0001,000 while corr(X, Y) remains strictly constant.
  • Experiment 2 (The Non-Linear Trap): Generate quadratic data Y=X2Y = X^2 on X∈[−10,10]X \in [-10, 10]. Verify that Pearson r≈0.0r \approx 0.0 despite a perfect deterministic functional relationship.

Comparative Implementation​


import numpy as np
import pandas as pd
from scipy import stats

x = [10, 11, 14, 14, 21]
y = [12, 14, 15, 16, 23]
df = pd.DataFrame({'Imports': x, 'Exports': y})

# 1. Sample Covariance Matrix (ddof=1 applied automatically)
cov_matrix = df.cov()
cov_xy = cov_matrix.loc['Imports', 'Exports']

# 2. Pearson Correlation Matrix & p-value
corr_matrix = df.corr(method='pearson')
r_val, p_val = stats.pearsonr(df['Imports'], df['Exports'])

print(f"Sample Covariance: {cov_xy:.2f}")
print(f"Pearson Correlation (r): {r_val:.4f}")
print(f"Two-Tailed p-value: {p_val:.4e}")

6. Interactive Exploration: Correlation Sandbox​

Observe how the scatter of points aligns as the target correlation coefficient (rr) varies from −1.0-1.0 (perfect inverse linearity) to +1.0+1.0 (perfect direct linearity):

Correlation Strength & Direction Explorer

Adjust the correlation slider to evaluate relationship strength:

Pearson Coefficient (r)
0.80
Classification
Strong Positive Association
Variance Explained (R-squared)
64.0%

7. Exam Traps & Operational Nuances​


  • The Trap: Assuming that r=0r = 0 implies variables XX and YY are statistically independent.
  • The Mathematical Reality: Pearson correlation measures linear association exclusively.
  • Classic Counter-Example: Let X∼Uniform(−1,1)X \sim \text{Uniform}(-1, 1) and Y=X2Y = X^2. Here, YY is completely deterministic based on XX. Yet, Cov(X,Y)=0\text{Cov}(X, Y) = 0 and r=0r = 0. Always inspect scatterplots before declaring lack of association.

8. Summary & Cheatsheet​

Mathematical Core

  • Sample Covariance: sXY=1n−1∑(Xi−Xˉ)(Yi−Yˉ)s_{XY} = \frac{1}{n-1}\sum (X_i - \bar{X})(Y_i - \bar{Y}).
  • Pearson rr: rXY=sXYsXsYr_{XY} = \frac{s_{XY}}{s_X s_Y}, bounded within [−1,+1][-1, +1].
  • Scale Invariance: Linear transformations preserve correlation: r(aX+b,cY+d)=r(X,Y)r(aX+b, cY+d) = r(X, Y) for a, c > 0.

Diagnostic Rules

  • Direction vs Strength: Covariance gives sign only; correlation provides magnitude.
  • Non-Linear Warning: r=0r = 0 does not mean independent; it only means no linear trend.
  • Coefficient of Determination: r2r^2 is the proportion of total variance shared between variables.

info

Key Takeaways

  • Takeaway 1: Covariance indicates direction of co-movement but cannot determine relationship strength because it scales with measurement units.
  • Takeaway 2: Pearson correlation standardizes covariance into a scale-free metric ([−1,1][-1, 1]), enabling direct comparisons across diverse features.
  • Takeaway 3: High correlation does not imply causation, and zero correlation does not rule out complex non-linear relationships.

9. Active Recall & Practice​

Test your understanding by answering first, then clicking to reveal the underlying principles.

Checkpoint Quiz​

Interactive Checkpoint: Self-Test

If all values of variable X are multiplied by 5, what happens to Cov(X, Y) and r(X, Y)?

Review Flashcards​

1. [SCALE] Why is covariance alone insufficient to evaluate the strength of an association?

  • Covariance is scale-dependent. Changing the measurement unit of a variable (e.g., converting height from meters to millimeters) multiplies the covariance by 1,000 without any change in the actual association.
  • Without standardization, a covariance of 500500 cannot be judged as stronger or weaker than a covariance of 55.
2. [EXAM QUESTION] Two variables have Cov(X, Y) = -18. If s_X = 4 and s_Y = 5, what is their correlation coefficient?

  • r=Cov(X,Y)sX⋅sY=−184×5=−1820=−0.90r = \frac{\text{Cov}(X, Y)}{s_X \cdot s_Y} = \frac{-18}{4 \times 5} = \frac{-18}{20} = -0.90
  • This indicates a strong negative linear association.
3. [THEORY] Can Pearson's r be negative while Cov(X, Y) is positive?

  • No. By definition, r=Cov(X,Y)sXsYr = \frac{\text{Cov}(X, Y)}{s_X s_Y}.
  • Since standard deviations sXs_X and sYs_Y are strictly positive real numbers, the algebraic sign of rr is identical to the sign of Cov(X,Y)\text{Cov}(X, Y).