Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Descriptive statistics and visualization

P1.D1240 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Before a model sees a data set, you look at it with a few summary numbers and plots, and many training and reporting choices (scaling, loss, which number to report) depend on what they show.

  • Exploring a data set before training: counts, means, quartiles and histograms reveal typos, outliers, skew and class imbalance (pandas and plotting are taught in P2.4 and P2.5). (P2.5: Data wrangling with Pandas, coming soon)
  • Feature scaling: subtracting a mean and dividing by a standard deviation, or using a median and an IQR when outliers are present, before fitting models such as linear regression and k-nearest neighbors. (P3.A11: Features, scaling and data leakage, coming soon)
  • Mean squared error follows the mean and is dragged by outliers, while mean absolute error follows a median (P1.D4); the choice of loss decides how much an outlier counts. (P3.A2: Linear regression, coming soon)
  • Class imbalance is read from counts and proportions, and shows why accuracy can mislead. (P3.A10: Calibration and class imbalance, coming soon)
  • Normalization layers subtract a mean and divide by a standard deviation inside a network, which is standardizing applied to activations. (P4.19: Normalization layers, coming soon)
  • Experiment tracking and drift monitoring log medians, percentiles and spreads of metrics, such as accuracy across random seeds. (P12.3: Experiment tracking and reproducibility, coming soon)

Before this: Random variables, Expectation and variance, Covariance and the multivariate Gaussian

After this lesson you can

  • Choose a summary that fits the kind of data (numerical or categorical), and compute the mean, median, mode, a weighted mean and a trimmed mean, saying how each reacts to an outlier and to skew
  • Compute the range, the sample standard deviation (with n−1n-1), the IQR and the median absolute deviation, and say which of them an outlier can wreck
  • Find percentiles by linear interpolation (the NumPy default), say that other conventions give other answers for small data, and build a five-number summary and a box plot with Tukey's 1.5×IQR1.5\times\text{IQR} whiskers
  • Standardize, min–max scale and robust-scale a feature, flag outliers by the zz-score and IQR rules (and know when the first one cannot fire), and pick a plot that does not hide the shape of the data

Ten people work at a small company (all the numbers here are made up). Nine of them earn between 4040 and 6060 thousand a year. The boss earns 10001000. The “average salary” is 145145 thousand, a number that no employee is near. The “middle salary”, the value halfway between the fifth and sixth of the ten sorted salaries, is 5151 thousand, which describes the typical employee well. Both numbers are correct. They answer different questions, and a data set can make one of them useless.

This lesson is about descriptive statistics: summarizing a data set with a few numbers and a few pictures, before you model it. P1.D2 and P1.D4 defined the mean, the variance and the quantiles of a distribution, a model of how values are produced. Here we have a data set, a list of nn numbers x1,…,xnx_1,\dots,x_n that were collected. The formulas are the same ideas with the data playing the role of the distribution: treat the data as a distribution that gives each value probability 1n\frac1n, and E[X]\mathbb{E}[X] becomes the sample mean. Everything in this lesson is computed from the data you have. Each number estimates the matching quantity of the population the data came from, without being equal to it (P1.D10 and P1.D13 return to that).

What kind of data is it?

The summary you can use depends on what the numbers mean.

  • Numerical, continuous: a measurement that can take any value in a range, such as a height or a waiting time. Means, medians, spreads and percentiles all make sense.
  • Numerical, discrete: a count, such as the number of children or the number of clicks. The same summaries make sense, though the mean of a count can be a fraction no one has (2.42.4 children).
  • Categorical, ordinal: categories with a natural order, such as “poor, fair, good, excellent”. A median or a percentile makes sense (the middle category). An average of the codes 1,2,3,41,2,3,4 assumes equal gaps between categories, which is a strong assumption.
  • Categorical, nominal: categories without an order, such as “cat, dog, bird” or a country. Only counts, proportions and the mode (the most common category) make sense.

A trap for beginners: a number is not always a numerical variable. A class label coded 0,…,90,\dots,9 (digits) or a postal code is nominal, and the mean of postal codes means nothing.

Measures of centre

Take seven values: 2,3,3,5,7,8,302,3,3,5,7,8,30.

  • The mean is the sum divided by nn: xˉ=1n∑ixi=587=8.29\bar x=\frac1n\sum_i x_i=\frac{58}{7}=8.29.
  • The median is the middle value of the sorted data (for even nn, the average of the two middle values). Here it is the fourth of seven, 55.
  • The mode is the most frequent value, 33 (it appears twice).

The mean, 8.298.29, lies above all but one of the values. One value, 3030, pulled it up. The median ignored how large 3030 is: replace 3030 by 30003000 and the median is still 55, while the mean becomes 432432. This is the main fact of the section.

The link to P1.D4 is a link to a loss. A guess cc for the whole data set costs 1n∑(xi−c)2\frac1n\sum(x_i-c)^2 in squared error, and the mean is the cc that makes it smallest. In absolute error, 1n∑∣xi−c∣\frac1n\sum|x_i-c|, a median is the best cc. For the data 1,2,101,2,10 the mean is 4.334.33 and the median is 22: the squared error is 16.216.2 at the mean and 21.721.7 at the median, and the absolute error is 3.783.78 at the mean and 33 at the median. For the seven values above, the mean gives 82.882.8 and the median gives 93.693.6 in squared error, while the absolute errors are 6.206.20 and 5.295.29.

The mode, and data with two humps

The mode is the only centre for nominal data. For numerical data it needs care. In a continuous measurement no two values are exactly equal, so you must group them into bins first (the histogram below) and call the fullest bin the mode, and a different bin width can change the answer. A data set can also have two peaks (bimodal) or more (multimodal). Then any single centre misleads: in the widget below, the “Two groups” data have both the mean and the median in the empty gap between the groups.

Weighted and trimmed means

A weighted mean gives values different importance, xˉw=∑wixi∑wi\bar x_w=\frac{\sum w_ix_i}{\sum w_i}. A course grade with the exam at weight 0.60.6 and the homework at weight 0.40.4 gives 0.6×80+0.4×90=840.6\times80+0.4\times90=84 for marks 8080 and 9090. It is also how to combine groups: a group of 3030 people with mean 7070 and a group of 1010 with mean 9090 have overall mean 30×70+10×9040=75\frac{30\times70+10\times90}{40}=75, not the 8080 you get by averaging 7070 and 9090.

A trimmed mean drops a fixed share of the lowest and of the highest values before averaging. Dropping the lowest and the highest of the seven values leaves 3,3,5,7,83,3,5,7,8 with mean 5.25.2. It sits between the mean and the median, and with more trimming it becomes the median.

Skew

A distribution is right-skewed if it has a long tail to the right, as incomes do (P1.D4 mentioned them), and left-skewed for a long left tail. In right-skewed data the mean is usually above the median, because the tail drags the mean and not the median. That is a tendency, and a rule with exceptions: the seven values 0,0,0,3,3,3,100,0,0,3,3,3,10 have a long right tail (skewness 1.321.32 by the usual moment formula) and yet mean 2.712.71 below median 33. So treat “mean above median” as a hint of right skew, not as a definition.

Measures of spread

Two data sets can have the same centre and be very different in how widely they scatter.

  • The range is the maximum minus the minimum, 30−2=2830-2=28. It uses only the two extreme values.
  • The sample variance is s2=1n−1∑i(xi−xˉ)2s^2=\frac1{n-1}\sum_i(x_i-\bar x)^2 and the standard deviation is s=s2s=\sqrt{s^2}, in the units of the data. P1.D4 explained why a sample divides by n−1n-1 rather than nn (the data are measured from their own mean, which makes the squared distances too small on average). Here s=9.83s=9.83, while dividing by nn gives 9.109.10. Libraries differ: NumPy’s np.std and np.var divide by nn unless you pass ddof=1, pandas divides by n−1n-1, and PyTorch’s torch.std by default divides by n−1n-1. np.cov divides by n−1n-1, as in the sample covariance of P1.D7.
  • The mean absolute deviation is 1n∑∣xi−xˉ∣\frac1n\sum|x_i-\bar x|, here 6.206.20. It is the absolute-error cousin of the standard deviation (the standard deviation of the same data is at least as large). Take care with the names: the next measure has a similar name.
  • The IQR (interquartile range) is the 75th percentile minus the 25th, Q3−Q1Q_3-Q_1. It is the width of the middle half of the data: here 7.5−3=4.57.5-3=4.5.
  • The MAD, the median absolute deviation, is the median of ∣xi−x~∣|x_i-\tilde x| where x~\tilde x is the median. Here the distances to the median 55 are 3,2,2,0,2,3,253,2,2,0,2,3,25, and their median is 22.

Remove the 3030 and the standard deviation falls from 9.839.83 to 2.422.42 and the range from 2828 to 66, while the IQR falls only from 4.54.5 to 3.53.5 and the MAD from 22 to 1.51.5. The standard deviation squares the distances, so one far value dominates it. The IQR and the MAD count only the middle of the order, so they are robust: an outlier hardly changes them.

How many bad values can a statistic take?

A statistic’s breakdown point is, informally, the share of the data you can replace by arbitrarily bad values before the statistic can be pushed anywhere. For the mean it is about 00: a single value can move it as far as you like. The same holds for the standard deviation and the range. For the median it is about one half: for the seven values above, replacing the three largest by 1,000,0001{,}000{,}000 leaves the median at 55, and other choices of three keep it within the range of the original data (replacing 2,3,32,3,3 gives 3030). Replacing four can move it anywhere (to 1,000,0001{,}000{,}000, for example). The IQR tolerates about a quarter, and the MAD about a half.

Go deeper Putting the MAD on the scale of the standard deviation

The MAD is on a different scale from the standard deviation. For a Gaussian distribution the MAD is 0.6745 σ0.6745\,\sigma (the 75th percentile of the standard Gaussian), so multiplying the MAD by 1.48261.4826 gives an estimate of σ\sigma that tolerates outliers. Libraries call this the “normal-consistent” MAD (for example, the function median_abs_deviation in SciPy with the option scale="normal"). For the seven values it would be 2×1.4826=2.972\times1.4826=2.97, far below s=9.83s=9.83. Likewise the IQR of a Gaussian is 1.349 σ1.349\,\sigma.

That correction is right for Gaussian data. For other shapes the factor is different, so use the raw MAD unless you know the data are roughly Gaussian.

Percentiles and quantiles

The pp-th percentile of a data set is a value with about p%p\% of the data at or below it. The quantile with fraction q=p/100q=p/100 is the same thing on a scale from 00 to 11. The median is the 50th percentile, and the quartiles Q1Q_1 and Q3Q_3 are the 25th and 75th. P1.D2 defined the quantile of a distribution as the inverse of the CDF. For data the “CDF” is a staircase that jumps by 1n\frac1n at each value, and a staircase has no exact inverse. That is why conventions differ, as P1.D2 warned.

NumPy’s default, called linear interpolation, works like this. Sort the data. The qq-quantile sits at the position h=(n−1)qh=(n-1)q, counting from 00. If hh falls between two sorted values, blend them in proportion. For 1,2,3,41,2,3,4 and q=0.25q=0.25: h=3×0.25=0.75h=3\times0.25=0.75, which is three quarters of the way from 11 to 22, so Q1=1.75Q_1=1.75.

Other conventions give other answers for the same four numbers:

  • The convention of P1.D2 (the smallest data value with at least a quarter of the data at or below it): 11. NumPy calls it inverted_cdf.
  • The position (n+1)q(n+1)q with interpolation (weibull in NumPy, and the default of Python’s statistics.quantiles): 1.251.25.
  • The median of the lower half: 1.51.5.
  • NumPy’s default: 1.751.75.

They come closer together when the data set is large, and they differ by at most one gap between neighbouring values. For a small data set the difference can be visible, so state the convention when it matters, and expect that different tools may use different defaults. This lesson and its widget use NumPy’s default.

For the seven values, Q1=3Q_1=3, the median is 55 and Q3=7.5Q_3=7.5 (positions 1.51.5, 33 and 4.54.5). A system that must answer within a time limit is judged by a high percentile of its response times, as in the last section.

The five-number summary and the box plot

The five-number summary is the minimum, Q1Q_1, the median, Q3Q_3 and the maximum: for the seven values, 2,  3,  5,  7.5,  302,\;3,\;5,\;7.5,\;30. A box plot draws it:

  • a box from Q1Q_1 to Q3Q_3, with a line at the median, so the box holds the middle half of the data;
  • whiskers that extend from the box to the farthest data value that is within 1.5×IQR1.5\times\text{IQR} of the box (Tukey’s convention; John Tukey popularized the box plot in his book Exploratory Data Analysis, 1977);
  • each value beyond the whiskers drawn as its own point, an outlier by this rule.

For the seven values, IQR=4.5\text{IQR}=4.5, so the fences are 3−6.75=−3.753-6.75=-3.75 and 7.5+6.75=14.257.5+6.75=14.25. The value 88 is the farthest inside, so the upper whisker stops at 88, and 3030 is drawn alone. The lower whisker stops at the minimum, 22.

The number 1.51.5 is a convention, not a law of nature. For a Gaussian distribution the quartiles are at ±0.6745σ\pm0.6745\sigma, the IQR is 1.349σ1.349\sigma, and the fences are at ±2.698σ\pm2.698\sigma. About 0.7%0.7\% of a large Gaussian sample therefore lies beyond them, so a few points beyond the whiskers are normal in a big sample and do not prove that something is wrong. Heavy-tailed data show many more.

Try it: add outliers and watch the mean and the median

Here is the idea of this lesson as a picture. Each value is a dot, with the mean (solid blue line) and the median (dashed pink line) marked, and a box plot below. Press Add an outlier and compare how far each of the two moves.

Add outliers: mean versus median

Data set (all numbers are made up)

Start: 20 values, quiz scores out of 100 (made up). The mean is 55.2 and the median is 54.5. Drag a point, or add an outlier, and watch which of the two moves.
050100scoremean 55.2median 54.5

mean median value beyond the whiskers

Box: the middle half of the values (Q1 to Q3), with the median as its bar and the mean as a diamond. Whiskers reach the farthest value within 1.5 × IQR of the box.

Selected point: value 73 (number 20 of 20 from the left)

n = 20 mean − median = 0.7 mean = 55.2 (start 55.2) median = 54.5 (start 54.5) sd (n − 1) = 9.48 (start 9.48) IQR = 12 (start 12) MAD = 6.5 (start 6.5) Q1, Q3 = 49.5, 61.5 min, max = 38, 73 beyond the whiskers = 0

Data: quiz scores out of 100 (made up). Quartiles use linear interpolation, the default of NumPy's np.percentile. sd divides by n − 1. MAD is the median of the distances to the median, not rescaled. You can drag a dot, or focus it and use the arrow keys (Page Up and Page Down move by 10, Delete removes it). At most 30 points.

Add outliers: mean versus median. Pick one of four made-up data sets with 20 values: symmetric, right-skewed, two groups, or one typo (an age typed as 120). The dots are the values, stacked where they would overlap. The solid blue line is the mean and the dashed pink line is the median. Below is a box plot: the box runs from the first to the third quartile with the median as its bar and the mean as a diamond, the whiskers reach the farthest value within 1.5 times the IQR of the box, and points beyond are hollow red rings. Add an outlier at the high end, drag a dot or move the selected one with the buttons or the arrow keys, remove a point, or reset. The readouts show the mean, median, sample standard deviation, IQR and MAD, each next to its value at the start. Quartiles use linear interpolation like NumPy’s default.

Things to try.

  1. Symmetric data, one outlier. Press Add an outlier once. The mean moves from 55.255.2 to 57.157.1 and the median from 54.554.5 to 5555, while the standard deviation jumps from 9.59.5 to 12.712.7. Press it again: the mean goes on to 58.858.8 and the median to 55.555.5. The IQR goes 12→13→14.2512\to13\to14.25 and the MAD 6.5→7→7.56.5\to7\to7.5, and the standard deviation goes 9.5→12.7→14.89.5\to12.7\to14.8, so the IQR and the MAD change much less.
  2. Right-skewed incomes. The mean starts at 52.1552.15, well above the median 4141. Add an outlier and the gap grows (63.263.2 against 4242), since the far point pulls the mean.
  3. Two groups. The mean is 40.140.1 and the median 38.538.5, both in the empty gap between the groups, a value that nobody in the data has. No single number describes these data well. Then drag the dot at 5252 down to 3030: the median jumps to 27.527.5, because the order in the middle changed.
  4. The typo. The age 120120 pulls the mean to 40.4540.45 and the standard deviation to 22.022.0. The dot is already selected: press −10 ten times to bring it to 2020, the age that was probably meant. The mean falls to 35.4535.45 and the standard deviation to 12.012.0. A typo you can fix is the easy case of an outlier.
  5. Move a point a long way. In the symmetric data drag the highest dot (7373) down to 3030. It moved 4343, the mean falls by 2.152.15 (to 53.0553.05), and the median falls by 11 (to 53.553.5), because the median depends on the order and the values next to the middle.

z-scores, standardizing and outlier rules

The zz-score of a value says how many standard deviations it is from the mean: zi=xi−xˉsz_i=\dfrac{x_i-\bar x}{s}. It is the standardizing of P1.D4, applied to data. Standardizing a whole feature gives it mean 00 and sample standard deviation 11. For the seven values the zz-scores are −0.64-0.64, −0.54-0.54, −0.54-0.54, −0.33-0.33, −0.13-0.13, −0.03-0.03 and 2.212.21.

Two rules for flagging an outlier are common:

  • The zz rule: flag ∣z∣>3|z|\gt3. For a Gaussian distribution only 0.27%0.27\% of values are beyond 33.
  • The IQR rule: flag values beyond the box-plot fences, Q1−1.5 IQRQ_1-1.5\,\text{IQR} and Q3+1.5 IQRQ_3+1.5\,\text{IQR}.

They do not agree. The zz rule is built from the two statistics that an outlier damages most: the outlier raises ss and shifts xˉ\bar x, which shrinks its own zz. This is called masking. In fact, with n−1n-1 in ss, no ∣z∣|z| can exceed n−1n\frac{n-1}{\sqrt n}. For the seven values that bound is 2.272.27 (the outlier 3030 reached 2.212.21), and for n=10n=10 it is 2.852.85, so in a sample of ten or fewer values the rule ∣z∣>3|z|\gt3 cannot fire, however absurd the value. For n=11n=11 the bound is 3.023.02. Nine values near 5050 and one typed as 10001000 give that value a zz of 2.8462.846, but the IQR rule flags it at once (second code cell). So the IQR rule, built from quartiles, is the safer one for small samples, and the zz rule is fine for large samples with only a few bad values.

An outlier is a fact about the data, not a verdict. Ask what produced it.

  • A typo or a broken sensor (an age of 120120, or a temperature of −999-999 used as a missing code): fix it, or mark it missing.
  • A real but rare event, such as a fraud transaction or a rare disease: it is probably the most interesting row. Deleting it deletes what you wanted to find (P3.C5 on anomaly detection).
  • A heavy-tailed quantity, such as incomes: the large values belong to the data, so choose summaries that cope (median, percentiles, a log scale).

Deleting an outlier because it is inconvenient changes the answer. If you remove one, say so and say why. Other options are to keep it and use a robust method, to winsorize (cap values at, say, the 1st and 99th percentiles), or to transform the data (a logarithm).

Scaling features for machine learning

Many models work better when features are on comparable scales, such as a height in metres and an income in dollars. Three common rescalings, shown on the seven values:

  • Standardization: x−xˉs\dfrac{x-\bar x}{s}. Result: −0.64-0.64, −0.54-0.54, −0.54-0.54, −0.33-0.33, −0.13-0.13, −0.03-0.03, 2.212.21. P4.19 uses the same operation inside a network.
  • Min–max scaling: x−min⁡max⁡−min⁡\dfrac{x-\min}{\max-\min}, which maps the data into [0,1][0,1]. Result: 00, 0.040.04, 0.040.04, 0.110.11, 0.180.18, 0.210.21, 11. One outlier decides the maximum, and the other six values are squeezed into roughly the lowest fifth of the range (00 to 0.210.21).
  • Robust scaling: x−medianIQR\dfrac{x-\text{median}}{\text{IQR}}. Result: −0.67-0.67, −0.44-0.44, −0.44-0.44, 00, 0.440.44, 0.670.67, 5.565.56. The six ordinary values keep a sensible spread, and the outlier stays visibly far away. (Scikit-learn’s RobustScaler does this by default, with the quartiles as the IQR.)

Each one needs numbers computed from the data, which brings a trap. Compute the mean and standard deviation (or the median and IQR) on the training data only and reuse them on validation and test data. Computing them on all of the data lets test information leak into training, a mistake that P3.A11 treats in detail.

Pictures

A summary compresses; a picture shows what was compressed away. Five kinds of plot do most of the work.

Histograms. Cut the range into bins, count the values per bin and draw the counts as bars. The picture depends on the bin width, which you choose. Narrow bins follow each value and look jagged. Wide bins smooth away structure. Try it on 6060 made-up values from two groups:

Histogram: the same 60 values, different bin widths

narrow bins (1)wide bins (80)
Bin width 5: 16 bars, 6 empty. The tallest holds 13 of the 60 values, and 2 of the 10 filled bars hold a single value. One stretch of empty bars between filled ones shows a gap in the data: two clusters.
05101501020304050607080value (made up)

bar: number of values in the bineach value (rug)

bin width = 5 bars = 16 tallest bar = 13 empty bars = 6

The bins start at 0, a value on an edge goes into the bin to its right, and the counts always add up to 60. Only the width of the bins changes between pictures.

One data set, many bin widths. The 60 values (made up, between 14.4 and 65.5) form two clusters. The bars count the values in each bin, the small ticks under the axis show the individual values, and the slider changes only the bin width, from 1 to 80 (the widths that divide the range 0 to 80 exactly). The status line reports the number of bars, the tallest bar, the empty bars and how many bars hold a single value. At a width of 1 or 2 the outline is jagged, at 5 to 10 one empty stretch separates the two clusters (at 4 several small gaps appear), and at 16 or more no empty bar is left to show it.

There is no single correct width. A good habit is to try several, and to be suspicious of a feature that appears at only one width. When the widths differ, label whether the bars show counts or a density (the count divided by n×widthn\times\text{width}), since counts change with the width.

Box plots. Compact, and good for comparing many groups side by side. They hide the number of points and the shape: two different histograms can give the same box plot, for instance one hump and two humps with the same quartiles.

Scatter plots show two numerical variables, one dot per example, and reveal curves, clusters and outliers that a correlation coefficient hides (P1.D7). That lesson also mentioned Anscombe’s quartet: four small data sets with the same means, variances and correlation but four different pictures. Later, Matejka and Fitzmaurice (2017, “Same Stats, Different Graphs”) generated many data sets with the same summary statistics as a dinosaur-shaped one drawn by Alberto Cairo (the “Datasaurus Dozen”). The lesson is the same: summaries alone are not enough, so plot the data.

Bar charts show counts or proportions for categories. Start the vertical axis at 00 (bars encode length), and for nominal data sort the bars by height so that the order is not mistaken for meaning.

Log scales. Data such as incomes, file sizes and word counts are positive and right-skewed, with values that differ by factors rather than by amounts. On a logarithmic axis each factor of 1010 is the same distance, so 2020, 200200 and 20002000 are evenly spaced, and the long tail no longer swamps the plot. A log needs positive values, and the mean of the logs is not the log of the mean, so say which scale a summary is on.

Summaries of categorical data

For categories, count. A table of counts (and proportions, the counts divided by nn) is the summary, and the mode is the most common category. Compare with the base rate. Suppose a data set has 950950 examples of class A and 5050 of class B (made up). A classifier that says “A” for each example is right 95%95\% of the time, which sounds good, and finds none of the B examples. The counts are what warn you; P3.A10 develops the fixes. For ordinal data you may also report the median category.

Where this shows up in machine learning

  • Inspecting a data set before training. Counts, means and quartiles per feature, a histogram of each, and a look at the extremes reveal typos, constant columns, impossible values, skewed features and imbalanced classes. Skipping this is a common source of mistakes that no model can repair (tools in P2.4 and P2.5).
  • Feature scaling. Choose standardization, min–max or robust scaling after looking at the distribution (P3.A11), and fit the scaler on the training data only.
  • Losses. Squared error pulls a fit toward the mean and weights large errors heavily, so a few outliers can dominate it. Absolute error pulls toward a median and is less sensitive (P1.D4, P3.A2).
  • Reporting results. A model trained with five random seeds can give accuracies 0.8120.812, 0.8050.805, 0.8090.809, 0.6400.640, 0.8110.811 (made up). The mean, 0.7750.775, matches none of the runs; the median is 0.8090.809, and the range 0.6400.640 to 0.8120.812 shows that one run went wrong. Report the median or the mean with a spread, mention the failed run, and keep the seeds (P1.D9 asked for this, and P1.D13 shows how to compare models fairly).
  • Tail metrics. For 10001000 request times, 980980 at 2020 ms and 2020 at 20002000 ms (made up), the median is 2020 ms and the mean is 59.659.6 ms, but the 99th percentile is 20002000 ms: two users in a hundred wait a hundred times longer than the typical one. Systems that serve models are watched through percentiles such as p50 and p99, not only through averages (monitoring is P12.5).

Intuition

A summary is a lossy photograph of a crowd. The mean is its centre of gravity: it moves when anyone moves, and far-away people move it most. The median is the person standing in the middle of a queue, who does not care how far back the last person stands. The standard deviation is how far people typically stand from the centre of gravity, and the IQR is the width of the middle half of the queue. A box plot draws the queue in one line, and a histogram draws it as a skyline. The analogy breaks when the crowd has two groups: the centre of gravity and the middle person can both stand in an empty field between them.

Math

Sample mean and variance. xˉ=1n∑xi\bar x=\frac1n\sum x_i and s2=1n−1∑(xi−xˉ)2s^2=\frac1{n-1}\sum(x_i-\bar x)^2. They are the mean and variance of the empirical distribution (probability 1n\frac1n per value), apart from the factor nn−1\frac{n}{n-1} in the variance.

Best constants. ∑(xi−c)2\sum(x_i-c)^2 is smallest at c=xˉc=\bar x, since it equals ∑(xi−xˉ)2+n(xˉ−c)2\sum(x_i-\bar x)^2+n(\bar x-c)^2. ∑∣xi−c∣\sum|x_i-c| is smallest at a median: moving cc a little to the right increases the distance to each point on the left and decreases it for each point on the right, so the sum falls while more points lie to the right of cc than to the left.

Linear-interpolation quantile. For sorted x(0)≤⋯≤x(n−1)x_{(0)}\le\dots\le x_{(n-1)} and h=(n−1)qh=(n-1)q, the quantile is Q(q)=x(⌊h⌋)+(h−⌊h⌋)(x(⌊h⌋+1)−x(⌊h⌋))Q(q)=x_{(\lfloor h\rfloor)}+(h-\lfloor h\rfloor)\bigl(x_{(\lfloor h\rfloor+1)}-x_{(\lfloor h\rfloor)}\bigr).

Tukey fences. [Q1−1.5 IQR,  Q3+1.5 IQR]\bigl[Q_1-1.5\,\text{IQR},\;Q_3+1.5\,\text{IQR}\bigr]. For N(μ,σ2)\mathcal{N}(\mu,\sigma^2): Q1,3=μ∓0.6745σQ_{1,3}=\mu\mp0.6745\sigma, IQR=1.349σ\text{IQR}=1.349\sigma, fences at μ±2.698σ\mu\pm2.698\sigma, and the share outside is 2(1−Φ(2.698))=0.00702\bigl(1-\Phi(2.698)\bigr)=0.0070.

Largest zz-score. With n−1n-1 in ss, max⁡i∣zi∣≤n−1n\max_i|z_i|\le\frac{n-1}{\sqrt n}, with equality when the other n−1n-1 values are equal.

Standardized data. The values zi=(xi−xˉ)/sz_i=(x_i-\bar x)/s have mean 00 and sample standard deviation 11.

Code

Statistics of a data set with NumPy. Note ddof=1 for the sample standard deviation, and that np.percentile uses linear interpolation unless you pass method=.

import numpy as np

x = np.array([2, 3, 3, 5, 7, 8, 30])
print(x.mean(), np.median(x))                 # 8.2857..., 5.0
print(x.std(ddof=1))                          # sample standard deviation, 9.827
q1, q3 = np.percentile(x, [25, 75])           # 3.0, 7.5
print(q3 - q1, np.median(np.abs(x - np.median(x))))   # IQR 4.5, MAD 2.0
z = (x - x.mean()) / x.std(ddof=1)            # standardized values

Try it: summaries in code

The first cell computes the summaries of this lesson for the seven values, three quantile conventions, and the best-constant check. The second cell compares the three scalers, shows that the zz rule cannot flag the typo while the IQR rule does, simulates how much of a Gaussian sample lies beyond the whiskers, and runs the request-time and seed examples.

Try it: the summaries of the lesson

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

With these seven values the cell prints a mean of 8.2868.286, a median of 55, a sample standard deviation of 9.8279.827 (9.0989.098 with nn), Q1=3Q_1=3, Q3=7.5Q_3=7.5, IQR 4.54.5, MAD 22 and a mean absolute deviation of 6.2046.204. The fences are −3.75-3.75 and 14.2514.25, so 3030 is flagged. The largest zz is 2.212.21, under the bound 2.272.27. The three conventions give 11, 1.251.25 and 1.751.75. The mean has the smaller squared error (82.7882.78 against 93.5793.57) and the median the smaller absolute error (5.295.29 against 6.206.20).

Try it: scaling, outlier rules and robust summaries

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first three lines reproduce the scalings of the lesson: the outlier at 3030 is scaled to 2.212.21, 11 or 5.565.56, and the other six values land in [−0.64,−0.03][-0.64,-0.03], [0,0.21][0,0.21] and [−0.67,0.67][-0.67,0.67]. The typo gets z=2.846z=2.846, essentially equal to the bound (it falls short only in the fifth decimal), so the zz rule cannot flag it, while the IQR rule does. In a million Gaussian draws, 0.00700.0070 of the values lie beyond the whiskers, close to the exact 0.006980.00698, and 0.00270.0027 beyond ∣z∣=3|z|=3. The request times give mean 59.659.6, p50 2020 and p99 20002000. The seeds give mean 0.77540.7754 and median 0.8090.809.

Go deeper Rank correlation: a relationship summary that resists outliers

P1.D7 showed that one odd student (studied 2020 hours, scored 00) changes the correlation of five students from 0.80.8 to −0.52-0.52. Spearman’s rank correlation replaces each value by its rank (its position in the sorted data, 11 for the smallest) and computes the ordinary correlation of the ranks. The five students keep 0.80.8; with the odd student it is 0.030.03. It is pulled as well, because that student has the largest hours and the lowest score, but only through the ranks, not through how extreme the values are. A perfect but curved increasing relationship gets a rank correlation of exactly 11, where Pearson’s coefficient is below 11. It is still one number, so look at the scatter plot too.

Go deeper The conventions for quantiles, and what changes

Statisticians have catalogued nine common definitions of a sample quantile (Hyndman and Fan, 1996, compared them). They differ in how they turn a fraction qq into a position in the sorted data, and in whether they interpolate. NumPy exposes several as the method argument of np.percentile (linear, weibull, hazen, inverted_cdf, lower, higher, nearest, midpoint and others), and its default, linear, is the one used here. For 1,2,3,41,2,3,4 and the 25th percentile the three choices above give 11, 1.251.25 and 1.751.75, and other choices give 1.51.5 (midpoint, hazen) or 22 (higher). The differences are at most one gap between neighbouring values (here 11 against 22 for lower and higher), and that gap shrinks relative to the spread as nn grows. What matters is to state the method when you publish a number computed from a small sample, and to use the same one when comparing.

Common mistakes

Check your understanding

  1. Ten salaries: nine between 4040 and 6060 thousand and one of 10001000 thousand. Which statement is correct?

  2. The data 1,2,3,41,2,3,4 give a 25th percentile of 1.751.75 in NumPy and 1.251.25 in Python’s statistics.quantiles (default method). What is the best explanation?

  3. In a box plot with Tukey’s convention, what does a point drawn beyond a whisker tell you?

  4. You have a sample of n=8n=8 values with one huge outlier. Why does the rule ∣z∣>3|z|\gt3 fail to flag it?

  5. A feature has a few extreme values. Which scaling keeps most of the values spread over a useful range?

Exercises

  1. For the data 4,8,6,5,3,2,8,9,2,54,8,6,5,3,2,8,9,2,5, give the mean, the median and the mode.
    Show answerSorted: 2,2,3,4,5,5,6,8,8,92,2,3,4,5,5,6,8,8,9. The sum is 5252, so the mean is 5.25.2. The median is the average of the fifth and sixth values, 55. The values 22, 55 and 88 each appear twice, so the data have three modes.
  2. Group A has 3030 people with mean score 7070 and group B has 1010 people with mean 9090. What is the mean of the 4040 people?
    Show answer30×70+10×9040=75\frac{30\times70+10\times90}{40}=75. It is a weighted mean of the group means, with the group sizes as weights.
  3. Compute the 25th and 75th percentiles of 1,2,3,4,5,6,7,81,2,3,4,5,6,7,8 with NumPy’s default, and the IQR.
    Show answerPositions h=7×0.25=1.75h=7\times0.25=1.75 and 7×0.75=5.257\times0.75=5.25 (counting from 00). Q1=2+0.75×(3−2)=2.75Q_1=2+0.75\times(3-2)=2.75 and Q3=6+0.25×(7−6)=6.25Q_3=6+0.25\times(7-6)=6.25, so the IQR is 3.53.5.
  4. For the seven values 2,3,3,5,7,8,302,3,3,5,7,8,30 find the fences and say what the box plot draws.
    Show answerQ1=3Q_1=3, Q3=7.5Q_3=7.5, IQR 4.54.5, fences −3.75-3.75 and 14.2514.25. The lower whisker reaches 22, the upper whisker reaches 88, and 3030 is drawn as a separate point.
  5. Compute the zz-scores of 2,4,6,82,4,6,8 with n−1n-1 in the standard deviation.
    Show answerThe mean is 55, the sum of squared distances is 2020, so s=20/3=2.582s=\sqrt{20/3}=2.582. The zz-scores are −1.162-1.162, −0.387-0.387, 0.3870.387, 1.1621.162. (With nn in place of n−1n-1, the standard deviation is 2.2362.236 and the values are ±1.342,±0.447\pm1.342,\pm0.447, as in the layer-normalization example of P1.D4.)
  6. Can the rule ∣z∣>3|z|\gt3 flag a value in a sample of 1010? Of 1212?
    Show answerNot in a sample of 1010: the largest possible ∣z∣|z| is 9/10=2.8469/\sqrt{10}=2.846. For 1212 the bound is 11/12=3.1811/\sqrt{12}=3.18, so it is possible, but only for an extreme outlier with the other values nearly equal.
  7. The data are 1,2,3,4,1001,2,3,4,100. What do the standard deviation and the MAD do when the 100100 is removed?
    Show answerWith 100100: s=43.6s=43.6 and the MAD is 11 (the median is 33, the distances 2,1,0,1,972,1,0,1,97). Without it: s=1.29s=1.29 and the MAD is 11 (the median is 2.52.5, the distances 1.5,0.5,0.5,1.51.5,0.5,0.5,1.5). The standard deviation changed by a factor of about 3434, and the MAD did not change.
  8. Why is a bar chart of counts for the categories “cat, dog, bird” best sorted by height rather than alphabetically?
    Show answerThe categories are nominal, so their order carries no meaning. Sorting by height makes the comparison easy to read and stops a reader from taking the alphabetical order as a ranking.
  9. A model scores 0.900.90, 0.910.91, 0.890.89, 0.620.62, 0.900.90 on five seeds (made up). Give the mean, the median and what you would report.
    Show answerThe mean is 0.8440.844 and the median is 0.900.90. Report the median or the mean with the spread, and say that one run (0.620.62) failed, rather than quoting 0.8440.844 alone, which matches none of the runs.
  10. Why can the same data look like one hump with wide bins and like two humps with narrow bins?
    Show answerA bin shows only the count of its values. Wide bins add neighbouring counts together, so a dip between two humps can disappear. Narrow bins follow individual values, so the dip shows, and so does chance variation. That is why you try several widths.
  11. A column of 10001000 rows has 990990 values of 00 and 1010 values of 11. What do the mean and the median say, and why do counts help?
    Show answerThe mean is 0.010.01 and the median is 00. The median hides the 1010 ones completely, and the mean is easy to misread. The counts, 990990 and 1010, show the class imbalance at once.
  12. Give one reason to keep an outlier and one reason to remove it.
    Show answerKeep it if it is a real, rare event that your model must handle, such as a fraud case. Remove or fix it if it is a recording error, such as an age typed as 120120, and say what you did.

Next: P1.D13 asks what a summary computed from a sample can say about the population: confidence intervals, significance and comparing models fairly. P3.A11 uses the scalers of this lesson on real features, with the leakage traps, and P4.19 shows standardization inside a network.

Key takeaways

  • A statistic summarizes a data set, the sample-side counterpart of E\mathbb{E}, Var\mathrm{Var} and quantiles of a distribution (P1.D2, P1.D4). The right one depends on the data type: numerical data allow means and spreads, ordinal data allow medians and percentiles, nominal data allow counts, proportions and the mode.
  • The mean uses every value, so one far-away value drags it. The median uses only the order, so it hardly moves. The mean is the constant with the smallest squared error and a median the one with the smallest absolute error (P1.D4). In right-skewed data the mean is usually above the median, which is a tendency, not a law.
  • Spread: the standard deviation (divide by n−1n-1 for a sample) and the range react strongly to an outlier. The IQR (the distance between the 75th and the 25th percentile) and the MAD (median absolute deviation) hardly move. The share of the data that can be changed before a statistic breaks is its breakdown point: about 00 for the mean and the standard deviation, up to about half for the median and the MAD.
  • A percentile is a value with a given share of the data below it. Libraries differ for small data: for 1,2,3,41,2,3,4 the 25th percentile is 11, 1.251.25 or 1.751.75 by three conventions, and NumPy’s default gives 1.751.75. A box plot draws the quartiles as a box, with whiskers to the farthest values within 1.5×IQR1.5\times\text{IQR} of it. Points beyond are drawn singly. That is a convention, not a law: a Gaussian sample puts about 0.7%0.7\% of its points there.
  • Standardizing, z=(x−xˉ)/sz=(x-\bar x)/s, gives mean 00 and standard deviation 11; min–max scaling squeezes everything between the extremes, so one outlier flattens the rest; robust scaling uses the median and the IQR. An outlier can be a typo or the most interesting point: look before deleting. In a small sample no ∣z∣|z| can exceed (n−1)/n(n-1)/\sqrt n, so the rule ∣z∣>3|z|\gt3 cannot fire for n≤10n\le10.
  • Always plot the data: a histogram’s bin width changes its look, a log axis helps for skewed positive data, and very different data sets can share the same means, spreads and correlation (P1.D7).
Found a mistake? Tell us