TExcelTAD
Home › Machine Learning › ML Percentile

ML Percentile

A percentile tells you the value below which a given percentage of the data falls. If your exam score is at the 90th percentile, 90 % of the students scored lower than (or equal to) you. Percentiles are a robust way to describe both the typical value and the spread of data, and they are everywhere in ML: summarising features, choosing thresholds, detecting outliers.

Computing a percentile

NumPy's percentile(data, q) takes q between 0 and 100. Here are the monthly mobile-data usages (GB) of 15 customers:

python · try it yourself
import numpy as np

usage_gb = np.array([2.1, 4.8, 3.3, 12.5, 6.0, 1.2, 7.7, 5.5,
                     3.9, 25.0, 4.4, 8.9, 2.8, 6.6, 5.1])

print("sorted:", np.sort(usage_gb))
print("50th percentile:", np.percentile(usage_gb, 50))
print("median:         ", np.median(usage_gb))
print("90th percentile:", round(np.percentile(usage_gb, 90), 2))
sorted: [ 1.2  2.1  2.8  3.3  3.9  4.4  4.8  5.1  5.5  6.   6.6  7.7  8.9 12.5
 25. ]
50th percentile: 5.1
median:          5.1
90th percentile: 11.06

The 50th percentile is exactly the median. The 90th says: 90 % of customers use at most that many gigabytes — useful when a phone company designs its plans.

When the requested position falls between two data points, NumPy interpolates linearly between them. That is why a percentile can be a value that does not appear in the data.

Quartiles and the IQR

Three percentiles are so common they have their own name, the quartiles:

Name Percentile Meaning
Q1 25th a quarter of the data is below
Q2 50th the median
Q3 75th three quarters of the data is below

The distance Q3 - Q1 is the interquartile range (IQR): the width of the middle half of the data. Unlike the standard deviation, it is not affected by extreme values.

python · try it yourself
import numpy as np

usage_gb = np.array([2.1, 4.8, 3.3, 12.5, 6.0, 1.2, 7.7, 5.5,
                     3.9, 25.0, 4.4, 8.9, 2.8, 6.6, 5.1])

q1, q2, q3 = np.percentile(usage_gb, [25, 50, 75])
iqr = q3 - q1
print(f"Q1 = {q1:.2f}, median = {q2:.2f}, Q3 = {q3:.2f}")
print(f"IQR = {iqr:.2f}")

# Tukey's rule: points beyond 1.5 * IQR from the quartiles are outliers
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"normal range: {low:.2f} .. {high:.2f}")
print("outliers:", usage_gb[(usage_gb < low) | (usage_gb > high)])
Q1 = 3.60, median = 5.10, Q3 = 7.15
IQR = 3.55
normal range: -1.73 .. 12.48
outliers: [12.5 25. ]

This "1.5 × IQR" rule is the same rule a box plot uses to draw its whiskers and dots.

Percentiles in pandas

Series.quantile() uses fractions (0–1) instead of percentages, and describe() prints the quartiles automatically:

python · try it yourself
import pandas as pd

usage = pd.Series([2.1, 4.8, 3.3, 12.5, 6.0, 1.2, 7.7, 5.5,
                   3.9, 25.0, 4.4, 8.9, 2.8, 6.6, 5.1], name="usage_gb")

print(usage.quantile([0.1, 0.25, 0.5, 0.75, 0.9]))
print()
print(usage.describe().round(2))
0.10     2.38
0.25     3.60
0.50     5.10
0.75     7.15
0.90    11.06
Name: usage_gb, dtype: float64

count    15.00
mean      6.65
std       5.82
min       1.20
25%       3.60
50%       5.10
75%       7.15
max      25.00
Name: usage_gb, dtype: float64

Ranking a single value

The opposite question — what percentile is this value? — is answered by scipy.stats.percentileofscore:

python · try it yourself
from scipy import stats

usage_gb = [2.1, 4.8, 3.3, 12.5, 6.0, 1.2, 7.7, 5.5,
            3.9, 25.0, 4.4, 8.9, 2.8, 6.6, 5.1]

for value in [3.0, 6.0, 12.5]:
    rank = stats.percentileofscore(usage_gb, value, kind="weak")
    print(f"{value:5} GB is at the {rank:.1f}th percentile")
  3.0 GB is at the 20.0th percentile
  6.0 GB is at the 66.7th percentile
 12.5 GB is at the 93.3th percentile

With kind="weak" the result is the percentage of values less than or equal to the given value.

Seeing the quartiles: box plot

A box plot draws Q1, the median and Q3 as a box, with whiskers reaching to the furthest non-outlier points:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

usage_gb = np.array([2.1, 4.8, 3.3, 12.5, 6.0, 1.2, 7.7, 5.5,
                     3.9, 25.0, 4.4, 8.9, 2.8, 6.6, 5.1])

plt.figure(figsize=(6, 2.5))
plt.boxplot(usage_gb, vert=False)
plt.xlabel("Monthly data usage (GB)")
plt.title("Box plot of mobile-data usage")
plt.tight_layout()
plt.show()
print("Box plot drawn: the two circles on the right are the outliers 12.5 and 25 GB")
Box plot drawn: the two circles on the right are the outliers 12.5 and 25 GB

Tip: In ML, percentiles are useful for clipping features: replacing everything above the 99th percentile by the 99th percentile value tames extreme outliers without dropping rows.

Test yourself

Which percentile is the same as the median?

  1. 25th
  2. 50th
  3. 75th
  4. 100th

What does the interquartile range (IQR) measure?

  1. The difference between the max and min
  2. The width of the middle 50 % of the data
  3. The average distance from the mean
  4. The number of outliers

In pandas, how do you ask for the 90th percentile of a Series s?

  1. s.percentile(90)
  2. s.quantile(0.9)
  3. s.quantile(90)
  4. s.describe(90)