Describing Data: Statistics and Plots for Spread, Shape and Imbalance
Summarise a dataset with the mean, median, quartiles and skew, flag outliers with the 1.5 × IQR rule that box plots use, draw histograms, box plots and scatter plots with Matplotlib and seaborn, read Pearson and Spearman correlations within their limits, and measure class imbalance.
Contentsand lesson path
On this page
- Why it matters
- Centre, spread and skew
- Quartiles, box plots and the 1.5 × IQR rule
- Histograms and scatter plots in Matplotlib and seaborn
- Correlation: Pearson, Spearman and their limits
- Class imbalance
- Check your understanding
- Apply it
- Review prompt
Lessons of Probability & Statistics for ML
- Describing Data: Statistics and Plots for Spread, Shape and Imbalance Concept · 25 min
- Conditional Probability and the Base-Rate Trap Concept · 20 min
- Likelihood: Where Loss Functions Come From Concept · 25 min
- Lab: Bootstrap a Confidence Interval for a Model Metric Lab · 30 min
- Worked Example: Is Model B Really Better Than Model A? Worked example · 20 min
- Check: Reasoning Under Uncertainty Knowledge check · 8 questions
What you will learn
- Describe a dataset with summary statistics, correlations and exploratory plots (histograms, box plots, scatter plots) in Matplotlib or seaborn, and identify skew, outliers and class imbalance.
01. Why it matters
Before you train a model, look at the data. Three facts decide many later choices. Is a column skewed, with a long tail on one side? Does it have outliers, values far from the rest? And is the label imbalanced, with one class much rarer than the other? A skewed target pulls a squared-error model towards its tail; an outlier may be a typo or your best customer. A rare class makes accuracy look excellent for a model that learned nothing.
This lesson answers them with a few summary numbers and three kinds of plot, on 5,000 synthetic grocery orders: basket value, delivery distance, delivery time and a flag for a returned item. A fixed seed makes your numbers match.
The examples were tested with Python 3.12, NumPy 2.5, pandas 3.1, SciPy 1.18, scikit-learn 1.9, Matplotlib 3.11 and seaborn 0.13. Install them with python -m pip install numpy pandas scipy scikit-learn matplotlib seaborn and run every script from one folder: the first writes orders.csv for the others.
02. Centre, spread and skew
The mean is the sum of the values divided by their count. The median is the middle value after sorting: half the values lie below it and half above. The standard deviation measures how far values typically sit from the mean; it is the square root of the variance, the average squared distance from the mean. Skewness is a number for lopsidedness: about 0 for a symmetric shape, positive when the long tail points to the right (towards large values) and negative when it points to the left.
The script creates the dataset and prints these numbers for two columns. Basket values follow a log-normal distribution, common for money and durations: most orders are modest and a few are very large.
"""Write orders.csv: 5,000 seeded grocery orders, then summarise two columns."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
n = 5_000
basket = rng.lognormal(mean=3.4, sigma=0.6, size=n) # pounds, long right tail
distance = rng.gamma(shape=4.0, scale=1.5, size=n) # km from the store
minutes = 18 + 3.0 * distance + rng.normal(0, 6, size=n)
returned = rng.random(n) < 0.04 # about 4% of orders have an item sent back
orders = pd.DataFrame({
"basket_value": basket.round(2),
"distance_km": distance.round(2),
"delivery_minutes": minutes.round(1),
"returned": returned.astype(int),
})
orders.to_csv("orders.csv", index=False)
for col in ["basket_value", "delivery_minutes"]:
x = orders[col]
print(f"{col:<17} mean {x.mean():6.1f} median {x.median():6.1f} "
f"std {x.std():5.1f} skew {x.skew():5.2f}")basket_value mean 35.4 median 29.4 std 23.3 skew 2.28
delivery_minutes mean 36.1 median 35.2 std 10.7 skew 0.53For basket_value the mean (£35.4) is £6 above the median (£29.4), and the skew is 2.28. A few £200 baskets pull the mean upwards; the median only depends on the middle position, so it hardly moves. A mean clearly above the median is the quickest sign of a right skew. A mean clearly below the median signals a left skew, for example exam marks where most students score high and a few score very low. delivery_minutes is close to symmetric: mean and median differ by under a minute.
The median describes a typical order; the mean is what you need for totals, because revenue is the mean times the number of orders. For modelling, a model trained with squared error pays most attention to large errors, and large errors live in the tail. Taking the logarithm of a right-skewed column often makes it close to symmetric, as the next section shows.
03. Quartiles, box plots and the 1.5 × IQR rule
A percentile is the value below which a given share of the data lies. The 25th percentile is the first quartile (Q1), the 50th is the median and the 75th is the third quartile (Q3). The interquartile range (IQR) is Q3 − Q1: the width of the middle half of the data. Unlike the standard deviation, it ignores a few huge values.
A box plot draws a box from Q1 to Q3 with a line at the median. Matplotlib and seaborn use the rule of John Tukey: the fences sit 1.5 × IQR below Q1 and 1.5 × IQR above Q3. Each whisker stops at the furthest data point that is still inside its fence, and every point beyond a fence is drawn on its own as a possible outlier (a flier). The rule uses quartiles, not standard deviations, and how many points it flags depends on the shape of the data, not on a fixed percentage.
"""Apply the 1.5 x IQR rule that box plots use, then draw the box plot."""
import matplotlib
matplotlib.use("Agg") # write image files; no window needed
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
orders = pd.read_csv("orders.csv")
def iqr_report(x, label):
q1, q3 = np.percentile(x, [25, 75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
beyond = (x < low) | (x > high)
whisker_top = x[x <= high].max() # furthest point still inside the fence
print(f"{label:<11} Q1 {q1:5.2f} Q3 {q3:5.2f} IQR {iqr:5.2f} "
f"fence {high:5.2f} whisker {whisker_top:5.2f} beyond {beyond.sum()}")
iqr_report(orders["basket_value"], "pounds")
iqr_report(np.log(orders["basket_value"]), "log(pounds)")
fig, ax = plt.subplots(figsize=(6, 2.5))
sns.boxplot(x=orders["basket_value"], whis=1.5, ax=ax) # 1.5 is also the default
ax.set_xlabel("basket value (£)")
fig.tight_layout()
fig.savefig("box_basket.png", dpi=120)
print("saved box_basket.png")pounds Q1 19.74 Q3 44.57 IQR 24.83 fence 81.82 whisker 81.78 beyond 232
log(pounds) Q1 2.98 Q3 3.80 IQR 0.81 fence 5.02 whisker 5.01 beyond 25
saved box_basket.pngOn the pound scale 232 orders (4.6%) lie beyond the upper fence of £81.82; the lower fence is negative, so no small orders are flagged. After a log transform only 25 points, on both sides, fall outside the fences. Most of the 232 were simply the long tail of a skewed distribution, not strange values.
So treat a point beyond the whisker as a candidate to investigate, not as an error to delete. Check whether it is impossible (a negative age, or 9,999 minutes used as a code for missing data) or merely rare. Rare but genuine values, such as bulk orders or fraud, often carry the signal you want.
04. Histograms and scatter plots in Matplotlib and seaborn
A histogram splits the range of a column into equal-width bins and draws a bar for the number of values in each bin. It shows what a summary hides: the shape of the tail, two humps that suggest two mixed groups, or a spike at a suspicious value such as 0. A scatter plot draws one point per row for two numeric columns, so you can see whether they rise together.
The script below saves three plots as PNG files. It selects Matplotlib's Agg backend, which writes image files and needs no window, so it also works on a server. seaborn draws on Matplotlib axes, so the two libraries mix freely. The printed numbers are the ones the histogram shows.
"""Histogram and scatter plot of the orders, saved as PNG files."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
orders = pd.read_csv("orders.csv")
basket = orders["basket_value"]
# 1. Histogram with the mean and the median marked
counts, edges = np.histogram(basket, bins=40)
top = counts.argmax()
print(f"tallest bin: £{edges[top]:.0f} to £{edges[top + 1]:.0f}, {counts[top]} orders")
print(f"orders above the mean: {(basket > basket.mean()).mean():.1%}")
fig, ax = plt.subplots(figsize=(6, 3.5))
sns.histplot(basket, bins=40, ax=ax)
ax.axvline(basket.mean(), color="black", linestyle="--", label="mean")
ax.axvline(basket.median(), color="black", label="median")
ax.set_xlabel("basket value (£)")
ax.legend()
fig.tight_layout()
fig.savefig("hist_basket.png", dpi=120)
# 2. The same data on a log scale: the long tail becomes a near-symmetric hump
fig, ax = plt.subplots(figsize=(6, 3.5))
sns.histplot(basket, bins=40, log_scale=True, ax=ax)
fig.tight_layout()
fig.savefig("hist_basket_log.png", dpi=120)
# 3. Scatter plot of two numeric columns, coloured by the rare class
fig, ax = plt.subplots(figsize=(6, 4))
sns.scatterplot(data=orders, x="distance_km", y="delivery_minutes",
hue="returned", alpha=0.4, s=12, ax=ax)
fig.tight_layout()
fig.savefig("scatter_delivery.png", dpi=120)
print("saved hist_basket.png, hist_basket_log.png, scatter_delivery.png")tallest bin: £20 to £29, 1076 orders
orders above the mean: 38.0%
saved hist_basket.png, hist_basket_log.png, scatter_delivery.pngOpen hist_basket.png. The tallest bar covers £20 to £29 with 1,076 orders, and the dashed mean line sits to the right of the median. Only 38% of orders are above the mean, another sign of right skew; in a symmetric distribution about half would be. The log-scale histogram turns the long tail into a near-symmetric hump. In scatter_delivery.png the points rise along a band, and alpha=0.4 turns overlapping points into darker areas instead of a solid blob. The returned orders, coloured by hue, are thinly scattered: a first look at how rare that class is.
The number of bins changes what you see: too few hide a second hump, too many make noise look like structure. Try 10 and 200 bins before you trust a shape.
05. Correlation: Pearson, Spearman and their limits
Correlation summarises how two columns move together with one number between −1 and +1. Pearson's r measures linear association: how well a straight line fits the scatter plot. Spearman's ρ (rho) replaces every value by its rank (1 for the smallest, 2 for the next, and so on) and then computes Pearson's r on the ranks. It therefore measures monotonic association: whether one column tends to rise when the other rises, along any curve.
"""Pearson and Spearman correlation on four shapes of relationship."""
import numpy as np
import pandas as pd
from scipy import stats
rng = np.random.default_rng(3)
orders = pd.read_csv("orders.csv")
x = rng.uniform(-3, 3, size=500)
noise = rng.normal(0, 0.5, size=500)
few_x = rng.normal(0, 1, size=30)
few_y = rng.normal(0, 1, size=30)
pairs = {
"linear (distance)": (orders["distance_km"], orders["delivery_minutes"]),
"curved, monotonic": (x, np.exp(x) + noise),
"U shape": (x, x**2 + noise),
"no link + 1 outlier": (np.append(few_x, 12.0), np.append(few_y, 12.0)),
}
print(f"{'relationship':<20} {'pearson':>8} {'spearman':>9}")
for name, (a, b) in pairs.items():
r = stats.pearsonr(a, b).statistic
rho = stats.spearmanr(a, b).statistic
print(f"{name:<20} {r:8.2f} {rho:9.2f}")relationship pearson spearman
linear (distance) 0.83 0.80
curved, monotonic 0.81 0.91
U shape -0.07 -0.04
no link + 1 outlier 0.85 0.18Row by row:
- Linear: both are high, since a straight line is also monotonic.
- Curved but monotonic: Spearman (0.91) beats Pearson (0.81), because the relationship always rises but not along a line.
- U shape: both are near zero, although y depends completely on x: the falling and rising halves cancel out, and a U is not monotonic.
- One outlier: 30 unrelated points plus one extreme point give Pearson 0.85. Spearman only sees that the point has the top rank and stays at 0.18.
So a correlation near zero does not mean the columns are unrelated, only that there is no linear (Pearson) or monotonic (Spearman) trend: look at the scatter plot before dropping a feature. A high correlation can come from a single point. And correlation says nothing about cause, since a third factor can drive two columns at once.
06. Class imbalance
A label is imbalanced when one class is much rarer than the other, as with fraud, churn or returns. Count the classes first, because imbalance changes how you split, train and evaluate.
"""Measure class imbalance and what it does to accuracy and to small splits."""
import pandas as pd
from sklearn.model_selection import train_test_split
orders = pd.read_csv("orders.csv")
y = orders["returned"]
print(y.value_counts().sort_index().to_string())
print(f"share returned: {y.mean():.1%}")
print(f"accuracy of always predicting 0: {(y == 0).mean():.1%}")
for strat in [None, y]:
counts = []
for seed in range(20): # 20 different 200-row test splits
_, test = train_test_split(orders, test_size=200, random_state=seed,
stratify=strat)
counts.append(int(test["returned"].sum()))
label = "random" if strat is None else "stratified"
print(f"{label:<10} returns per 200-row test set: {min(counts)} to {max(counts)}")returned
0 4803
1 197
share returned: 3.9%
accuracy of always predicting 0: 96.1%
random returns per 200-row test set: 1 to 11
stratified returns per 200-row test set: 8 to 8Only 197 of 5,000 orders (3.9%) were returned, so a "model" that always predicts not returned scores 96.1% accuracy and finds no returns at all. Report precision and recall for the rare class instead; the next lesson defines both.
Imbalance also makes small samples unstable. Across 20 random 200-row test sets the number of returns ranged from 1 to 11, so a rare-class metric would rest on a handful of rows and swing from split to split. Passing stratify=y to train_test_split keeps the class shares the same in every split: always 8 returns here. Even then, 8 positives is very few; lesson 4 measures that uncertainty with a bootstrap confidence interval.
07. Check your understanding
08. Apply it
The practice task for this skill compares two classifiers on one test set. Start by describing that test set, because its shape decides how far you can trust a metric computed on it:
- Count the rows of each class in the test set. Few positives mean wide intervals later.
- For each model, draw a histogram of its predicted probabilities, split by true class with
hue. Well-separated humps mean the model separates the classes well; overlap means many borderline rows. - Draw a scatter plot of model A's probability against model B's for the same rows, and compute Pearson and Spearman between them. Note whether the models mostly agree; lesson 5 shows why that matters.
09. Review prompt
Without looking back:
- How do the mean and the median react to a long right tail, and which would you report for a typical value?
- How are box-plot fences and whiskers computed, and why does a skewed column show many points beyond them?
- What does Spearman measure that Pearson does not, and which shape defeats both?
- Why is accuracy misleading for a rare class, and what does
stratifychange in a train/test split?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.