Skip to content

MLDay 3 of 50Foundations

Explore Data Before Modelling

7 min read

You train a model to predict hourly bike rentals, and it scores almost perfectly on the first try. Then you try to use it for tomorrow and it can't run: one of its columns was the answer in disguise, known only after the hour ends. Five minutes with the table would have shown it.

The idea

Exploring a dataset means looking at it before you train anything. You ask three questions.

  1. One column at a time: what values does it take? Summary statistics give the shape in a few numbers: the minimum, the median (the middle value), the mean (the average) and the maximum.
  2. Two columns together: does one move with the other? A scatter plot draws one dot per row, and a correlation puts the trend in one number.
  3. Over time: does the data drift? Compare averages across periods, such as one year against the next.

Along the way you hunt for two kinds of trouble. An outlier is a row far from the rest, like a broken sensor or a storm. A leaky column holds information you won't have when you need the prediction.

Correlation (rr) runs from −1 to +1. Near +1, the dots hug a rising straight line. Near −1, they hug a falling one. Near 0, no straight line fits. It has two limits. It sees only straight lines, so a curved pattern can score near 0. And it isn't cause: ice-cream sales and sunburns move together because of the sun.

A tiny example

Three small datasets, each with xx = 1, 2, 3:

yy values What the dots do rr
2, 4, 6 rise on a perfect line +1
6, 4, 2 fall on a perfect line −1
2, 6, 2 rise, then fall back 0

The third set has a clear pattern: up, then down. Yet r=0r = 0, because no straight line fits it. Keep it in mind for the hourly rentals below.

The formula

Pearson's correlation compares how far each point sits from the average on both axes at once:

r=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2 ∑(yi−yˉ)2r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2 \,\sum (y_i - \bar{y})^2}}
Symbol Meaning
rr the correlation, from −1 to +1
xix_i, yiy_i the two values of row ii
xˉ\bar{x}, yˉ\bar{y} the mean of each column (the bar marks an average)
∑\sum add up over all nn rows

The top is positive when points above average on xx are also above average on yy. The bottom scales the result into the range −1 to +1.

Worked, for (1, 2), (2, 4), (3, 6): xˉ=2\bar{x} = 2 and yˉ=4\bar{y} = 4. The gaps from the mean are −1, 0, 1 for xx and −2, 0, 2 for yy. The top is (−1)(−2)+0+(1)(2)=4(-1)(-2) + 0 + (1)(2) = 4. The bottom is 2×8=4\sqrt{2 \times 8} = 4. So r=4/4=1.0r = 4 / 4 = 1.0.

Try it

One stormy hour hides the trend

Drag a point (or pick one below and use its sliders). Line the points up and r heads towards 1 or −1; scatter them and it falls towards 0.

01020300100200Temperature (°C)Rentals per hour

r = 0.42 (moderate positive)best line ŷ = 3.32·x + 59.8

Seven hours rise steadily with temperature, but one 30 °C hour had a storm and only 20 rentals. That single point drags rr down to 0.42. Drag it up near 240 rentals and watch rr climb to 0.99. One row can make a strong trend look weak, so look at the plot, not just the number.

In code

This report loads the 17,379 hours of rentals (Day 2 covers read_csv). It prints the target's summary, the trend over the two years, and each column's rr with cnt, the rentals that hour.

# script_id: day_003_explore_data/report
import os
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
df = df.assign(temp_c=df["temp"] * 41)                       # undo the ÷ 41

print(df["cnt"].describe().round(1).to_string())            # one column: the target
print(f"hours under 50 rentals: {(df['cnt'] < 50).mean():.0%}")
print("mean by year:", df.groupby("yr")["cnt"].mean().round(1).to_dict())  # over time
cols = ["temp_c", "hum", "windspeed", "hr", "casual", "registered", "cnt"]
print(df[cols].corr()["cnt"].drop("cnt").round(2).to_string())  # pairs: r with cnt
print("cnt == casual + registered everywhere:", (df["cnt"] == df["casual"] + df["registered"]).all())
count    17379.0
mean       189.5
std        181.4
min          1.0
25%         40.0
50%        142.0
75%        281.0
max        977.0
hours under 50 rentals: 28%
mean by year: {0: 143.8, 1: 234.7}
temp_c        0.40
hum          -0.32
windspeed     0.09
hr            0.39
casual        0.69
registered    0.97
cnt == casual + registered everywhere: True

Here is what the numbers say:

  • The target is lopsided. The mean (189.5) sits well above the median (142). Half the hours have 142 rentals or fewer, and a few busy ones reach 977.
  • Demand grew. An average hour in 2012 (yr = 1) had 234.7 rentals, against 143.8 in 2011. A model trained on 2011 will guess low for 2012.
  • Temperature helps (r=0.40r = 0.40), and humid hours are a little quieter (r=−0.32r = -0.32).
  • registered is a leak. Its rr is 0.97 because cnt is casual + registered on every row. You only know those counts after the hour ends, so drop both before modelling.

The hour of the day has r=0.39r = 0.39, which looks modest. A bar chart of the average rentals per hour tells a different story.

# script_id: day_003_explore_data/report
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
by_hour = df.groupby("hr")["cnt"].mean()
print("busiest hours:", by_hour.nlargest(3).round(0).to_dict())
print("quietest hour:", by_hour.nsmallest(1).round(0).to_dict())

fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(by_hour.index, by_hour.values)
ax.set(title="Rentals peak at 8 am and 5 pm", xlabel="Hour of day", ylabel="Average rentals per hour")
fig.tight_layout()
fig.savefig(FIG_DIR / "rentals_by_hour.png", dpi=120)
plt.close(fig)
busiest hours: {17: 461.0, 18: 426.0, 8: 359.0}
quietest hour: {4: 6.0}

Rentals peak at 8 am and 5 pm

Two commuter peaks, and a dip to about 6 rentals at 4 am. That's a strong pattern, but not a straight line, so rr undersells it, just like the 2, 6, 2 example.

Quick check

Quick check

1. A column has r = 0 with the target. What can you conclude?

2. The column `registered` has r = 0.97 with rentals. Why drop it?

3. The mean of hourly rentals is 189.5 and the median is 142. What does that tell you?

Next

You've seen temperature move with rentals; Day 4 turns that trend into a first model, a straight line.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 4 · 6 minFit Your First Model: a Straight Line← Previous: Day 2 · Set Up Python, NumPy, pandas and matplotlib
Not tapped yet