Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Schutt & O'Neil (2013), p. 41 shows schematically how we go about ‘data science’:

The “data science process”. Figure after , p. 41 (Cathy O’Neil and Rachel Schutt, O’Reilly 2013).

Figure 1:The “data science process”. Figure after Schutt & O'Neil (2013), p. 41 (Cathy O’Neil and Rachel Schutt, O’Reilly 2013).

Our focus here: exploratory data analysis

We will go over what we have learned about descriptive statistics so far and put it in a new context – summary statistics and visualisation in particular.

This revision doubles as a vocabulary lesson: we want to understand the language of statistical data analysis and the language of machine learning alike, and to be able to translate between them.

Statistics vs. machine learning

There are two “cultures”: statistics with statistical learning, and machine learning with predictive modelling. Machine learning is a subfield of artificial intelligence, statistics a subfield of mathematics.

The right-hand column is the vocabulary of the course “Introduction to Deep Learning”, which uses it throughout; anyone who knows the left-hand column will quickly find their way around there.

Exploratory data analysis means computing summary statistics and visualisations (descriptive statistics, that is) in order to get a better sense of the information in a dataset. It is a human-driven, iterative process, and it needs knowledge of the field of application – without some idea of which values are plausible and which questions are worth asking, you produce diagrams instead of insights. Data mining is about automating this step of a data science project: the automatic discovery of patterns and relationships, often following a scheme fixed in advance.

The cultures of modelling can be divided more finely still, as C. Molnar does in the book “Modeling Mindsets: The Many Cultures Of Learning From Data” Molnar (2022); to follow that, though, it helps to already know the maximum likelihood approach and Bayes’ theorem.

Descriptive statistics

Descriptive statistics covers the data analysis that happens before inferential statistics. Mostly that means describing the data through various summary measures.

For a short and relaxed overview of part of the question “what actually are data”, and of the question of scales in particular, there is a video from the HeiCAD programme “KI für Alle” (in German).

Level of measurement and permissible summary measures

Not every summary measure above makes sense for every feature. A mean over postcodes is a number, but it is not information; a standard deviation over school grades presupposes that the distance from “good” to “very good” is the same as the distance from “sufficient” to “deficient”. The level of measurement decides what is allowed:

Level of measurementExampleMeaningful comparisonsMeasure of locationMeasure of spread
nominaldegree programme, colour, postcodeequal / not equalmodevariation ratio (non-modal proportion)
ordinalschool grade, Mohs hardness, rankadditionally: smaller / largermedian, quartilesrange, interquartile range
intervaltemperature in °C, date, Likert scaleadditionally: differencesarithmetic mean, mid-rangevariance, standard deviation
ratioage, price, temperature in Kadditionally: quotientsadditionally: geometric meanadditionally: coefficient of variation

Every level of measurement also permits all the summary measures of the rows above it: for a cardinal feature you may report the median and the mode as well, for an ordinal one the mode. The other way round does not work – the mean and variance of a nominal variable are meaningless, even when its levels are stored as numbers. So a column of data type int is a long way from being on a cardinal scale: an ID is nominal, a school grade ordinal.

Two nominal features. There is no correlation coefficient for the relationship between two nominal features, but there is an equally simple summary measure: the cross-tabulation (contingency table), which counts how often each combination of levels occurs. A cross-tabulation of ground truth against prediction is called a confusion matrix; the chapter Titanic EDA reads the quality of a classifier off one, and pandas produces it with pd.crosstab.

Encoding categorical features. Most machine learning methods (linear regression, say) calculate with numbers, and how to translate a nominal or an ordinal feature into numbers depends on the same table:

The chapter Linear regression shows how to do this with pandas, and what it means for a regression, on the Melbourne dataset. How to unify different spellings of a category beforehand is covered in the chapter Data cleaning.

A worked example

Take the n=8n = 8 values x=(7, 2, 9, 4, 4, 12, 5, 3)x = (7,\ 2,\ 9,\ 4,\ 4,\ 12,\ 5,\ 3) – the number of emails per day over a week plus a day, say.

The same in Numpy (with the quartiles as numpy.percentile interpolates them):

import numpy as np
x = np.array([7, 2, 9, 4, 4, 12, 5, 3])
print(np.median(x))            # 4.5
print(np.percentile(x, [25, 75]))  # [3.75 7.5 ]
print(np.mean(x), np.var(x))   # 5.75 9.9375
print(np.std(x))               # 3.1524... (n-version)
print(np.std(x, ddof=1))       # 3.3701... (Bessel correction, n-1)
print(np.std(x) / np.mean(x))  # 0.5482... coefficient of variation
print(np.exp(np.mean(np.log(x))))  # 4.9542... geometric mean

Simpson’s paradox

Before we come to the pictures, a warning about aggregation that needs nothing more than percentages and still shows why data analysis is more than arithmetic. It comes from a medical study of two treatments for kidney stones Charig et al. (1986); we will simply call them A and B. Each was given to 350 patients, and “success” is whatever the clinicians defined it to be.

TreatmentPatientsSuccessesSuccess rate
A35027378%
B35028983%

Imagine you have kidney stones. Which treatment do you choose? Most people say B.

But there is no such thing as simply “kidney stones”: there are small ones and large ones. Let us split the table along that line:

Treatmentsmall stoneslarge stones
A81 of 87, so 93%192 of 263, so 73%
B234 of 270, so 87%55 of 80, so 69%

For small stones A is better, for large stones A is better. If you have small stones you want A; if you have large stones you want A. And only if you do not know how large your stones are would you want B? That cannot be right, because your stones are either small or large.

The resolution lies in the absolute numbers, not the percentages. Treatment A was used almost exclusively on large stones (263 of 350), treatment B almost exclusively on small ones (270 of 350). Large stones are harder to treat, so the large group of difficult cases drags A’s overall rate down, while B profits from its large group of easy ones. The doctors chose the therapy by stone size, and stone size determines success. A variable like this, one that influences both which group you end up in and the outcome, is called a confounder. The punchline: you should choose B only if it also lets you choose to have small stones.

This phenomenon is called Simpson’s paradox: a relationship that holds overall can reverse in every single subgroup. It occurs not only in tables of percentages but just as readily with continuous features:

Simpson’s paradox with continuous features: within each group y rises with x, over all the points together the trend falls.

Figure 2:Simpson’s paradox with continuous features: within each group yy rises with xx, over all the points together the trend falls.

In the kidney stone example we knew the stone size. Often, though, the variable that creates the groups is not in the table at all: then all we see is the cloud of points on the right, without the colours, and the falling trend looks entirely convincing. Such an unobserved variable is called a latent variable – nothing mysterious about the word, it just means “not observed”. The overall distribution is then a mixture of two group distributions, and the question of whether a cloud of points can be decomposed into such groups will meet us throughout this book: with the contaminated normal distribution, with clustering by k-means, and finally with Gaussian mixture models. That covariance and correlation walk straight into this trap is something we will see in the chapter Covariance.

Visualisation

Why visualise? The first reason: summary numbers can lie without letting it show. Alberto Cairo invented the ‘Datasaurus’ to point out the difference between summary statistics and visualisation:

Never trust summary statistics alone; always visualize your data.

Alberto Cairo, 2016

Justin Matejka and George Fitzmaurice developed it into the ‘Datasaurus Dozen’ Matejka & Fitzmaurice (2017): twelve datasets that all share the same summary statistics (the same means and standard deviations of xx and yy to two decimal places, and the same correlation coefficient of about -0.06 as well; what that measures comes in the chapter Covariance and dependence) but look very different indeed.

The Datasaurus Dozen, inspired by Anscombe’s quartet. Figure: Justin Matejka and George Fitzmaurice, Autodesk Research 2017 .

Figure 3:The Datasaurus Dozen, inspired by Anscombe’s quartet. Figure: Justin Matejka and George Fitzmaurice, Autodesk Research 2017 Matejka & Fitzmaurice (2017).

The second reason to always plot is Simpson’s paradox from above: a single summary measure over all the data can say the opposite of what holds in every group, and in a plot you can see the groups.

A colour palette that works well even with restricted colour perception is this one:

A good palette

That it works can be checked by calculation: a colour vision deficiency can be simulated as a linear map in colour space, and applied to the eight colours above, that looks like this.

The same palette, simulated for normal colour vision and for the three kinds of dichromacy (method after Viénot, Brettel and Mollon 1999). The colours stay distinguishable in all four panels – that is the property that matters.

Figure 4:The same palette, simulated for normal colour vision and for the three kinds of dichromacy (method after Viénot, Brettel and Mollon 1999). The colours stay distinguishable in all four panels – that is the property that matters.

Two things can be seen from it. First, the palette does lose its colourfulness, but no two patches merge – every colour keeps a lightness of its own. Second, a palette that set red against green would merge here, and that is exactly what happens with the widespread traffic-light coding.

Research into suitable colour palettes is not finished – at the SciPy conference in 2022, for instance, there was the talk Development of Accessible, Aesthetically-Pleasing Color Sequences by Matthew Petroff, whose results went into Matplotlib version 3.10.0 in December 2024.

Exploratory data analysis as a process

The tools of this chapter – levels of measurement, measures of location and spread, visualisation – are means to an end. The end is called exploratory data analysis (EDA): opening up a dataset step by step until you can say something about it. “Step by step” is meant literally here, and above all: in a circle. You go through the following five steps not once but again and again, because every pass throws up new questions.

  1. Formulate the research questions. What do you actually want to know? What levels of measurement do the features have, what distributions do you expect, which relationships do you consider plausible? Without this step you produce diagrams instead of insights. In the chapter Exploratory analysis: examples this step comes expressly first.

  2. Visualise the data. The quickest way to see a distribution, an outlier or a relationship is a picture – that was the previous section, and the Datasaurus showed why summary numbers alone are not enough.

  3. Clean the data. Check outliers and remove them where necessary, impute or interpolate missing values, repair errors in the coding. In the chapter Titanic EDA missing ages are replaced by the median; the chapter Data cleaning turns that into a programme of its own.

  4. Transform the data. Select subsets, rescale features, build new features – age groups out of age (binning), say, or an area out of length and width. Such new columns are features too, and finding them is often where the real insight lies.

  5. Model the data. Choose a statistical model and fit it to the data – a normal distribution or a regression line, for instance. The chapters that follow are about that.

The five steps are a finer resolution of the whole picture that Figure 1 showed at the start of the chapter. And because they run in a circle, it is also clear why EDA cannot be automated: step 1 needs somebody with a question, and step 3 somebody who knows which values are implausible in this field of application. We practise that in the chapters that follow, on several datasets.

References
  1. Schutt, R., & O’Neil, C. (2013). Doing Data Science: Straight Talk from the Frontline. O’Reilly Media, Inc.
  2. Molnar, C. (2022). Modeling Mindsets: The Many Cultures Of Learning From Data (p. 113). Independently published.
  3. Charig, C. R., Webb, D. R., Payne, S. R., & Wickham, J. E. A. (1986). Comparison of treatment of renal calculi by open surgery, percutaneous nephrolithotomy, and extracorporeal shockwave lithotripsy. British Medical Journal (Clinical Research Edition), 292(6524), 879–882. 10.1136/bmj.292.6524.879
  4. Matejka, J., & Fitzmaurice, G. (2017). Same Stats, Different Graphs: Generating Datasets with Varied Appearance and Identical Statistics through Simulated Annealing. Proceedings of the 2017 CHI Conference on Human Factors in Computing Systems, 1290–1294. 10.1145/3025453.3025912