Unit 1, lesson 6

Exploratory Data Analysis and Data Quality

How exploratory data analysis checks data quality before modeling, and how the empirical distribution, histograms, the mean, the median and quantiles describe a variable, with outliers flagged for investigation, not deletion.

  • Video 6
  • Data Quality and Feature Preparation

A temperature sensor reports 68 while nearby readings sit around 20. The value could be a faulty reading, a genuinely hot spot or a Fahrenheit reading among Celsius values, and deleting it before finding out which could throw away a real event. This lesson looks at data before any model is fitted, checking units, duplicates, missing values and unusual readings, and describing a variable with its empirical distribution, a histogram, the mean, the median and quantiles.

Key terms

Exploratory data analysis

Definition Exploratory data analysis is the examination of a data set through summaries, tables and plots before a model is chosen, to learn how the values are distributed, how variables relate and where the data have quality problems. Checks of structure, such as the schema (what one row represents, which columns exist, their types, units and allowed values), identifiers, timestamps and permissions, can be run on every record, because they do not use outcomes to tune any choice. Exploration of relationships with the target that will guide modeling choices, such as which features or versions of a feature to use, belongs to the training data, since looking at test outcomes and acting on them makes the test set part of development. A pattern found in exploration describes these data and is not by itself evidence of cause.

In plain words Look at the data before fitting anything, and let the measurement context decide what a pattern means. A plot can show that a value is odd, but only the units, the source and the records can say why.

Example The constructed table below has seven rows of daily records, each with a temperature and that day’s demand.

RowIDTemperatureUnitDemand in units
1D110Celsius30
2D212Celsius34
3D212Celsius34
4D368Fahrenheit50
5D4blankCelsius46
6D516Celsius42
7D640Celsius90

A first look raises four questions. D2 appears twice, D3 is recorded in Fahrenheit while the others are in Celsius, D4 has no temperature, and D6 is much warmer than the other days. A scatter plot of demand against temperature that treated the 68 as Celsius would show one point far to the right with ordinary demand, which points to the unit rather than the weather. After the repairs in the next card, the five days with both values give the points (10,30)(10, 30), (12,34)(12, 34), (16,42)(16, 42), (20,50)(20, 50) and (40,90)(40, 90), and demand rises with temperature. That is an association in these days. Season or operating schedules could raise both, so the plot does not show what changing the temperature would do to demand. In this constructed table the five points even lie exactly on one line, which real measurements essentially never do.

Data quality

Definition Data quality is the fitness of a data set for a stated task. Its main parts are accuracy, meaning that each value measures the quantity it claims to in its stated unit, consistency of units, codes and formats across records, completeness, meaning which values are missing and how many, uniqueness, meaning that each real event is recorded once, timeliness, meaning that each value is available at the prediction time, and representativeness of the deployment population. Repairs keep the raw values beside the derived ones. A unit conversion is recorded next to the raw reading, a copy confirmed by the source collapses to one record, a missing value stays marked as missing and never becomes zero, and an unusual value is changed only when evidence shows it is wrong. Each change goes into a log with its reason, so that someone else can retrace it.

In plain words Good data hold the right quantity, in a known unit, recorded once, with their gaps visible, for cases like the ones the model will meet. Cleaning can fix a unit, but it cannot make data from one site or season speak for another, and a correct value that arrives after the prediction time is still unusable for prediction.

Example For D3 the conversion is

TC=(TF−32)⋅59=(68−32)⋅59=20,\begin{aligned} T_{\text{C}} &= (T_{\text{F}} - 32) \cdot \tfrac{5}{9} \\[0.4em] &= (68 - 32) \cdot \tfrac{5}{9} = 20 , \end{aligned}

so the record keeps the raw 68 degrees Fahrenheit and adds the derived 20 degrees Celsius, and every axis is then labeled in Celsius. The ingestion log confirms that the two D2 rows are one copied event, so they collapse to one record and six distinct days remain. One of the six days, D4, has no temperature, so the missing fraction is 1/61/6. Its demand of 46 units was observed, and deleting the whole row would also discard that valid value. The sensor log confirms the 40 degrees on D6, so that value stays. The observed temperatures are 10, 12, 16, 20 and 40 degrees Celsius, and each summary below says that it rests on these five values.

Empirical distribution and histogram

Definition The empirical distribution of observed values x1,…,xnx_1, \dots, x_n gives weight 1/n1/n to each observation, so a value observed kk times gets weight k/nk/n. Its empirical cumulative distribution function is

Fn(t)=#{i:xi≤t}n,F_n(t) = \frac{\#\{i : x_i \le t\}}{n},

the proportion of observations at or below tt. It is a step function that rises from 0 to 1 and jumps at each observed value. A histogram groups the observations into bins on the number line and draws one bar per bin, whose height is the count in the bin or the proportion of observations in it. When bins have unequal widths, the height is the density, the proportion divided by the bin width, so that areas show proportions. The bins must not overlap and must cover every value, so the rule for values on an edge is part of the definition. This lesson uses bins that include their left edge and exclude their right edge, except that the last bin also includes its right edge.

In plain words The empirical distribution treats the data set as a distribution in its own right, every observed day counting equally. It describes these days, not every future day. A histogram is a coarse picture of it, and different bins can change the picture, so try more than one bin width before reading a shape into the bars.

Example For the five temperatures 10, 12, 16, 20 and 40, each value has weight 1/51/5. Three values are at most 16, so F5(16)=3/5F_5(16) = 3/5, and the function stays at 4/54/5 for every tt from 20 up to just below 40. With the bins [0,10)[0, 10), [10,20)[10, 20), [20,30)[20, 30), [30,40)[30, 40) and [40,50][40, 50], the counts are 0, 3, 1, 0 and 1. The value 20 falls in [20,30)[20, 30) and the value 40 in the last bin. Bins of width 20, namely [0,20)[0, 20), [20,40)[20, 40) and [40,60][40, 60], give the counts 3, 1 and 1, a different picture of the same five days.

Mean and median

Definition For observations x1,…,xnx_1, \dots, x_n the mean is

xˉ=1n∑i=1nxi.\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i .

Sort the values as x(1)≤x(2)≤⋯≤x(n)x_{(1)} \le x_{(2)} \le \dots \le x_{(n)}. The median is the middle sorted value x((n+1)/2)x_{((n+1)/2)} when nn is odd, and the average of the two middle values x(n/2)x_{(n/2)} and x(n/2+1)x_{(n/2 + 1)} when nn is even. Among all constants cc, the mean minimizes the sum of squared deviations ∑i(xi−c)2\sum_{i} (x_i - c)^2, and the median minimizes the sum of absolute deviations ∑i∣xi−c∣\sum_{i} \lvert x_i - c \rvert, a minimum that for even nn every value between the two middle values shares. Both summaries use only the observed values, so they are reported together with the number of values they rest on.

In plain words The mean balances all the values and moves with every one of them, so a single far value pulls it. The median depends only on the order of the values near the middle, so it barely notices how far out an extreme value lies. Neither is right in general. They answer different questions, and a large gap between them is itself a sign of skew or of extreme values.

Example The five temperatures sum to 98, so the mean is 98/5=19.698/5 = 19.6 degrees, and the median is the third sorted value, 16 degrees. If the 40 had been 400, the mean would jump to 91.6 degrees while the median stayed at 16. Mistakes in preparation move these summaries too. Keeping both copies of D2 gives six values with mean 110/6≈18.33110/6 \approx 18.33 and median 14, and entering 0 for the missing D4 gives mean 98/6≈16.3398/6 \approx 16.33 and median 14.

Quantile

Definition For a proportion qq with 0<q≤10 < q \le 1, a qq quantile of observed values is a value tt with at least a fraction qq of the observations at or below tt and at least a fraction 1−q1 - q at or above it. Several values can qualify, and software uses different conventions to pick one, which can disagree on small samples, so the convention must be named. This lesson uses the nearest-rank quantile

Q(q)=x(⌈nq⌉),Q(q) = x_{(\lceil nq \rceil)},

the sorted value at position ⌈nq⌉\lceil nq \rceil, which is also the smallest observed value tt with Fn(t)≥qF_n(t) \ge q. The lower quartile is Q(0.25)Q(0.25), the upper quartile is Q(0.75)Q(0.75), and the interquartile range is IQR⁡=Q(0.75)−Q(0.25)\operatorname{IQR} = Q(0.75) - Q(0.25), the width of the middle half of the data under this convention. For odd nn the nearest-rank Q(0.5)Q(0.5) equals the median, but for even nn it is the lower of the two middle values, while the median averages them.

In plain words Quantiles mark positions in the sorted data. The quartiles cut it into four parts, and the interquartile range measures how spread out the middle half is. It describes the spread of these observations, not the uncertainty of a mean.

Example With five sorted temperatures 10, 12, 16, 20 and 40, the lower quartile sits at position ⌈5⋅0.25⌉=⌈1.25⌉=2\lceil 5 \cdot 0.25 \rceil = \lceil 1.25 \rceil = 2, giving 12, and the upper quartile at position ⌈3.75⌉=4\lceil 3.75 \rceil = 4, giving 20. The interquartile range is 8 degrees. For the four values 10, 12, 16 and 20, the nearest-rank Q(0.5)Q(0.5) is the second value, 12, while the median is (12+16)/2=14(12 + 16)/2 = 14.

Outlier

Definition An outlier is an observation that lies unusually far from the bulk of the data, or from the pattern the other observations follow, judged against a stated comparison. A common exploratory flag uses Tukey’s fences

lower=Q(0.25)−1.5 IQR⁡,upper=Q(0.75)+1.5 IQR⁡,\begin{aligned} \text{lower} &= Q(0.25) - 1.5\,\operatorname{IQR}, \\[0.4em] \text{upper} &= Q(0.75) + 1.5\,\operatorname{IQR}, \end{aligned}

and marks the values outside them. A flag calls for investigation, not removal. An outlier may be a recording error, a unit mistake, a case from outside the intended population or a genuine extreme, and only evidence about the measurement decides which. A confirmed value stays in the data. When an extreme value has a large influence on a result, a sensitivity analysis reports the result with and without it, and any exclusion is reported with its reason and the population it leaves out.

In plain words Unusual and wrong are different things. A very hot day that really happened is part of what a model has to learn about, and deleting it to make a fit look better removes the conditions where predictions may matter most.

Example For the five temperatures the fences are 12−1.5⋅8=012 - 1.5 \cdot 8 = 0 and 20+1.5⋅8=3220 + 1.5 \cdot 8 = 32 degrees, so the value 40 is flagged. The sensor log confirms the reading, so it stays. As a sensitivity check, the mean of the other four values is 58/4=14.558/4 = 14.5 degrees, against 19.6 with all five. Both numbers are correct for their stated sets, and the difference shows the value’s influence, not that it is an error. The raw 68, by contrast, was never a genuine extreme. It was a temperature in a different unit, and the recorded unit, not the size of the number, justified the conversion.

Check yourself

  1. A new file of daily records has temperatures of 8, 10, 10, 12, 14 and 30 degrees Celsius and one blank, and the ingestion log confirms that the two 10-degree rows are two copies of one event. Find the mean and the median temperature after resolving the copy. What would they be if the copy were kept, or if the blank were entered as 0?
Show the answer

After the copy is collapsed, the observed values are 8, 10, 12, 14 and 30, five values for six distinct days. They sum to 74, so the mean is 74/5=14.874/5 = 14.8 degrees, and the median is the third sorted value, 12 degrees. The blank stays missing, and the report says that 5 of 6 days have a temperature.

Keeping the copy gives six values with sum 84, so the mean becomes 14 degrees and the median (10+12)/2=11(10 + 12)/2 = 11 degrees, because one day counts twice. Entering 0 for the blank gives the mean 74/6≈12.3374/6 \approx 12.33 degrees and the median 11 degrees, which invents a reading of 0 degrees that nobody measured.

  1. For the five resolved temperatures of the first question, find the nearest-rank quartiles, the interquartile range and Tukey’s fences. Is 30 degrees flagged, and what does the flag establish?
Show the answer

The sorted values are 8, 10, 12, 14 and 30, with n=5n = 5. The lower quartile is at position ⌈1.25⌉=2\lceil 1.25 \rceil = 2, which is 10, and the upper quartile at position ⌈3.75⌉=4\lceil 3.75 \rceil = 4, which is 14. The interquartile range is 4 degrees, so the fences are 10−6=410 - 6 = 4 and 14+6=2014 + 6 = 20 degrees, and 30 lies above the upper fence.

The flag establishes only that 30 is far from these other values under this rule. It does not show that the reading is wrong. The next step is to check its recorded unit, the sensor’s calibration and log, and outside context such as weather records for that day. If the reading is confirmed, it stays. Without it the mean and the median would both be 11 degrees, against 14.8 and 12, and that comparison belongs in a report as a sensitivity check, not as a cleaned result.

  1. An analyst explores the full data set, including the rows reserved for testing. The analyst checks column types, units and duplicate identifiers, then plots demand against several versions of temperature on all rows, keeps the version most strongly correlated with demand, and concludes that hotter days cause higher demand. Which steps are fine, and which need to change?
Show the answer

The structural checks of types, units and identifiers are fine on all rows, since they use no outcome to tune any choice.

Choosing the version of temperature by its relation to demand on all rows uses test outcomes for a modeling decision, so the test rows have become development data and a later test score would be optimistic. Exploration that guides modeling belongs to the training data, with candidate versions compared on validation data, while the test rows stay untouched until the final evaluation. Since the test rows have already been used here, a credible final estimate needs data that played no part in these choices.

The causal conclusion is not supported. These are observational records, and season, holidays or operating schedules could raise both temperature and demand. The association can still help predict demand under similar conditions, but what a change in temperature would do to demand needs a study design or assumptions that deal with such common causes.

How this lesson connects