Byte by Byte › Book 8: Real-World Coding, Data and AI › Chapter 8: Statistics for Data and AI
Chapter 8: Statistics for Data and AI
🔎 The Case
The village council asks a simple question: "How high does the river usually get, and how worried should we be?" Glim answers, "The average is fine, so relax." Vega disagrees: "An average hides the dangerous days." Both are using numbers. Only one is using statistics properly. Statistics is the maths of summarising data and reasoning about uncertainty, and it is the foundation of machine learning.
💡 The Concepts
Measures of central tendency (the "middle"):
- Mean: sum of values ÷ number of values. Sensitive to extreme values.
- Median: the middle value when sorted (the mean of the two middle values if the count is even). Not pulled by extremes.
- Mode: the most frequent value. Useful for categories (most common location).
Example: levels 2, 2, 3, 3, 3, 4, 12. Mean = 29 ÷ 7 ≈ 4.14; median = 3; mode = 3. The single 12 drags the mean up. When data has extreme values, the median describes the typical case better. (This is why salaries are reported as medians.)
Measures of spread (how scattered values are):
- Range: maximum − minimum.
- Variance: the average of the squared distances from the mean.
- Standard deviation (SD): the square root of the variance, in the same units as the data. Small SD: values cluster near the mean. Large SD: widely spread.
σ = √( Σ (x − x̄)² ÷ n )
Pandas' std() divides by n − 1 (the sample SD), which is slightly larger; both are correct for different purposes.
Percentiles and quartiles. The 90th percentile is the value below which 90% of the data falls. Quartiles split sorted data into four parts (Q1 = 25th, Q2 = median, Q3 = 75th percentile). The interquartile range (IQR) = Q3 − Q1. A common rule flags outliers as values more than 1.5 × IQR beyond Q1 or Q3.
Probability. The chance of an event, from 0 (impossible) to 1 (certain).
- Theoretical: P(event) = favourable outcomes ÷ total outcomes. P(rolling a 6) = 1/6.
- Experimental: from data. If the river passed 3 m on 18 of the last 120 days, P(above 3 m) ≈ 18 ÷ 120 = 0.15.
- P(not A) = 1 − P(A). For independent events, P(A and B) = P(A) × P(B).
AI models output probabilities, not certainties: "82% likely to flood" means the model expects floods on about 82 of 100 days that look like this one.
Correlation. Measures how strongly two variables move together, from −1 (perfect opposite) through 0 (no straight-line link) to +1 (perfect together). Correlation is not causation. Ice-cream sales and drowning both rise in summer; ice cream does not cause drowning. A third factor (hot weather) drives both.
🛠️ Build It
import pandas as pd
df = pd.read_csv("river_clean.csv")
lev = df["level_m"]
print("Mean:", round(lev.mean(), 2))
print("Median:", lev.median())
print("Mode:", lev.mode().tolist())
print("Range:", lev.max() - lev.min())
print("SD:", round(lev.std(), 2))
print(lev.describe())
print("P(level >= 3 m):", (lev >= 3).mean())
print("Correlation rain-level:", round(df["rain_mm"].corr(df["level_m"]), 2))
print(df.groupby("location")["level_m"].agg(["mean", "max", "count"]))
describe() gives count, mean, SD, min, quartiles and max in one go. groupby summarises each location separately.
Now work out, by hand, the mean, median, mode and range of the levels 2.1, 2.4, 2.8, 3.1, 3.3 and check them against Python.
✅ Case Closed
Memoon presents three numbers to the council, not one: the median level (the typical day), the 90th percentile (a bad day) and the probability of crossing the danger mark. Rain and level have a strong positive correlation, and here the causation is real and physical: rain fills the river. But she adds, "The correlation alone doesn't prove that. The physics does."
Think About It: A news headline says "Students who eat breakfast score higher." Does breakfast cause higher scores? What other factors might explain it?
❓ Test Yourself
- Find the mean, median, mode and range of: 4, 8, 6, 5, 3, 8, 9.
- When is the median a better summary than the mean?
- Two classes both average 70. Class A has SD 3; Class B has SD 15. Describe each class.
- A bag has 3 red and 5 blue marbles. What is P(red)? P(not red)?
- Give your own example of a correlation that is not causation.
- Challenge: Write a Python function
my_median(values)without using any library: sort the list and handle both odd and even lengths.
📚 Key Terms
statistics · mean · median · mode · range · variance · standard deviation · percentile · quartile · interquartile range · outlier · describe · groupby · probability · theoretical probability · experimental probability · independent events · correlation · causation
Keep learning with Byte by Byte
Explore Book 8: Real-World Coding, Data and AI. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment