Ten people work at a small company (all the numbers here are made up). Nine of them earn between and thousand a year. The boss earns . The “average salary” is 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 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 numbers 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 , and 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 ( 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 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 (digits) or a postal code is nominal, and the mean of postal codes means nothing.
Measures of centre
Take seven values: .
- The mean is the sum divided by : .
- The median is the middle value of the sorted data (for even , the average of the two middle values). Here it is the fourth of seven, .
- The mode is the most frequent value, (it appears twice).
The mean, , lies above all but one of the values. One value, , pulled it up. The median ignored how large is: replace by and the median is still , while the mean becomes . This is the main fact of the section.
The link to P1.D4 is a link to a loss. A guess for the whole data set costs in squared error, and the mean is the that makes it smallest. In absolute error, , a median is the best . For the data the mean is and the median is : the squared error is at the mean and at the median, and the absolute error is at the mean and at the median. For the seven values above, the mean gives and the median gives in squared error, while the absolute errors are and .
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, . A course grade with the exam at weight and the homework at weight gives for marks and . It is also how to combine groups: a group of people with mean and a group of with mean have overall mean , not the you get by averaging and .
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 with mean . 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 have a long right tail (skewness by the usual moment formula) and yet mean below median . 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, . It uses only the two extreme values.
- The sample variance is and the standard deviation is , in the units of the data. P1.D4 explained why a sample divides by rather than (the data are measured from their own mean, which makes the squared distances too small on average). Here , while dividing by gives . Libraries differ: NumPy’s
np.stdandnp.vardivide by unless you passddof=1, pandas divides by , and PyTorch’storch.stdby default divides by .np.covdivides by , as in the sample covariance of P1.D7. - The mean absolute deviation is , here . 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, . It is the width of the middle half of the data: here .
- The MAD, the median absolute deviation, is the median of where is the median. Here the distances to the median are , and their median is .
Remove the and the standard deviation falls from to and the range from to , while the IQR falls only from to and the MAD from to . 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 : 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 leaves the median at , and other choices of three keep it within the range of the original data (replacing gives ). Replacing four can move it anywhere (to , 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 (the 75th percentile of the standard Gaussian), so multiplying the MAD by gives an estimate of 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 , far below . Likewise the IQR of a Gaussian is .
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 -th percentile of a data set is a value with about of the data at or below it. The quantile with fraction is the same thing on a scale from to . The median is the 50th percentile, and the quartiles and 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 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 -quantile sits at the position , counting from . If falls between two sorted values, blend them in proportion. For and : , which is three quarters of the way from to , so .
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): . NumPy calls it
inverted_cdf. - The position with interpolation (
weibullin NumPy, and the default of Python’sstatistics.quantiles): . - The median of the lower half: .
- NumPy’s default: .
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, , the median is and (positions , and ). 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, , the median, and the maximum: for the seven values, . A box plot draws it:
- a box from to , 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 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, , so the fences are and . The value is the farthest inside, so the upper whisker stops at , and is drawn alone. The lower whisker stops at the minimum, .
The number is a convention, not a law of nature. For a Gaussian distribution the quartiles are at , the IQR is , and the fences are at . About 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.
Things to try.
- Symmetric data, one outlier. Press Add an outlier once. The mean moves from to and the median from to , while the standard deviation jumps from to . Press it again: the mean goes on to and the median to . The IQR goes and the MAD , and the standard deviation goes , so the IQR and the MAD change much less.
- Right-skewed incomes. The mean starts at , well above the median . Add an outlier and the gap grows ( against ), since the far point pulls the mean.
- Two groups. The mean is and the median , 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 down to : the median jumps to , because the order in the middle changed.
- The typo. The age pulls the mean to and the standard deviation to . The dot is already selected: press −10 ten times to bring it to , the age that was probably meant. The mean falls to and the standard deviation to . A typo you can fix is the easy case of an outlier.
- Move a point a long way. In the symmetric data drag the highest dot () down to . It moved , the mean falls by (to ), and the median falls by (to ), because the median depends on the order and the values next to the middle.
z-scores, standardizing and outlier rules
The -score of a value says how many standard deviations it is from the mean: . It is the standardizing of P1.D4, applied to data. Standardizing a whole feature gives it mean and sample standard deviation . For the seven values the -scores are , , , , , and .
Two rules for flagging an outlier are common:
- The rule: flag . For a Gaussian distribution only of values are beyond .
- The IQR rule: flag values beyond the box-plot fences, and .
They do not agree. The rule is built from the two statistics that an outlier damages most: the outlier raises and shifts , which shrinks its own . This is called masking. In fact, with in , no can exceed . For the seven values that bound is (the outlier reached ), and for it is , so in a sample of ten or fewer values the rule cannot fire, however absurd the value. For the bound is . Nine values near and one typed as give that value a of , 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 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 , or a temperature of 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: . Result: , , , , , , . P4.19 uses the same operation inside a network.
- Min–max scaling: , which maps the data into . Result: , , , , , , . One outlier decides the maximum, and the other six values are squeezed into roughly the lowest fifth of the range ( to ).
- Robust scaling: . Result: , , , , , , . The six ordinary values keep a sensible spread, and the outlier stays visibly far away. (Scikit-learn’s
RobustScalerdoes 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 made-up values from two groups:
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 ), 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 (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 is the same distance, so , and 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 ) is the summary, and the mode is the most common category. Compare with the base rate. Suppose a data set has examples of class A and of class B (made up). A classifier that says “A” for each example is right 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 , , , , (made up). The mean, , matches none of the runs; the median is , and the range to 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 request times, at ms and at ms (made up), the median is ms and the mean is ms, but the 99th percentile is 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. and . They are the mean and variance of the empirical distribution (probability per value), apart from the factor in the variance.
Best constants. is smallest at , since it equals . is smallest at a median: moving 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 than to the left.
Linear-interpolation quantile. For sorted and , the quantile is .
Tukey fences. . For : , , fences at , and the share outside is .
Largest -score. With in , , with equality when the other values are equal.
Standardized data. The values have mean and sample standard deviation .
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 valuesTry 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 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.
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 , a median of , a sample standard deviation of ( with ), , , IQR , MAD and a mean absolute deviation of . The fences are and , so is flagged. The largest is , under the bound . The three conventions give , and . The mean has the smaller squared error ( against ) and the median the smaller absolute error ( against ).
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 is scaled to , or , and the other six values land in , and . The typo gets , essentially equal to the bound (it falls short only in the fifth decimal), so the rule cannot flag it, while the IQR rule does. In a million Gaussian draws, of the values lie beyond the whiskers, close to the exact , and beyond . The request times give mean , p50 and p99 . The seeds give mean and median .
Go deeper Rank correlation: a relationship summary that resists outliers
P1.D7 showed that one odd student (studied hours, scored ) changes the correlation of five students from to . Spearman’s rank correlation replaces each value by its rank (its position in the sorted data, for the smallest) and computes the ordinary correlation of the ranks. The five students keep ; with the odd student it is . 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 , where Pearson’s coefficient is below . 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 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 and the 25th percentile the three choices above give , and , and other choices give (midpoint, hazen) or (higher). The differences are at most one gap between neighbouring values (here against for lower and higher), and that gap shrinks relative to the spread as 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
Ten salaries: nine between and thousand and one of thousand. Which statement is correct?
The median depends only on the order: the middle two values are near , so it is . The mean adds the size of every value, and adds a lot, giving . The reverse assignment confuses which statistic reacts to size. Having nine close values does not stop the one far value from moving the sum. The average of the lowest and highest value is the midrange, which here would be thousand.
The data give a 25th percentile of in NumPy and in Python’s
statistics.quantiles(default method). What is the best explanation?NumPy’s default places the quantile at position and interpolates; the other uses position . Both are accepted definitions that differ for small samples, so state the method. A bug is not the reason, since each follows its own documented definition. Rounding would not change a result by a quarter of the gap between values. The four values are all different, so there is no tie.
In a box plot with Tukey’s convention, what does a point drawn beyond a whisker tell you?
The whisker rule marks values far from the quartiles in units of the IQR. A large Gaussian sample puts about of its points there, so a few are not alarming, and a point may be real data. The rule says nothing about errors by itself. The three-standard-deviation rule is a different convention that uses the mean. A maximum inside the fences is drawn as a whisker end, not as a separate point.
You have a sample of values with one huge outlier. Why does the rule fail to flag it?
The bound is for eight values, so cannot be reached. The -score can be computed for any data, though its meaning of “rare” is clearest for Gaussian ones. The mean and the median are not equal here: the outlier moves the mean. An outlier’s is large but capped, not near zero.
A feature has a few extreme values. Which scaling keeps most of the values spread over a useful range?
The median and the IQR hardly change when a few extreme values are added, so the bulk of the data keeps its spread. Min–max scaling uses the minimum and the maximum, so one extreme value squeezes the rest into a narrow band, and dividing by the maximum does the same. The claim that scaling by the mean and standard deviation is unaffected is false: both are pulled by extreme values.
Exercises
- For the data , give the mean, the median and the mode.
Show answer
Sorted: . The sum is , so the mean is . The median is the average of the fifth and sixth values, . The values , and each appear twice, so the data have three modes. - Group A has people with mean score and group B has people with mean . What is the mean of the people?
Show answer
. It is a weighted mean of the group means, with the group sizes as weights. - Compute the 25th and 75th percentiles of with NumPy’s default, and the IQR.
Show answer
Positions and (counting from ). and , so the IQR is . - For the seven values find the fences and say what the box plot draws.
Show answer
, , IQR , fences and . The lower whisker reaches , the upper whisker reaches , and is drawn as a separate point. - Compute the -scores of with in the standard deviation.
Show answer
The mean is , the sum of squared distances is , so . The -scores are , , , . (With in place of , the standard deviation is and the values are , as in the layer-normalization example of P1.D4.) - Can the rule flag a value in a sample of ? Of ?
Show answer
Not in a sample of : the largest possible is . For the bound is , so it is possible, but only for an extreme outlier with the other values nearly equal. - The data are . What do the standard deviation and the MAD do when the is removed?
Show answer
With : and the MAD is (the median is , the distances ). Without it: and the MAD is (the median is , the distances ). The standard deviation changed by a factor of about , and the MAD did not change. - Why is a bar chart of counts for the categories “cat, dog, bird” best sorted by height rather than alphabetically?
Show answer
The 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. - A model scores , , , , on five seeds (made up). Give the mean, the median and what you would report.
Show answer
The mean is and the median is . Report the median or the mean with the spread, and say that one run () failed, rather than quoting alone, which matches none of the runs. - Why can the same data look like one hump with wide bins and like two humps with narrow bins?
Show answer
A 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. - A column of rows has values of and values of . What do the mean and the median say, and why do counts help?
Show answer
The mean is and the median is . The median hides the ones completely, and the mean is easy to misread. The counts, and , show the class imbalance at once. - Give one reason to keep an outlier and one reason to remove it.
Show answer
Keep 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 , 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.