Correlation
Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 30 of 64.
A feature that moves with the target helps a model predict it. The correlation r scores how tightly two columns follow a straight line, from -1 to 1:
Six weeks of a shop's ads and sales: np.corrcoef returns a 2 by 2 table, each array against each, with r at [0, 1]. A column's .corr gives it directly:
ads = np.array([100, 200, 150, 300, 250, 50])
sales = np.array([430, 520, 560, 760, 610, 410])
print(np.round(np.corrcoef(ads, sales), 2))
shop = pd.DataFrame({"ads": ads, "sales": sales})
print(np.round(shop["ads"].corr(shop["sales"]), 2))This prints:
[[1. 0.94]
[0.94 1. ]]
0.94At 0.94, weeks with more ads clearly sold more.
Challenge
MediumA gym tracked 20 members for three months in gym.csv, with the columns visits, classes, minutes_per_visit, age and weight_change_kg. The program reads two column names.
- Print the two names and their
r, rounded to 2 decimals, as below. - Print
Direction:positivewhenris above 0.3,negativebelow -0.3, elsenone.
For a swimming club's laps and minutes:
laps and minutes: r = 0.95
Direction: positiveTry it yourself
import numpy as np
import pandas as pd
gym = pd.read_csv("gym.csv")
first = input()
second = input()
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Statistics for ML
1Center and Spread
Mean and MedianPercentiles and QuartilesVariance and StdSample or Population?The Most Common ValueRecap: Delivery Times4Samples and Populations
Population and SampleSample Means VaryThe Sampling DistributionBigger Samples, Less NoiseRecap: Polling a Town2Distributions
Density HistogramsShapes of DataThe Normal CurveThe 68-95-99.7 RuleZ-ScoresRecap: Battery Life3Probability by Simulation
Probability as FrequencyThe Law of Large NumbersSums of DiceExpected ValueConditional ProbabilityRecap: Dice Stall Odds6Relationships
Reading Scatter PlotsCorrelationCorrelation MatrixCorrelation HeatmapsCorrelation Is Not CauseRecap: Ice Cream and SunPractice on your own: Online Python compiler