Module 1: Mathematics and Statistics
Statistical tests and model metrics, probability and synthetic data, the linear algebra and calculus behind data science, and temporal models.
Testing Hypotheses: t-Tests, Chi-Squared, ANOVA and p-Values
- Choose among one-sample, paired and two-sample t-tests, chi-squared tests and one-way ANOVA based on the type of outcome variable, the number of groups and how the data were collected.
- Run a hypothesis test by hand from the hypotheses to the decision, and interpret its p-value and confidence interval correctly.
- Explain Type I and Type II errors and statistical power, and predict how sample size and the significance level change them.
- Distinguish Pearson from Spearman correlation, compute each on a small data set, and say which one a scenario calls for.
Fernhill Market's $5.20 question
Forty customers who saw Fernhill Market's old checkout page spent an average of $52.10 per order. Forty others were randomly shown a redesigned page during the same week, and they spent an average of $57.30. Fernhill is a fictional online grocer, and every number it produces in this lesson is invented for teaching. Its product manager's message is still one that every working data scientist has received: "That's a $5.20 lift. Can we ship it?"
A defensible reply needs four things. First, a decision rule that separates a real lift from the noise in forty orders. Second, a test statistic that measures the gap in units of that noise. Third, a report of how large the lift could plausibly be. Fourth, an honest account of the two ways the decision can be wrong. Once the checkout question is settled, Fernhill brings four more: whether a new handheld scanner speeds up its pickers, whether late deliveries depend on region, whether three warehouse layouts differ in picking time, and whether delivery distance tracks lateness. Each question calls for a different method, and each method is introduced when Fernhill needs it.
Exam objectives: 1.1 Given a scenario, apply the appropriate statistical method or concept.[1] This lesson teaches the hypothesis-testing bullets of 1.1: t-tests, the chi-squared test, analysis of variance (ANOVA), the p value, hypothesis testing, Type I and Type II errors, confidence intervals and correlation coefficients (Pearson and Spearman). Lesson 2 covers the model metrics in the same objective, such as the confusion matrix, ROC/AUC (receiver operating characteristic/area under the curve) and AIC/BIC (Akaike and Bayesian information criteria).
Because this is the first lesson, here are the basic facts about the exam. CompTIA now markets the certification as CompTIA DataAI and describes it as formerly DataX.[2] The exam series code is still DY0-001 and the version is still V1, so this course applies under either name. The exam launched on 25 July 2024.[2] A sitting has at most 90 questions.[2] The questions are a mix of multiple-choice and performance-based items.[2] You have 165 minutes, so a full sitting averages a little under two minutes per question. Results are pass/fail only, with no scaled score.[2] The exam is offered in English and Japanese. CompTIA recommends five or more years of experience in data science or a similar role.[2] CompTIA usually retires an exam about three years after launch and estimates 2027 for this one. Before you book, check that the objectives document you study from matches the exam you are taking.[2]
| Domain | Weight | Course lessons |
|---|---|---|
| 1.0 Mathematics and Statistics | 17% | 1-5 |
| 2.0 Modeling, Analysis, and Outcomes | 24% | 6-11 |
| 3.0 Machine Learning | 24% | 12-17 |
| 4.0 Operations and Processes | 22% | 18-24 |
| 5.0 Specialized Applications of Data Science | 13% | 25-28 |
Domain 1 carries 17% of the exam, and CompTIA's own summary of it opens with exactly the methods taught here.[2] These tools also return in other domains. Lesson 10, for example, uses experiments and tests to justify a model.
Each lesson opens with the exam objective it serves. It teaches each bullet by its exam name, using worked examples you can reproduce with a calculator. Most lessons also include an exam-cue table that maps question wording to answers. A hands-on lab gives you data and asks for a decision, and its worked solution stays hidden until you ask for it. The closing list states claims specific enough to be tested. The ten-question quiz returns weeks later as short warm-ups, because recalling an idea after a gap makes it last longer than rereading it. A cumulative final exam closes the course. The exam assumes years of practice that no text course can supply, and no course can promise a pass. This one aims to make sure that when a question stem describes a situation, you recognize which method it calls for and why. Atlas also offers a related course on CompTIA's Data+ certification.
Hypothesis testing: a null hypothesis and a rule fixed in advance
A statistical hypothesis test is a procedure for making a yes-or-no decision from noisy data. You state a claim, assume for the moment that it is true, and ask whether the data you collected would be surprising under that assumption. The Engineering Statistics Handbook from the National Institute of Standards and Technology (NIST), published as the NIST/SEMATECH e-Handbook of Statistical Methods, describes a test as deciding whether there is enough evidence to reject a conjecture or hypothesis about a process. That conjecture is the null hypothesis, written H0.[3] Its rival, the alternative hypothesis Ha, is what you conclude if H0 is rejected.
For Fernhill, let μA and μB stand for the true mean order values under the old page (A) and the new page (B). These are the averages you would see if every customer used each page indefinitely. The Greek letter μ (mu) marks a population quantity. The sample means you actually compute are estimates of it. The hypotheses are:
H0: mu_B - mu_A = 0 (the new page changes nothing)
Ha: mu_B - mu_A ≠ 0 (the new page changes mean order value, up or down)This is a two-sided alternative. NIST's handbook uses the same form for photomasks whose linewidths should average 500 micrometers. It calls the alternative two-sided because it guards against departures in both directions, too wide and too narrow.[3] Fernhill wants the two-sided version as well, because a page that lowers spending is as important to catch as one that raises it. A one-sided test looks in one direction only. In the handbook's light-bulb example, the null hypothesis is that the mean lifetime is at least 500 hours, and the test rejects only when the statistic falls below a lower critical value.[3] Choose the direction before you look at the data. If you pick the side after seeing which way the means moved, you halve the reported p-value without adding any evidence.
Next comes the risk you are willing to run. The handbook explains that a test is built so that the risk of rejecting H0 when it is actually true is small. That risk, written α (alpha), is called the significance level of the test.[3] The usual choice is α = 0.05, but that is a convention, not a law. A drug-safety study and a button-color test can reasonably choose different values. Whatever you choose, fix it before the data arrive.
OpenStax's introductory statistics text sums up a hypothesis test as two contradictory hypotheses, a decision based on the data, and a conclusion.[4] In practice the steps are:
- State H0 and Ha, including whether Ha is one-sided or two-sided.
- Choose α.
- Choose the test whose assumptions match the data: what kind of variable the outcome is, how many groups there are, and whether observations come in pairs.
- Compute the test statistic, then either its p-value or the critical value it must pass.
- Decide whether to reject H0 or fail to reject it. Then state the conclusion in the business's own terms.
Notice the wording of the last step. You never "accept" H0. The handbook points out that failing to reject can simply mean you do not yet have enough data.[3] A lack of evidence for a lift is not evidence that the lift is zero, and Fernhill's checkout test is about to show why that matters.
Welch's two-sample t-test on the checkout data
The two groups are independent, because different customers saw each page. The outcome, order value, is a continuous number. Comparing the means of two independent groups is the job of a two-sample t-test. Here is what Fernhill's experiment produced. In this lesson, m stands for a sample mean, s for a sample standard deviation and n for the number of observations.
| Page | Orders (n) | Mean order value (m) | Standard deviation (s) |
|---|---|---|---|
| A, old checkout | 40 | $52.10 | $12.00 |
| B, new checkout | 40 | $57.30 | $13.00 |
The test asks how many standard errors apart the two sample means are. The standard error (SE) of a difference in means is the standard deviation that difference would have if you repeated the whole experiment many times. Each sample mean has variance s2/n, and the variances of independent quantities add, so:
SE = sqrt( s_A^2 / n_A + s_B^2 / n_B )
t = (m_B - m_A) / SE- Variance of the old page's mean: 12.002 / 40 = 144 / 40 = 3.600.
- Variance of the new page's mean: 13.002 / 40 = 169 / 40 = 4.225.
- SE = √(3.600 + 4.225) = √7.825 = 2.797 dollars.
- t = 5.20 / 2.797 = 1.86. The observed lift sits 1.86 standard errors above zero.
- Degrees of freedom, from the Welch-Satterthwaite formula shown below: about 77.5.
- For a two-sided test at α = 0.05 with about 77 degrees of freedom, the critical values are about -1.99 and +1.99. Because 1.86 falls between them, Fernhill fails to reject H0. The exact two-sided p-value, from software or a detailed t table, is about 0.067.
Why use a t distribution and not the normal curve? If you knew the population standard deviations, the statistic would be a z statistic and the normal curve would apply. You do not know them. You estimated them from the same forty orders per page, and that estimate varies from sample to sample. Student's t-distribution builds in this extra uncertainty with heavier tails, so its critical value (1.99 here) is larger than the normal curve's 1.96. How heavy the tails are depends on the degrees of freedom (df), roughly the amount of independent information left over for estimating spread. As df grows, the t distribution approaches the normal curve.
The version just used is Welch's t-test, which does not assume the two groups share the same variance. Its degrees of freedom come from the Welch-Satterthwaite approximation:
vA = s_A^2 / n_A = 3.600 vB = s_B^2 / n_B = 4.225
df = (vA + vB)^2 / ( vA^2/(n_A - 1) + vB^2/(n_B - 1) )
= 7.825^2 / ( 3.600^2/39 + 4.225^2/39 )
= 61.23 / 0.790 = 77.5The older Student's t-test for two samples pools the two standard deviations into one estimate and uses nA + nB - 2 degrees of freedom. Pooling is valid only if the population variances really are equal. When they differ, especially with unequal group sizes, the pooled test's real false-alarm rate drifts away from the α you chose. When the variances are equal, Welch's version loses very little. Because of this asymmetry, many analysts treat Welch as the default for two independent groups. On the exam, a stem that mentions unequal variances or clearly different spreads is pointing you to Welch.
What a p-value of 0.067 does and does not say
The p-value is the probability of getting a test statistic at least as extreme as the one you observed, calculated on the assumption that H0 is true. For Fernhill this means: if the new page truly changed nothing, random assignment alone would produce a gap of $5.20 or more, in either direction, in about 6.7% of experiments this size. The decision rule compares the two numbers you now have. Reject H0 when p is less than or equal to α. Here 0.067 is greater than 0.05, so the test does not reject.
Three common readings of 0.067 are wrong, and each one appears in exam distractors:
- "There is a 6.7% chance the new page has no effect." The p-value is computed by assuming H0 is true, so it cannot also be the probability that H0 is true. Getting that probability would require a prior belief and Bayes' theorem.
- "The effect is small." A p-value mixes the size of the effect with the size of the sample. A trivial effect can give a tiny p-value in a huge sample, and a large effect can give p = 0.4 in a small one.
- "0.067 means the page almost worked; 0.049 means it worked." Those two values describe nearly identical evidence. A decision rule needs a line somewhere, but where the line falls does not change the data.
NIST's technical note on comparing instruments records a growing view among scientists and statisticians that "one should not rely solely on hypothesis tests and associated p-values to draw conclusions."[5] The same note urges you to look at statistical intervals and to always do an exploratory analysis that includes plots of the data.[5] Fernhill's product manager asked "can we ship it?", and a p-value alone cannot answer that.
Remember: a p-value measures how surprising your data would be if H0 were true. It is not the probability that H0 is true, and on its own it says nothing about how big or how valuable the effect is.
Type I and Type II errors: the two ways Fernhill can be wrong
Any decision made from a sample can go wrong in two distinct ways. OpenStax sets them out as a table of what you decide against what is actually true. Rejecting H0 when it is true is a Type I error.[6] Failing to reject H0 when it is false is a Type II error.[6] Lesson 2's confusion matrix uses the same structure: a Type I error is a false positive and a Type II error is a false negative.
| Your decision | H0 actually true (page does nothing) | H0 actually false (page changes spending) |
|---|---|---|
| Fail to reject H0 | Correct | Type II error, probability β |
| Reject H0 | Type I error, probability α | Correct, probability 1 - β (the power) |
In Fernhill's terms, a Type I error ships a page that does nothing. That costs engineering time, and a redesign that does nothing may hide a small harm. A Type II error shelves a page that really would have earned about $5 more per order. The probability of a Type I error is α, which you choose. The probability of a Type II error is β (beta). Statistical power, 1 - β, is the probability that the test detects an effect that is really there.
Which error is worse depends on what each wrong decision costs. In one OpenStax example, H0 is that a climber's equipment is safe. The Type II error, believing unsafe equipment is safe, has the greater consequence, because the climber will then use it.[6] A screening model for a serious disease and a test of an email subject line sit at opposite ends of this range. That is why α should come from the business problem, not from habit.
The two risks behave differently. You set α directly. The handbook stresses that β is not chosen by the user. It depends on how large the real departure from H0 is: big departures are easy to detect and small ones are hard.[3] For a fixed sample size, lowering α makes the test more reluctant to reject, which raises β. You cannot push both risks to zero by moving the threshold. The only way to lower both at once is to collect more information.
Eighty customers per page: how sample size flips the verdict
Suppose Fernhill had run the experiment for two weeks instead of one and collected 80 orders per page. Suppose too that the means and standard deviations came out exactly the same. Only n changes.
- The variance of each mean halves: 144 / 80 = 1.800 and 169 / 80 = 2.1125.
- SE = √(1.800 + 2.1125) = √3.9125 = 1.978. That is smaller by a factor of √2, about 1.414.
- t = 5.20 / 1.978 = 2.63, larger by the same factor.
- Welch df is about 157, and the two-sided critical values at α = 0.05 are about -1.975 and +1.975.
- 2.63 lies beyond 1.975, so Fernhill rejects H0. The two-sided p-value is about 0.009.
| Quantity | Run 1: 40 orders per page | Run 2: 80 orders per page |
|---|---|---|
| Observed lift | $5.20 | $5.20 |
| Standard error | 2.797 | 1.978 |
| t statistic | 1.86 | 2.63 |
| Welch degrees of freedom | 77.5 | 157 |
| Two-sided p-value | about 0.067 | about 0.009 |
| Decision at α = 0.05 | Fail to reject | Reject |
Nothing about the page changed between the two runs. Only the amount of evidence changed. If the page really does lift spending by about $5, the first run's verdict was a Type II error: the experiment was too small to detect an effect of that size. This is what OpenStax means when it says that a larger sample can increase the power of the test.[6] The standard error shrinks with the square root of n, so doubling n divides it by about 1.41, and quadrupling n halves it.
The practical step is to settle n before the experiment with a power analysis. You state the smallest effect worth detecting, the α you will use and the power you want (0.8 is a common target), then solve for the sample size that delivers it. The wrong step is to keep adding customers and checking until p drops below 0.05. Every extra look gives chance another try, so the real Type I error rate climbs well above the α you report. Sequential test designs that correct for repeated looks exist for exactly this reason.
Remember: a non-significant result from a small sample is weak evidence that there is no effect. Power, 1 - β, rises with sample size and with the true effect size, and falls when α is made stricter.
Confidence intervals: how big the lift might be
The NIST note states the weakness of a bare test plainly. A hypothesis test says whether to reject "no difference", but it does not say which option did better, how large the difference is, or whether the difference matters in practice.[5] A confidence interval addresses those questions. For a difference, it is the range of values for the difference that are plausible given the data.[5]
CI (confidence interval) = (m_B - m_A) ± t* × SE
where t* is the two-sided critical value for the chosen confidence level
(for 95%, the same value used in the test at alpha = 0.05)Run 1: 5.20 ± 1.991 × 2.797 = 5.20 ± 5.57, which gives -0.37 to 10.77 dollars. Run 2: 5.20 ± 1.975 × 1.978 = 5.20 ± 3.91, which gives 1.29 to 9.11 dollars.
Read the intervals against the tests. Run 1's interval includes 0, and its test failed to reject. Run 2's interval excludes 0, and its test rejected. That is no coincidence. A 95% interval built from the same t procedure excludes the null value exactly when the two-sided test at α = 0.05 rejects. The interval also carries more information than the test. Run 1 says the page might cost 37 cents an order or add almost $11. That is not "no effect". It is "not enough data", and a product manager can decide whether more data is worth paying for.
The confidence level belongs to the procedure, not to one computed interval. NIST puts it this way: a procedure with a 90% confidence level should include the correct value 90% of the time.[5] Once you have computed -0.37 to 10.77, the true lift either is or is not inside it. The 95% describes how often intervals made this way capture the truth across many experiments. Higher confidence costs width: a 99% interval is longer than a 95% interval, which is longer than a 90% one.[5] For run 2, the 99% critical value is about 2.607, giving 5.20 ± 5.16, or 0.04 to 10.36 dollars. That interval still clears zero, but only just, which matches a p-value of 0.009 sitting just under 0.01.
Remember: report a confidence interval with every test. If the 95% interval for a difference excludes zero, the two-sided test at α = 0.05 rejects. If it includes zero, the test does not reject, and the interval's width tells you how much you still do not know.
One-sample, paired and two-sample t-tests
The t-test is a family. The question you are asking, and the way the data were collected, decide which member to use.
| Test | Question it answers | Statistic | Degrees of freedom |
|---|---|---|---|
| One-sample t-test | Does one group's mean differ from a fixed target μ0? | t = (m - μ0) / (s / √n) | n - 1 |
| Paired t-test | Do two measurements on the same units differ on average? | t = md / (sd / √n), computed on the differences | n - 1, where n counts pairs |
| Student's two-sample t-test | Do two independent groups' means differ, assuming equal variances? | Difference in means / pooled SE | nA + nB - 2 |
| Welch's t-test | The same question, without assuming equal variances | Difference in means / unpooled SE | Welch-Satterthwaite approximation |
Start with the one-sample t-test. Fernhill promises customers an average delivery window of 60 minutes. Operations samples 25 recent deliveries and finds a mean of 63.0 minutes with a standard deviation of 7.5 minutes. The team agreed in advance to flag drift in either direction, so H0 is μ = 60 and Ha is μ ≠ 60, a two-sided alternative.
- SE = s / √n = 7.5 / √25 = 7.5 / 5 = 1.5 minutes.
- t = (63.0 - 60) / 1.5 = 2.00, with n - 1 = 24 degrees of freedom.
- The two-sided critical value at α = 0.05 for 24 degrees of freedom is 2.064. Because 2.00 falls short of it, Fernhill fails to reject H0. The p-value is about 0.057.
- The 95% interval is 63.0 ± 2.064 × 1.5 = 63.0 ± 3.10, or 59.9 to 66.1 minutes. It includes 60, which agrees with the test.
Now change one input: the question. Suppose that before collecting any data, the team had written down a one-sided alternative, μ > 60, because only late deliveries break the promise. The one-sided critical value at α = 0.05 for 24 degrees of freedom is 1.711. The statistic 2.00 exceeds it, so the test rejects, with a one-sided p of about 0.028. The same data give the opposite verdict. That is legitimate only because the direction was fixed before the data arrived. Choosing it after seeing a mean of 63 is the after-the-fact switch warned about earlier, and it quietly doubles the real false-alarm rate.
Fernhill's next question calls for a paired design. The operations team timed eight pickers filling a standard five-item order with the old handheld scanner, then timed the same eight pickers with a new one.
| Picker | Old scanner (seconds) | New scanner (seconds) | Difference, old minus new |
|---|---|---|---|
| 1 | 60 | 56 | 4 |
| 2 | 75 | 69 | 6 |
| 3 | 52 | 50 | 2 |
| 4 | 88 | 83 | 5 |
| 5 | 70 | 67 | 3 |
| 6 | 66 | 59 | 7 |
| 7 | 95 | 94 | 1 |
| 8 | 58 | 54 | 4 |
| Mean | 70.5 | 66.5 | 4.0 |
A paired t-test works on the eight differences alone. Their mean is md = 32 / 8 = 4.0 seconds. Their deviations from 4.0 are 0, 2, -2, 1, -1, 3, -3 and 0. The squares of those deviations sum to 28, so sd = √(28 / 7) = 2.0 seconds. The standard error is 2.0 / √8 = 0.707, and t = 4.0 / 0.707 = 5.66 with 7 degrees of freedom. The two-sided critical value at α = 0.05 is 2.365, so the scanner does save time. The p-value is below 0.001, and the 95% interval for the saving is 4.0 ± 2.365 × 0.707, or 2.3 to 5.7 seconds.
Now make the classic mistake and treat the two columns as independent groups. The old times have mean 70.5 and s = 14.9. The new times have mean 66.5 and s = 15.3. Welch's test gives SE = √(14.92/8 + 15.32/8), about 7.54, so t = 4.0 / 7.54 = 0.53 and p is about 0.6. The same data now give the opposite verdict. The cause is the spread between pickers. Picker 7 takes 95 seconds and picker 3 takes 52, a gap more than ten times the scanner effect. Pairing subtracts each picker's own speed out of the comparison and leaves only the change. The unpaired test lets that between-picker variation flood the standard error. The mistake can also run the other way: pairing two groups that are not genuinely matched invents a link the data do not have.
All t-tests share some assumptions. Observations must be independent: ten orders from the same loyal customer are not ten independent data points. The sample mean, or the mean difference, must be close to normally distributed. That holds when the data are roughly normal, or, through the central limit theorem, when samples are reasonably large and not dominated by outliers. Heavy skew in small samples, or ordinal data such as 1-5 ratings, push you toward rank-based nonparametric statistics. The Mann-Whitney U test (also called the Wilcoxon rank-sum test) handles two independent groups. The Wilcoxon signed-rank test handles pairs. The Kruskal-Wallis test handles three or more groups. NIST's note on comparing instruments lists nonparametric tests among its topics, alongside hypothesis tests and equivalence testing.[5]
Chi-squared test of independence: late deliveries by region
Fernhill's operations director suspects the South region has a lateness problem. The data are 750 deliveries, each classified two ways: by region (North, Central or South) and by whether it arrived late. These are counts in categories, not measurements, so there is no mean to test and a t-test cannot help. The tool is the chi-squared test, written χ2 (chi is pronounced "kai").
| Region | Late | On time | Total |
|---|---|---|---|
| North | 14 | 186 | 200 |
| Central | 27 | 273 | 300 |
| South | 34 | 216 | 250 |
| Total | 75 | 675 | 750 |
A contingency table like this one counts observations cross-classified by two categorical variables. For a test of independence, OpenStax states the hypotheses in words: H0 says the two factors are independent, and Ha says they are not.[7] Here H0 is "lateness does not depend on region".
The test compares each observed count O with the count E you would expect if H0 were true. Overall, 75 of 750 deliveries, or 10%, were late. If region does not matter, each region should also be about 10% late. In general, E = row total × column total / grand total. For late deliveries in the North, E = 200 × 75 / 750 = 20.
| Cell | Observed O | Expected E | (O - E)2 / E |
|---|---|---|---|
| North, late | 14 | 20 | 1.80 |
| Central, late | 27 | 30 | 0.30 |
| South, late | 34 | 25 | 3.24 |
| North, on time | 186 | 180 | 0.20 |
| Central, on time | 273 | 270 | 0.03 |
| South, on time | 216 | 225 | 0.36 |
| Total | 750 | 750 | 5.93 |
chi-squared = sum over all cells of (O - E)^2 / E = 5.93
df = (rows - 1) × (columns - 1) = (3 - 1) × (2 - 1) = 2Squaring makes every discrepancy positive, and dividing by E puts it in proportion. Being 9 deliveries off when you expected 25 matters more than being 9 off when you expected 225. Large discrepancies can only make the statistic bigger, so the test of independence is always right-tailed: only large values count against H0.[7] With 2 degrees of freedom the critical value at α = 0.05 is 5.991. Fernhill's 5.93 falls just short, so the test fails to reject, with a p-value of 0.051. For exactly 2 degrees of freedom the right-tail area has a simple form, p = e-χ²/2 = e-2.967, about 0.051, which you can check on a calculator.
The verdict is "not significant at 0.05" by a hair, and the earlier sections tell you what to do with that. Do not switch to α = 0.10 now that you have seen the result, because α belongs to the plan. Do look at where the statistic came from. The South late cell contributes 3.24 of the 5.93: 34 late deliveries against 25 expected, or 13.6% late against 10% overall. A reasonable report says the evidence of a South problem is suggestive but inconclusive. It recommends another month of data, with the sample sized in advance for adequate power.
The chi-squared test has conditions. It needs raw counts, never percentages or means, because converting counts to percentages throws away the sample size the test depends on. Each observation must fall in exactly one cell, and observations must be independent. OpenStax requires every expected count to be at least five.[7] Fernhill's smallest expected count is 20, so the condition holds. When it fails, combine sparse categories or use Fisher's exact test, which computes the probability directly instead of relying on the chi-squared approximation. Finally, a significant χ2 says the variables are associated, not how strongly. A measure such as Cramér's V reports the strength.
For comparison, OpenStax works a larger example: 839 volunteers cross-classified by type of volunteer and hours worked per week. It gets χ2 = 12.99 on 4 degrees of freedom and a p-value of 0.0113, so at α = 0.05 it rejects H0 and concludes that the two factors are not independent.[7]
Independence is one of three main uses of the chi-squared distribution that OpenStax lists. The goodness-of-fit test asks whether one categorical variable's counts follow a claimed distribution, such as whether lottery numbers come up equally often.[8] Its statistic has the same form, the sum of (O - E)2/E, with expected counts taken from the claimed distribution. It has k - 1 degrees of freedom for k categories when no parameters are estimated from the data. The third use tests a single variance, such as whether a coffee machine dispenses a consistent amount.[8] A related design, the test of homogeneity, uses the same arithmetic as the independence test but draws a separate sample from each population. On the exam, "observed versus expected counts for one variable" points to goodness-of-fit, and "two categorical variables in a table" points to independence.
Analysis of variance (ANOVA): three warehouse layouts
Fernhill's warehouse team tried three shelf layouts. Fifteen pickers were randomly assigned, five to each layout, and each was timed in minutes on a standard 20-item order. The question is whether the layouts differ in mean picking time.
| Layout | Picking times (minutes) | Group mean |
|---|---|---|
| A | 10, 12, 11, 13, 9 | 11 |
| B | 13, 15, 14, 12, 16 | 14 |
| C | 11, 13, 12, 14, 10 | 12 |
Why not run three t-tests (A against B, A against C, B against C)? Each test at α = 0.05 carries a 5% false-alarm risk. If H0 is true everywhere and the tests were independent, the chance that at least one would falsely reject is 1 - 0.953 = 0.143, nearly three times the risk you meant to accept. Five groups give ten pairs, and the problem gets worse. Analysis of variance asks the whole question in a single test. H0 is μA = μB = μC. Ha is that at least one mean differs.
The name describes the mechanism. ANOVA splits the total variation in the data into two parts: variation between the group means, and variation of individual observations within their own groups. If the layouts make no difference, the group means should scatter only about as much as the within-group noise predicts. If the group means scatter much more than that, the layouts matter.
- Grand mean of all 15 times: 185 / 15 = 12.33 minutes.
- Between-group sum of squares, SSB: for each group, compute n × (group mean - grand mean)2, then add the results. 5 × [(11 - 12.33)2 + (14 - 12.33)2 + (12 - 12.33)2] = 5 × (1.78 + 2.78 + 0.11) = 23.33.
- Within-group sum of squares, SSW: each observation's squared distance from its own group mean, all added together. Each group's deviations are some arrangement of -2, -1, 0, 1 and 2, so each group contributes 10, and SSW = 30.
- A mean square is a sum of squares divided by its degrees of freedom. Between groups has k - 1 = 2 degrees of freedom, where k is the number of groups. Within groups has N - k = 15 - 3 = 12, where N is the total number of observations. The mean square between groups is MSB = 23.33 / 2 = 11.67. The mean square within groups is MSW = 30 / 12 = 2.50.
- F = MSB / MSW = 11.67 / 2.50 = 4.67.
| Source | Sum of squares | df | Mean square | F | p |
|---|---|---|---|---|---|
| Between layouts | 23.33 | 2 | 11.67 | 4.67 | 0.032 |
| Within layouts | 30.00 | 12 | 2.50 | ||
| Total | 53.33 | 14 |
Under H0, the statistic follows an F-distribution with 2 and 12 degrees of freedom, whose 5% critical value is 3.89. Since 4.67 is greater than 3.89, Fernhill rejects H0, with p about 0.032. Like χ2, the F test is right-tailed, because only between-group spread larger than the within-group noise counts as evidence. A useful effect size is η2 (eta squared) = SSB / total sum of squares = 23.33 / 53.33 = 0.44. In this sample, layout accounts for about 44% of the variation in picking time.
A significant ANOVA tells you that some layout differs, not which one. To find out, run a post hoc analysis built for many comparisons, such as Tukey's honestly significant difference (HSD) test. It compares every pair while holding the chance of any false rejection across the whole set at α. Here layout B, with a mean of 14 minutes, is the obvious candidate for being slower than layout A, with 11.
One-way ANOVA assumes independent observations, roughly normal residuals within each group, and similar variances across groups. Levene's test checks the last assumption. Welch's ANOVA relaxes it, and the Kruskal-Wallis test replaces the comparison of means with a comparison of ranks when normality fails badly. A two-way analysis of variance handles two factors at once, such as layout and shift (day or night). It adds an interaction term that asks whether the layout effect depends on the shift. With exactly two groups, one-way ANOVA and the pooled two-sample t-test are the same test, and F = t2. The same ratio of explained to unexplained mean squares reappears as the F statistic among the regression performance metrics in objective 1.1.
Remember: three or more group means call for ANOVA, not a string of t-tests. A significant F says at least one mean differs, and a post hoc test such as Tukey's HSD says which.
Pearson and Spearman correlation coefficients
Fernhill's last question is about the strength of an association rather than a difference between groups: do longer delivery distances go with later arrivals? Here is a sample of six deliveries, small enough to work by hand.
| Delivery | Distance x (km) | Minutes late y | Rank of x | Rank of y | d = rank of x - rank of y |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 1 | 1 | 0 |
| 2 | 2 | 3 | 2 | 2 | 0 |
| 3 | 3 | 5 | 3 | 4 | -1 |
| 4 | 4 | 4 | 4 | 3 | 1 |
| 5 | 5 | 6 | 5 | 5 | 0 |
| 6 | 6 | 30 | 6 | 6 | 0 |
A correlation coefficient summarizes how two variables move together on a scale from -1 (a perfect negative relationship) through 0 (no relationship of the kind measured) to +1 (a perfect positive one). The phrase "of the kind measured" is the whole difference between the two coefficients the exam names.
The Pearson correlation coefficient, r, measures linear association between two continuous variables:
r = sum of (x - m_x)(y - m_y) / sqrt( sum of (x - m_x)^2 × sum of (y - m_y)^2 )Here mx = 3.5 and my = 50 / 6 = 8.33. The sum of cross-products is 74.0, the sum of (x - mx)2 is 17.5, and the sum of (y - my)2 is 573.3. So r = 74.0 / √(17.5 × 573.3) = 74.0 / 100.2 = 0.74.
Spearman's rank correlation coefficient, ρ (rho), is Pearson's r computed on the ranks instead of the raw values. It measures monotonic association: whether y tends to rise whenever x rises, at any rate. When there are no tied values it has a shortcut formula:
rho = 1 - 6 × (sum of d^2) / ( n (n^2 - 1) )Only deliveries 3 and 4 swap ranks, so the sum of d2 is 1 + 1 = 2, and ρ = 1 - 12 / (6 × 35) = 1 - 12 / 210 = 0.94.
Why the gap between 0.74 and 0.94? The ranks rise almost perfectly in step, so ρ is close to 1. Pearson's r is pulled down because the relationship is not a straight line: the 30-minute delivery at 6 km sits far above any line through the first five points. Pearson counts that point's distance from the line as disagreement. Spearman only sees that the point has the largest y and the largest x, which fits the ordering. Use Pearson when the relationship is plausibly linear and outliers are not driving it. Use Spearman for ordinal data such as satisfaction ratings, for relationships that are monotonic but curved, and when a few extreme values would dominate r. Plot the data first either way: a scatterplot shows curvature and outliers that a single number hides. When values tie, give the tied observations the average of their ranks and apply Pearson's formula to the ranks, because the shortcut is exact only without ties.
A correlation can also be tested. H0 says the population correlation is 0, and the statistic is t = r √(n - 2) / √(1 - r2) with n - 2 degrees of freedom. For r = 0.74 and n = 6, t = 0.74 × 2 / 0.67 = 2.19, which is below the critical value of 2.776 for 4 degrees of freedom. An r of 0.74 looks strong but is not significant at 0.05 with only six points. This is the checkout lesson about sample size again, in a new setting.
Two limits apply to both coefficients. Correlation is not causation: distance and lateness might both be driven by a third factor, such as rural routes having fewer drivers. And a coefficient near zero rules out only the kind of relationship it measures. A U-shaped pattern, where both very short and very long trips run late, can give r and ρ close to zero.
Reading the question stem: cue words and the method they point to
Objective 1.1 begins "given a scenario", so most questions describe a situation and ask which method applies or what a result means. Two questions settle most of them. What kind of variable is the outcome: a continuous measurement, a count in categories, or a rank? And how many groups are there, and how were they measured?
| The stem says | It points to | Do not confuse with |
|---|---|---|
| compare an average with a target, specification or claimed value | One-sample t-test | Two-sample t-test, which needs two groups |
| the same customers, machines or stores before and after; matched pairs | Paired t-test on the differences | Two-sample t-test, which ignores the pairing and loses power |
| two independent or randomly assigned groups; unequal variances | Welch's two-sample t-test | Student's pooled t-test, which assumes equal variances |
| three or more groups; compare means across regions or layouts | One-way ANOVA, then a post hoc test such as Tukey's HSD | Repeated pairwise t-tests, which inflate the false-alarm rate |
| two categorical variables; contingency table; counts; independent of | Chi-squared test of independence | A t-test, which needs a numeric mean |
| observed counts against an expected or claimed distribution | Chi-squared goodness-of-fit test | Test of independence, which involves two variables |
| an expected cell count below 5 | Fisher's exact test or combined categories | The ordinary chi-squared test |
| rejected a true null; false alarm; false positive | Type I error, probability α | Type II error |
| missed a real effect; false negative; test too small | Type II error, probability β; fix with a larger sample | Type I error |
| probability of detecting a real effect | Power, 1 - β | α or the confidence level |
| range of plausible values; how large; margin of error | Confidence interval | p-value, which gives no magnitude |
| linear relationship between two continuous variables | Pearson's r | Spearman's ρ |
| ranks; ordinal scale; monotonic; outliers | Spearman's ρ | Pearson's r |
Common misconceptions
- "A p-value of 0.03 means a 3% chance the null hypothesis is true." The p-value is computed assuming H0 is true. It is the probability of data at least this extreme under that assumption, not the probability of the assumption itself.
- "Not significant means no effect." Fernhill's first checkout run failed to reject a $5.20 lift whose confidence interval reached nearly $11. A small sample has low power, and failing to reject means the data were inconclusive.
- "Statistically significant means important." With enough data, a lift of one cent per order becomes significant. Judge importance from the confidence interval and the business cost, not from the p-value.
- "There is a 95% probability that the true value lies in this particular interval." In the frequentist framework, the 95% describes the method's long-run hit rate. A specific computed interval either contains the true value or does not.
- "Comparing four groups with six t-tests is the same as one ANOVA." Each extra test adds false-alarm risk. With six independent tests at 0.05, the chance of at least one false rejection is about 26%.
- "A correlation near zero means the variables are unrelated." Pearson's r measures only linear association and Spearman's ρ only monotonic association. A U-shaped relationship can score near zero on both.
Recap
- A hypothesis test fixes H0, the alternative and α before the data arrive. You then reject H0 or fail to reject it, and you never accept it. α is the probability of a Type I error.
- The p-value is the probability, assuming H0 is true, of a statistic at least as extreme as the one observed. You reject when p is at or below α. It is not the probability that H0 is true, and it is not an effect size.
- One mean against a fixed target calls for a one-sample t-test with n - 1 degrees of freedom. Two independent groups with a continuous outcome call for a two-sample t-test, using Welch's version when variances are not assumed equal. The same units measured twice call for a paired t-test on the differences, with n - 1 degrees of freedom for n pairs.
- A Type I error rejects a true H0 and has probability α. A Type II error fails to reject a false H0 and has probability β. Power is 1 - β. It rises with sample size and true effect size, and falls when α is made stricter.
- A confidence interval is the estimate ± t* × SE. A 95% interval for a difference excludes zero exactly when the two-sided test at 0.05 rejects. A 99% interval is wider than a 95% interval, and the confidence level describes the procedure, not one interval.
- The chi-squared test of independence uses counts in a contingency table, expected counts E = row total × column total / grand total, and df = (rows - 1)(columns - 1). It is always right-tailed. Every expected count must be at least 5; otherwise use Fisher's exact test.
- One-way ANOVA compares three or more means with F = MSB / MSW (mean square between over mean square within) on k - 1 and N - k degrees of freedom. A significant F needs a post hoc test such as Tukey's HSD to show which means differ.
- Pearson's r measures linear association between continuous variables and is sensitive to outliers. Spearman's ρ is Pearson's r on ranks and measures monotonic association. Both run from -1 to +1, and neither establishes causation.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- CompTIA. (n.d.). CompTIA DataX certification. comptia.org
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Hypothesis testing (Product and Process Comparisons). itl.nist.gov
- OpenStax. (n.d.). 9 Introduction (Hypothesis Testing with One Sample). openstax.org
- NIST. (n.d.). Comparing Instruments (NIST Technical Note 2106). nvlpubs.nist.gov
- OpenStax. (n.d.). 9.2 Outcomes and the Type I and Type II Errors. openstax.org
- OpenStax. (n.d.). 11.3 Test of Independence. openstax.org
- OpenStax. (n.d.). 11 Introduction (The Chi-Square Distribution). openstax.org
- Key terms
- Null hypothesis
- The claim a statistical test assumes true and tries to reject, usually that there is no difference, no effect or no association, written H0.
- Significance level (alpha)
- The probability of rejecting a true null hypothesis that an analyst accepts, chosen before the data are seen; 0.05 is a common convention.
- p-value
- The probability, calculated assuming the null hypothesis is true, of obtaining a test statistic at least as extreme as the one observed; the null is rejected when it is at or below alpha.
- Type I and Type II errors
- A Type I error rejects a null hypothesis that is true (a false positive, probability alpha); a Type II error fails to reject a null hypothesis that is false (a false negative, probability beta).
- Statistical power
- The probability, 1 minus beta, that a test rejects a false null hypothesis; it rises with sample size and effect size and falls as alpha is made stricter.
- Confidence interval
- A range computed from sample data by a procedure that captures the true parameter in a stated share of repeated samples, such as 95%, showing the plausible size of an effect.
- Welch's t-test
- A two-sample t-test for comparing the means of two independent groups that does not assume equal population variances and uses Welch-Satterthwaite degrees of freedom.
- Chi-squared test of independence
- A right-tailed test on a contingency table of counts that compares observed with expected counts to judge whether two categorical variables are associated, with (rows - 1)(columns - 1) degrees of freedom.
- One-way ANOVA
- Analysis of variance that tests whether three or more group means are equal by comparing between-group to within-group variation through an F ratio of mean squares.
- Spearman's rank correlation coefficient
- A correlation coefficient computed on ranks that measures monotonic association from -1 to +1 and suits ordinal data, curved relationships and data with outliers.
Measuring Models: Confusion Matrices, ROC Curves, Information Criteria and Impurity
- Compute accuracy, precision, recall, F1 score and the Matthews correlation coefficient from a confusion matrix, and pick the metric that matches the costs of each kind of error.
- Build an ROC curve from scored cases, calculate AUC two ways, and explain what AUC measures and what it hides.
- Interpret R-squared, adjusted R-squared, RMSE and the F statistic, and use AIC and BIC to compare likelihood-based models fitted to the same data.
- Calculate entropy, the Gini index and information gain for a decision-tree split, and explain why the gain ratio exists.
Ninety percent accuracy from a classifier that finds one positive in a hundred
On 23 January 2025, Madhavan Mukund showed his DMML class (data mining and machine learning) at the Chennai Mathematical Institute a confusion matrix for 1,000 cases: 100 actually positive, 900 actually negative. The classifier had flagged exactly one case as positive, and it was right. It called everything else negative. His slide gave its precision as 1 and its recall as 0.01. The next slides showed classifiers that gained recall by giving up precision.[1]
Work out its accuracy. It got 1 + 900 = 901 cases right, so accuracy is 901 / 1,000 = 90.1 percent. Now take a program that answers "negative" for every row without reading any data. It gets the 900 negatives right and scores 90.0 percent. On this data the headline number cannot tell a model that found one positive from a model that found none.
Every measure in this lesson solves that problem in its own way. A single number summarizes a model by throwing information away, and each measure throws away something different. The exam's scenarios test whether you know what each one keeps.
The lesson compares measures in four families. Classifier metrics read a confusion matrix at one threshold. ROC curves and AUC summarize a classifier across all thresholds. Regression metrics and information criteria judge models that predict numbers or assign likelihoods. Entropy, the Gini index and information gain judge a single split inside a decision tree. In each family you will work an example, then change one input and watch the ranking flip.
Exam objectives: 1.1 Given a scenario, apply the appropriate statistical method or concept.[2] This lesson covers these bullets of 1.1: the confusion matrix and its classifier performance metrics (accuracy, recall, precision, F1 score, Matthews correlation coefficient), receiver operating characteristic/area under the curve (ROC/AUC), the regression performance metrics (R2, adjusted R2, root mean square error, F statistic), the Akaike and Bayesian information criteria (AIC/BIC), entropy, information gain and the Gini index. Lesson 1 covered the hypothesis tests from the same objective.
Reading a confusion matrix: four cells and one positive class
A Confusion matrix is a table that counts every combination of actual class and predicted class. In a binary problem you first name the positive class: the outcome you are trying to detect, such as fraud, disease or churn. Everything else is negative. The choice matters, because precision, recall and F1 look only at the positive class.
| Actual class | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
The two cells on the diagonal, true positives and true negatives, are the correct answers. The other two, false positives and false negatives, are the wrong ones.[1] Read each cell name from the back. The second word is what the model predicted. The first word says whether that prediction was correct. So a false negative is a "negative" prediction that was false, which means the case was really positive. In the hypothesis-testing language of Lesson 1, a false positive is a Type I error and a false negative is a Type II error.
Layouts are not standardized, so read the labels before the numbers. scikit-learn provides the table as its confusion_matrix function.[3] That function puts actual labels in rows and predicted labels in columns, in sorted label order. With labels 0 and 1, that puts TN in the top-left corner, the opposite of the slide above. A small illustrative run:
>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 0, 1, 1, 1, 0]
>>> y_pred = [0, 1, 1, 0, 1, 0]
>>> confusion_matrix(y_true, y_pred)
array([[2, 1],
[1, 2]])
>>> tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
Check it by hand. The three actual 0s (rows 1, 2 and 6) were predicted 0, 1 and 0, giving TN = 2 and FP = 1. The three actual 1s were predicted 1, 0 and 1, giving TP = 2 and FN = 1.
Seven ratios come from those four counts. Each one is a fraction, and its denominator tells you which question it answers.
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / (TP + TN + FP + FN) | What share of all predictions were right? |
| Precision | TP / (TP + FP) | Of the cases flagged positive, what share really were positive? |
| Recall (sensitivity, true positive rate) | TP / (TP + FN) | Of the real positives, what share did the model find? |
| Specificity (true negative rate) | TN / (TN + FP) | Of the real negatives, what share were left alone? |
| False positive rate (FPR) | FP / (FP + TN) = 1 - specificity | Of the real negatives, what share were wrongly flagged? |
| F1 score | 2PR / (P + R) = 2TP / (2TP + FP + FN) | Are precision (P) and recall (R) both reasonably high? |
| Matthews correlation coefficient (MCC) | (TP × TN - FP × FN) / √((TP + FP)(TP + FN)(TN + FP)(TN + FN)) | How strongly do predictions agree with the truth, using all four cells? |
Mukund's notes put the two central questions plainly. Precision asks what percentage of positive predictions are correct. Recall asks what percentage of actual positive cases are discovered.[1] Recall goes by other names: sensitivity in medicine, and true positive rate (TPR) on an ROC plot.[1]
Precision against recall, and the two scores that combine them
Precision and recall pull against each other. They share the numerator TP but have different denominators. A strict model flags only the cases it is very sure of. It raises few false alarms, so its precision is high, but it leaves many positives unflagged, so its recall is low. A permissive model flags generously. It finds most positives, so its recall is high, but it pulls in false alarms, so its precision is low.
Which one to favor depends on what each error costs. Mukund's example is hiring. A first-round screening test should have high recall, so no strong candidate is lost early. The final interview should have high precision, because each offer is expensive.[1] The same logic gives a medical screening test a recall target and a confirmatory diagnosis a precision target.
The F1 score combines the two as their harmonic mean.[1] A harmonic mean is pulled toward the smaller value, and that is the point. For the strict classifier from the opening, precision is 1 and recall is 0.01. Their ordinary average is 0.505, which flatters a model that missed 99 of 100 positives. Their harmonic mean is 2 × 1 × 0.01 / (1 + 0.01) = 0.0198. F1 cannot be high unless both inputs are.
F1 has two limits. It never uses TN, so it says nothing about how the model treats negatives. And its value changes if you swap which class you call positive. When misses matter more than false alarms, practitioners use the F-beta score, which weights recall β times as heavily as precision. F1 is the case β = 1.
The Matthews correlation coefficient fixes both limits. It uses all four cells, and swapping the positive and negative labels leaves it unchanged, because TP trades places with TN and FP with FN in a formula that treats them symmetrically. It runs from -1 to +1: +1 is a perfect prediction, 0 is no better than random and -1 is a perfectly inverted prediction.[4] It equals the Pearson correlation between predicted and actual labels coded 0 and 1, which is why it is also known as the phi coefficient.[4] scikit-learn computes it with matthews_corrcoef.[3] If any row or column total of the matrix is zero, the denominator is zero and the formula is undefined, so check how your library reports that case.
The scikit-learn documentation works a four-row example with that function.[4] The true labels are +1, +1, +1, -1 and the predictions are +1, -1, +1, +1. Treat +1 as positive. Rows 1 and 3 are true positives (TP = 2). Row 2 is a false negative (FN = 1). Row 4 is a false positive (FP = 1). There are no true negatives (TN = 0). So MCC = (2 × 0 - 1 × 1) / √(3 × 3 × 1 × 1) = -1/3, the -0.33 the documentation prints. Accuracy on the same predictions is 2 of 4, which sounds like a coin flip. MCC shows the model is slightly worse than a coin flip, because it got the only negative case wrong.
In short: accuracy counts all correct calls, precision guards against false alarms, recall guards against misses, F1 balances those two while ignoring true negatives, and MCC correlates predictions with the truth using all four cells.
Two classifiers on one dataset: where accuracy, F1 and MCC part company
Mukund's slides also show a permissive classifier on the same 1,000 cases. It flags 599 cases: 99 of the 100 positives and 500 of the 900 negatives. Set the two side by side.
| Measure | Strict classifier | Permissive classifier |
|---|---|---|
| TP, FN, FP, TN | 1, 99, 0, 900 | 99, 1, 500, 400 |
| Accuracy | 901 / 1,000 = 0.901 | 499 / 1,000 = 0.499 |
| Precision | 1 / 1 = 1.000 | 99 / 599 = 0.165 |
| Recall | 1 / 100 = 0.010 | 99 / 100 = 0.990 |
| Specificity | 900 / 900 = 1.000 | 400 / 900 = 0.444 |
| F1 = 2TP / (2TP + FP + FN) | 2 / 101 = 0.020 | 198 / 699 = 0.283 |
| MCC | 0.095 | 0.266 |
Here is the strict classifier's MCC step by step. The numerator is TP × TN - FP × FN = 1 × 900 - 0 × 99 = 900. The four totals in the denominator are TP + FP = 1, TP + FN = 100, TN + FP = 900 and TN + FN = 999. Their product is 89,910,000, and its square root is about 9,482. So MCC = 900 / 9,482 ≈ 0.095.
The permissive classifier works the same way. The numerator is 99 × 400 - 500 × 1 = 39,100. The totals are 599, 100, 900 and 401. Their product is about 21,617,910,000, with a square root near 147,030. So MCC = 39,100 / 147,030 ≈ 0.266.
Read the table across. Accuracy prefers the strict model by 40 percentage points. F1 and MCC both prefer the permissive one, because it actually finds the positives. Neither model is good: an MCC of 0.27 is weak agreement.
Now change one input: what each error costs. Suppose, in a fictional costing, that a missed positive costs 50 units and a false alarm costs 1. The strict model costs 99 × 50 + 0 × 1 = 4,950. The permissive model costs 1 × 50 + 500 × 1 = 550. The permissive model wins easily. Now make a false alarm cost 20 and a miss cost 10. The strict model costs 99 × 10 = 990, and the permissive model costs 1 × 10 + 500 × 20 = 10,010. The same two confusion matrices give the opposite decision. A metric that ignores costs cannot make this call for you. When a scenario states costs, compute expected cost.
With more than two classes, the matrix has k rows and k columns. You compute precision and recall for each class, treating it in turn as positive, then average. A macro average gives each class equal weight. A micro average pools the counts first, so large classes dominate. A weighted average weights each class by its number of true cases. scikit-learn exposes these as scoring options such as f1_macro, f1_micro and f1_weighted.[4] Macro averaging is the one that exposes a model that ignores a small class.
ROC curves and AUC: every threshold at once
Most classifiers do not output labels. They output a score, often a probability estimate for the positive class, and some metrics need those scores rather than labels.[4] A threshold t turns scores into labels: predict positive if the score is at least t. Each threshold produces a different confusion matrix. The Receiver operating characteristic (ROC) curve shows all of them at once.
To draw it, sort the cases from highest score to lowest and lower the threshold one case at a time. At each step, plot the false positive rate on the horizontal axis and the true positive rate (recall) on the vertical axis. The curve starts at (0, 0), where nothing is flagged, and ends at (1, 1), where everything is. A model that ranks perfectly climbs straight up the left edge to (0, 1) before moving right. A model that ranks at random follows the diagonal between the corners.
Here are ten fictional scored cases: four positives (P) and six negatives (N). With 4 positives, each positive found raises TPR by 0.25. With 6 negatives, each false alarm raises FPR by 1/6, about 0.167.
| Rank | Score | Actual | TP so far | FP so far | TPR | FPR |
|---|---|---|---|---|---|---|
| 1 | 0.95 | P | 1 | 0 | 0.25 | 0.000 |
| 2 | 0.85 | P | 2 | 0 | 0.50 | 0.000 |
| 3 | 0.80 | N | 2 | 1 | 0.50 | 0.167 |
| 4 | 0.70 | P | 3 | 1 | 0.75 | 0.167 |
| 5 | 0.55 | N | 3 | 2 | 0.75 | 0.333 |
| 6 | 0.45 | N | 3 | 3 | 0.75 | 0.500 |
| 7 | 0.40 | P | 4 | 3 | 1.00 | 0.500 |
| 8 | 0.30 | N | 4 | 4 | 1.00 | 0.667 |
| 9 | 0.20 | N | 4 | 5 | 1.00 | 0.833 |
| 10 | 0.10 | N | 4 | 6 | 1.00 | 1.000 |
The last two columns are the curve. Plotted, it rises to TPR 0.5 at FPR 0, steps right to FPR 0.167, rises to 0.75, runs right to FPR 0.5, rises to 1.0, then runs flat to the right edge.
The area under the curve (AUC) is the area beneath that staircase. scikit-learn's general auc function computes an area with the trapezoidal rule, and roc_auc_score computes ROC AUC directly from prediction scores.[3] On a staircase the trapezoids are rectangles, so multiply each horizontal run by its height:
- FPR 0 to 0.167 at height 0.50: 0.167 × 0.50 = 0.083
- FPR 0.167 to 0.500 at height 0.75: 0.333 × 0.75 = 0.250
- FPR 0.500 to 1.000 at height 1.00: 0.500 × 1.00 = 0.500
The total is 0.833. (Vertical steps add no area.)
The same number has a second meaning that is easier to reason with. AUC is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative, with ties counted as half. Check it by counting pairs. There are 4 × 6 = 24 positive-negative pairs. The positive at 0.95 outscores all 6 negatives, and so does the one at 0.85. The positive at 0.70 outscores 5, every negative except the one at 0.80. The positive at 0.40 outscores 3: those at 0.30, 0.20 and 0.10. That makes 6 + 6 + 5 + 3 = 20 of 24 pairs, or 0.833 again.
An illustrative run on the same ten cases, with the result rounded to three places:
>>> from sklearn.metrics import roc_auc_score
>>> y_true = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
>>> y_score = [0.95, 0.85, 0.80, 0.70, 0.55, 0.45, 0.40, 0.30, 0.20, 0.10]
>>> round(roc_auc_score(y_true, y_score), 3)
0.833
Pair counting explains AUC's most important property: it depends only on the order of the scores. Square every score, or take every square root, and the order stays the same, so the AUC does too. AUC therefore measures ranking, not calibration. It cannot tell you whether a score of 0.8 means an 80 percent chance. A metric built on the probabilities themselves, such as log loss, does change when you distort them.
AUC also hides the threshold you will actually deploy. Change t and the confusion matrix changes while AUC stays put. At t = 0.50 the model flags the top five cases: TP = 3, FP = 2, FN = 1, TN = 4, so precision is 0.60 and recall is 0.75. Lower t to 0.40 and it flags seven: TP = 4 and FP = 3, so recall rises to 1.00 and precision falls to 4/7, about 0.57. Choosing t is a cost decision. A common default is the threshold that maximizes TPR - FPR, called Youden's J statistic. Here that is t = 0.70, where J = 0.75 - 0.167 = 0.583. Both t = 0.85 and t = 0.40 give J = 0.50.
Read AUC on this scale: 1.0 is perfect ranking, 0.5 is random ranking, and below 0.5 the model ranks backwards. An AUC of 0.30 is not hopeless. Reverse the scores and you get 0.70. A result like that usually means a flipped label or sign somewhere in the pipeline.
ROC's weak point is heavy class imbalance. The false positive rate divides by the number of negatives, so when negatives vastly outnumber positives, a large count of false alarms is still a small FPR. Take a fictional screen with 100,000 negatives and 100 positives. An FPR of 0.01 looks excellent on an ROC plot, yet it means 1,000 false alarms. If recall is 0.90, the model finds 90 positives, and precision is 90 / 1,090, about 8 percent. A precision-recall curve, which computes precision-recall pairs across thresholds, shows that problem directly.[3] When a stem says positives are rare and false alarms are what hurts, prefer the precision-recall view.
With more than two classes, ROC AUC is usually computed for each class against the rest, then averaged with the same macro or weighted choice as F1. One naming trap: credit scoring often reports a "Gini" equal to 2 × AUC - 1. That is a ranking statistic and has nothing to do with the decision-tree Gini index taught below.
In short: an ROC curve plots true positive rate against false positive rate across every threshold; AUC is the chance that a random positive outranks a random negative, so it measures ranking, ignores calibration and the deployed threshold, and can look rosy when positives are rare.
Regression metrics: R2, adjusted R2, RMSE and the F statistic
Cornell's Statistical Consulting Unit names three statistics used to evaluate fit in ordinary least squares (OLS) regression: R-squared, the overall F test and the root mean square error (RMSE).[5] Two of them, R-squared and the F test, compare your model with the simplest one possible, the mean model. The mean model predicts the average of y for every case, and it is what you would use if no predictor carried information.[5] RMSE does something different: it measures the absolute size of your model's errors, without reference to the mean model.
Two sums of squares do all the work. Write y for an actual value, ŷ ("y-hat") for the model's prediction, ȳ ("y-bar") for the mean of y, n for the number of observations and p for the number of predictors, not counting the intercept.
- Total sum of squares, SST = Σ(y - ȳ)2: how far the data sit from the mean model.
- Residual sum of squares (RSS), Σ(y - ŷ)2, also called the sum of squared errors (SSE): how far the data sit from your model.
- Regression sum of squares, SSR = SST - RSS: the improvement your model makes over the mean model, for OLS with an intercept.
| Metric | Formula | Scale | What it tells you |
|---|---|---|---|
| R2 (coefficient of determination) | 1 - RSS / SST | 0 to 1 for OLS with an intercept, on the training data | Share of the variation in y that the model accounts for |
| Adjusted R2 | 1 - (1 - R2)(n - 1) / (n - p - 1) | At most 1; can fall below 0 | R2 charged for each predictor used |
| RMSE | √(RSS / n) | 0 upward, in units of y | Typical size of a prediction error |
| F statistic | (SSR / p) / (RSS / (n - p - 1)) | 0 upward; compared with an F distribution on p and n - p - 1 degrees of freedom | Whether the predictors jointly beat the mean model |
R2 is a relative measure: 0 means no improvement on the mean model, and 1 means perfect prediction. Its weakness is mechanical. Adding a predictor to an OLS model can only keep RSS the same or lower it, so R2 can only rise as predictors are added, even when they are pure noise.[5] Adjusted R2 multiplies the unexplained share by (n - 1)/(n - p - 1), a factor that grows with every predictor. So it falls when a new predictor's gain in fit does not make up for the degree of freedom it uses.[5] Cornell's advice is to use adjusted R2 for any model with more than one predictor.[5]
Whether an R2 is "good" depends on the purpose. Cornell's example is a study of how religiosity affects health. Health has many other causes, so an R2 of 0.10 to 0.15 is reasonable there: the goal is a reliable relationship, not prediction.[5] R2 can also go below zero. On held-out data, or for a model fitted without an intercept, a model can predict worse than the mean, and then 1 - RSS/SST is negative.
The F statistic connects back to Lesson 1. It tests the null hypothesis that every regression coefficient is zero against the alternative that at least one is not.[5] Equivalently, it tests whether the population R2 is zero. A large F with a small p-value says the predictors jointly beat the mean model. It does not say every predictor matters, or that the model predicts well.
RMSE is the absolute measure. R2 gives the share of variation explained, while RMSE tells you how far off predictions typically are.[5] It is in the same units as the response, so an RMSE of 3.2 minutes on delivery times means exactly that.[5] Software differs on the divisor. Dividing RSS by n gives the plain RMSE used to score predictions. Dividing by the degrees of freedom for error, n minus the number of estimated coefficients, gives the "standard error of the regression" printed in OLS output.[6]
Work an example. A fictional regression predicts delivery time for n = 50 orders, with SST = 2,000 (in minutes squared). Model 1 uses p = 3 predictors and leaves RSS = 500. Model 2 adds 7 columns of random noise, so p = 10. As OLS always does, it fits the noise a little, and RSS falls to 480. Model 1, step by step:
- R2 = 1 - 500/2,000 = 0.750.
- Adjusted R2 = 1 - (0.250)(49/46) = 1 - 0.266 = 0.734.
- RMSE = √(500/50) = √10 ≈ 3.16 minutes.
- F = (1,500/3) / (500/46) = 500 / 10.87 ≈ 46.0, on 3 and 46 degrees of freedom.
| Statistic | Model 1 (p = 3) | Model 2 (p = 10, 7 noise columns) | Direction |
|---|---|---|---|
| RSS | 500 | 480 | Falls |
| R2 | 0.750 | 0.760 | Rises |
| Adjusted R2 | 0.734 | 1 - 0.24 × 49/39 = 0.698 | Falls |
| RMSE, divisor n | 3.16 | √9.6 = 3.10 | Falls |
| Standard error of regression, divisor n - p - 1 | √(500/46) = 3.30 | √(480/39) = 3.51 | Rises |
| F statistic | 46.0 on (3, 46) | (1,520/10) / (480/39) = 12.35 on (10, 39) | Falls |
Three numbers say the noise helped: RSS, R2 and in-sample RMSE. Two say it hurt: adjusted R2 and the degrees-of-freedom-corrected standard error. F falls because roughly the same explained variation is now spread over ten numerator degrees of freedom. The real test is new data: noise columns that lowered training RMSE will usually raise RMSE on new orders. The machine learning module of this course treats validation on held-out data in full.
In scikit-learn, metrics where lower is better are negated when used as scorers, so the library can always maximize. That is why the scoring names read neg_mean_squared_error.[4] Those names come from the 2016 documentation for version 0.18. Current releases also ship a dedicated root_mean_squared_error function, so you no longer take the square root yourself.[3]
RMSE against MAE: when one large miss decides the ranking
The exam names RMSE, but its working partner is the mean absolute error (MAE): Σ|y - ŷ| / n, the average size of an error with no squaring. Squaring makes RMSE more sensitive than other measures to the occasional large error, because it gives disproportionate weight to very large errors.[6] Two fictional models show the effect.
| Model | Absolute errors on five cases | MAE | RMSE |
|---|---|---|---|
| A | 1, 1, 1, 1, 10 | 14 / 5 = 2.80 | √(104 / 5) ≈ 4.56 |
| B | 3, 3, 3, 3, 3 | 15 / 5 = 3.00 | √(45 / 5) = 3.00 |
MAE ranks A first; RMSE ranks B first. Which one is right depends on what an error costs. If a 10-minute delay costs ten times as much as a 1-minute delay, MAE matches the business. If one 10-minute delay loses a customer while small delays are shrugged off, RMSE does. On the same errors, RMSE is never smaller than MAE, and the two are equal only when every error has the same size, as in model B.
Both are in the units of y, so they can only compare models whose errors are measured in the same units.[6] An RMSE on log-sales cannot be set beside an RMSE on sales. The mean absolute percentage error (MAPE) gives a unit-free percentage instead, but it breaks down when actual values are near zero.
In short: R2 and adjusted R2 measure improvement over the mean model, RMSE and MAE measure error in the units of y, the F statistic tests whether the predictors jointly beat the mean, and noise predictors flatter R2 and in-sample RMSE while adjusted R2 exposes them.
AIC and BIC: what each extra parameter must buy
R2 belongs to least-squares regression. Many models, including logistic regression, Poisson regression and autoregressive integrated moving average (ARIMA) time-series models, are fitted by maximum likelihood instead. For those, the natural fit measure is the maximized log-likelihood, written ln L: the natural logarithm of the probability the fitted model assigns to the observed data. Higher ln L means better fit. But choosing the model with the highest likelihood will always pick the biggest model, because extra parameters can only help on the data used to estimate them.[7]
The two information criteria subtract a price for each parameter. With k the number of estimated parameters and n the number of observations:
AIC = 2k - 2 ln L (Akaike information criterion)
BIC = k ln(n) - 2 ln L (Bayesian information criterion)
The -2 ln L term measures misfit, shrinking as fit improves, and the other term is the penalty. Because of the minus sign, lower is better for both: low AIC is good fit, high AIC is bad fit.[8] The Akaike information criterion comes from Hirotugu Akaike's work in the early 1970s. The Bayesian information criterion, also called the Schwarz criterion, comes from Gideon Schwarz in 1978.
The only difference is the price per parameter: 2 for AIC, ln(n) for BIC. Since ln(n) is at least 2 once n reaches 8, BIC penalizes larger models more heavily, and from the same candidate set it never chooses a larger model than AIC does.[8] Halve both criteria and you get a rule you can apply in your head. An extra parameter earns its place under AIC if it raises ln L by more than 1. Under BIC it must raise ln L by more than ln(n)/2.
A fictional churn analysis fits two logistic regressions to the same n = 200 customers. Model A has k = 3 parameters and ln L = -520. Model B has k = 6 and ln L = -514. Note that ln(200) ≈ 5.298.
| Quantity | Model A | Model B |
|---|---|---|
| k | 3 | 6 |
| -2 ln L | 1,040 | 1,028 |
| AIC = 2k - 2 ln L | 6 + 1,040 = 1,046 | 12 + 1,028 = 1,040 (lower) |
| BIC = k ln(200) - 2 ln L | 15.89 + 1,040 = 1,055.89 (lower) | 31.79 + 1,028 = 1,059.79 |
The criteria disagree. Geyer's notes at the University of Minnesota point out that, in general, the two do not agree.[8] The break-even rule shows why. B's three extra parameters raised ln L by 6. AIC needs more than 3 × 1 = 3, so B passes. BIC needs more than 3 × ln(200)/2 = 3 × 2.65 = 7.95, so B fails.
Now change one input. Suppose B had reached ln L = -510, a gain of 10 over A. Then AIC(B) = 12 + 1,020 = 1,032 and BIC(B) = 31.79 + 1,020 = 1,051.79. Both are below A's values, so both criteria pick B. Disagreement happens only when the likelihood gain falls between the two prices, here between 3 and 7.95.
Differences between criteria can be turned into weights. For each model, compute Δ, its criterion minus the smallest criterion in the set. Weight each model by exp(-Δ/2), then divide by the total so the weights sum to 1. With BIC and equal prior probabilities on the models, these weights approximate each model's posterior probability. Geyer reads them that way, reporting a BIC weight of 0.975 on the best model in his example.[8] In the first run above, A's ΔAIC is 6, so A gets e-3 ≈ 0.050 against B's 1, and B takes about 95 percent of the AIC weight. B's ΔBIC is 3.90, so B gets e-1.95 ≈ 0.142 against A's 1, and A takes about 88 percent of the BIC weight.
Which should you use? They answer different questions. Larry Wasserman's lecture notes at Carnegie Mellon separate two goals: find the model that predicts best, or find the true model, assuming one of the candidates is true. AIC serves the first goal. Informally, it is an asymptotic approximation to cross-validation.[7] BIC serves the second: if your goal is selecting the true model, use BIC.[7] BIC is consistent, meaning that as n grows its chance of choosing the true model goes to 1.[7] AIC is not consistent. It keeps a steady chance of choosing a model slightly too large, which costs little when prediction is the goal. With a reasonable sample and computing budget, Wasserman's advice for prediction is to use cross-validation itself.[7]
- Same data, same response. Compare criteria only for models fitted to the same n observations of the same y. A model of log(y) and a model of y have likelihoods on different scales.
- Nesting is not required. Likelihood-ratio, Wald and score tests need one model to be a special case of the other; AIC has no such requirement.[8] AIC can compare, for example, a churn model built on income and age with one built on tenure and region, where neither predictor set contains the other.
- Only differences mean anything. An AIC of 1,040 says nothing on its own. Software packages drop different constants from ln L, so compare values from one tool.
- Small samples. When n is small relative to k, practitioners use the corrected AICc = AIC + 2k(k + 1)/(n - k - 1). It converges to AIC as n grows.
For an OLS model with normally distributed errors, the criteria reduce to RSS: AIC = n ln(RSS/n) + 2k, plus a constant that is the same for every model on the same data. This is where AIC meets adjusted R2, which also charges for parameters. Robert Nau's regression notes at Duke call the adjustments built into RMSE and adjusted R2 minor, and say a heavier penalty on complexity really ought to be imposed when selecting among models.[6] AIC and BIC are such penalties.
The "information" in AIC is Kullback-Leibler information, which is Shannon's idea of information carried into statistics.[8] The same Shannon entropy grows decision trees in the next section.
In short: AIC = 2k - 2 ln L and BIC = k ln(n) - 2 ln L; lower wins; an extra parameter must raise ln L by more than 1 under AIC or more than ln(n)/2 under BIC; AIC aims at prediction and BIC at finding the true model.
Entropy, the Gini index and information gain at a decision-tree split
A classification tree grows by asking, at each node, which yes-or-no question best separates the classes. To answer, the algorithm needs a number for how mixed a node is, called its impurity, and a way to score how much a split reduces impurity.
Shannon entropy is the information-theoretic choice: Claude Shannon's measure of randomness, the minimum number of bits needed to transmit a message.[1] For a node whose cases fall into k classes with proportions p1 to pk:
Entropy H = - sum over classes of p_i * log2(p_i) (0 * log2(0) counts as 0)
Gini G = 1 - sum over classes of p_i^2
The Gini impurity, which the exam calls the Gini index, is the probability that two cases drawn at random, with replacement, from the node belong to different classes. Both measures are zero for a pure node, where every case shares one class, and both are largest when the classes are evenly mixed.[9] For two classes the maximum entropy is 1 bit and the maximum Gini is 0.5. For k classes the maxima are log2(k) and 1 - 1/k.
The CART algorithm (Classification and Regression Trees) of Breiman and colleagues, published in 1984, used the Gini impurity as its alternative to entropy.[9] Gini is also the default split criterion for scikit-learn's decision tree classifiers.[9] Ross Quinlan's ID3 and C4.5 algorithms used entropy. A third impurity, the misclassification error 1 - max(pi), is the share of the node that a majority-class prediction gets wrong.
| Share of class 1 in a two-class node | Entropy (bits) | Gini | Misclassification error |
|---|---|---|---|
| 0.00 | 0.000 | 0.000 | 0.000 |
| 0.10 | 0.469 | 0.180 | 0.100 |
| 0.25 | 0.811 | 0.375 | 0.250 |
| 0.50 | 1.000 | 0.500 | 0.500 |
Read down the columns. Misclassification error rises in a straight line. Entropy and Gini rise steeply near purity and flatten near 0.5: they are curved, or concave. Mukund's notes state the practical result in one line: an impurity measure that increases more sharply performs better, empirically.[1] The next section shows why.
Information gain scores a split as the parent's impurity minus the weighted average impurity of its children, with each child weighted by its share of the parent's cases:
Gain = I(parent) - sum over children of (n_child / n_parent) * I(child)
Strictly, "information gain" means this formula with entropy as the impurity I. With Gini, the same formula is often called the Gini decrease. Regression trees use the same structure with the variance of y in place of impurity, which is called variance reduction.[10]
Why misclassification error stalls where entropy keeps splitting
Sebastian Raschka's 2018 decision-tree notes for STAT 479 at the University of Wisconsin-Madison use one split to make the comparison concrete. A node holds 120 cases: 40 of class A and 80 of class B. Split X sends 70 cases left (28 A, 42 B) and 50 cases right (12 A, 38 B).
| Node | Cases | Share of A | Entropy | Gini | Misclassification error |
|---|---|---|---|---|---|
| Parent | 120 | 0.333 | 0.918 | 0.444 | 0.333 |
| Left child | 70 | 0.400 | 0.971 | 0.480 | 0.400 |
| Right child | 50 | 0.240 | 0.795 | 0.365 | 0.240 |
| Children, weighted 70/120 and 50/120 | 120 | - | 0.898 | 0.432 | 0.333 |
| Gain (parent minus weighted children) | - | - | 0.021 | 0.012 | 0.000 |
The entropy column, step by step. Parent: -(1/3)log2(1/3) - (2/3)log2(2/3) = 0.528 + 0.390 = 0.918. Left: 0.4 × 1.322 + 0.6 × 0.737 = 0.529 + 0.442 = 0.971. Right: 0.24 × 2.059 + 0.76 × 0.396 = 0.494 + 0.301 = 0.795. Weighted children: (70/120)(0.971) + (50/120)(0.795) = 0.566 + 0.331 = 0.898. Gain: 0.918 - 0.898 = 0.021.
Under misclassification error the gain is exactly zero. Both children still predict class B and make 28 + 12 = 40 errors, the same 40 the parent made. Raschka notes that, by this measure, the split did not result in an improvement compared to the original state, so a tree using it would stop growing here.[10] Yet the split is useful. The right child is noticeably purer, and a later split of the left child may separate it further. Entropy and Gini both register a positive gain, because of the concave shape of the entropy function, and Gini's curve has the same shape.[10] For a concave curve, the weighted average of the children's impurities lies below the parent's impurity whenever the children's class mixes differ. A straight line, like misclassification error, gives no such gap unless a child's majority class changes.
Now compare a second fictional split of the same parent. Split Y sends 60 cases left (40 A, 20 B) and 60 right (0 A, 60 B), so the right child is pure. Entropy gain = 0.918 - (0.5 × 0.918 + 0.5 × 0) = 0.459. Gini gain = 0.444 - (0.5 × 0.444 + 0) = 0.222. Misclassification gain = 0.333 - (0.5 × 0.333 + 0) = 0.167. All three prefer Y to X. The criteria usually agree on the best split. They differ at the margins, where a straight-line measure sees nothing and a curved one sees a little.
Information gain has a known bias: it tends to prefer features with many possible values.[9] The extreme case is a customer ID column. Splitting 120 cases on 120 unique IDs gives 120 pure leaves, so the gain equals the parent's whole entropy, 0.918. That beats Split Y, yet the split predicts nothing for a new customer. Quinlan's C4.5 corrects this with the gain ratio: divide the gain by the entropy of the split itself, called the split information, so scattered attributes are penalized.[1] The split information of 120 single-case branches is log2(120) ≈ 6.91, so the ID column's gain ratio is 0.918 / 6.91 ≈ 0.13. Split Y divides the cases 60 and 60, so its split information is exactly 1 bit, and its gain ratio stays at 0.459. The gain ratio prefers Y. Gini is drawn to many-valued features in the same way, which is one reason to drop identifiers before training any tree.
Entropy also underlies a classifier metric. scikit-learn describes log loss as logistic loss, or cross-entropy loss.[3] Log loss scores the predicted probabilities themselves, so, unlike AUC, it changes when those probabilities are distorted.
In short: entropy and the Gini index are zero for a pure node and largest for an even mix; information gain is the parent's impurity minus the size-weighted impurity of the children; their curved shape lets them reward splits that misclassification error scores as zero; and the gain ratio keeps many-valued features such as IDs from winning.
Choosing the measure: comparison table and exam cues
The first table sets every measure in this lesson against the same four questions.
| Measure | What it needs | Range and better direction | Blind spot |
|---|---|---|---|
| Accuracy | Predicted labels | 0 to 1, higher | Misleads when one class dominates |
| Precision | Predicted labels | 0 to 1, higher | Ignores missed positives |
| Recall | Predicted labels | 0 to 1, higher | Ignores false alarms |
| F1 score | Predicted labels | 0 to 1, higher | Ignores true negatives; depends on which class is positive |
| MCC | Predicted labels | -1 to +1, higher; 0 is random | Undefined if a row or column of the matrix is empty |
| ROC AUC | Scores | 0 to 1, higher; 0.5 is random | Ignores calibration and the deployed threshold; optimistic when positives are rare |
| R2 | OLS predictions | 0 to 1 in training, higher | Never falls when predictors are added |
| Adjusted R2 | R2, n and p | At most 1, higher | Light penalty; still computed in-sample |
| RMSE | Predictions | 0 upward in units of y, lower | Dominated by large errors; not comparable across units |
| F statistic | OLS fit | 0 upward; larger is stronger evidence | Tests joint significance, not predictive quality |
| AIC | ln L and k | Any value, lower | Only differences on the same data mean anything |
| BIC | ln L, k and n | Any value, lower | Can choose too small a model when prediction is the goal |
| Entropy, Gini, information gain | Class counts at a node | Impurity 0 when pure; gain higher is better | Gain favors many-valued features |
The second table maps the words a question stem uses to the measure they point to, including the pairs people confuse.
| The stem says | Reach for | Not |
|---|---|---|
| Rare positive class; accuracy looks high | Recall, precision, F1 or MCC | Accuracy |
| Missing a positive is dangerous or expensive (screening, safety) | Recall | Precision |
| Each flag triggers a costly action; false alarms hurt | Precision | Recall |
| One balanced number using all four cells; class labels could be swapped | MCC | F1 |
| Balance precision and recall; true negatives are irrelevant | F1 | Accuracy |
| Ranking quality across all thresholds | ROC AUC | Accuracy at one threshold |
| Threshold-free view, rare positives, false alarms matter | Precision-recall curve | ROC curve |
| Costs of each error are stated | Expected cost from the confusion matrix | Any single unweighted metric |
| Proportion of variance explained | R2 | RMSE |
| Regressions with different numbers of predictors | Adjusted R2 (or AIC/BIC) | R2 |
| Typical error in the target's own units | RMSE (or MAE) | R2 |
| Large errors are disproportionately bad | RMSE | MAE |
| Cost grows in proportion to error size; outliers present | MAE | RMSE |
| Are all slopes zero? Is the model better than the mean? | F statistic | R2 alone |
| Likelihood models, prediction goal, possibly non-nested | AIC | Likelihood-ratio test |
| Large n, find the true or most parsimonious model | BIC | AIC |
| Choose a split in a classification tree | Information gain (entropy) or Gini decrease | Misclassification error |
| A many-valued feature such as an ID wins every split | Gain ratio | Plain information gain |
| Choose a split in a regression tree | Variance reduction | Gini |
Common misconceptions
- "A 95 percent accurate classifier is a good classifier." If 95 percent of cases are negative, predicting negative for everything scores 95 percent. Always compare accuracy with the base rate, and check recall, precision or MCC.
- "An AUC of 0.85 means the model is right 85 percent of the time." AUC is the chance that a random positive outranks a random negative, taken across all thresholds. Accuracy at your chosen threshold can be much lower, and AUC says nothing about whether the probabilities are calibrated.
- "A higher R2 always means a better model, and R2 cannot be negative." R2 never falls when OLS predictors are added, so compare adjusted R2, AIC/BIC or held-out error. On test data, a model worse than the mean has a negative R2.
- "An AIC of 1,040 is a good score." AIC and BIC values have no meaning alone. Only differences between models fitted to the same observations of the same response can be interpreted.
- "The Gini index in a decision tree is the Gini coefficient of income inequality." The tree's Gini index is 1 - Σpi2, the chance that two random draws from a node differ in class. The inequality coefficient and the credit-scoring Gini (2 × AUC - 1) are different quantities that share the name.
- "The split with the highest information gain is always the most useful." A unique identifier produces maximal gain and predicts nothing. The gain ratio, or simply dropping identifier columns, prevents it.
What to carry forward
- Precision = TP / (TP + FP) and recall = TP / (TP + FN). F1 = 2TP / (2TP + FP + FN) is their harmonic mean, and it ignores true negatives.
- MCC = (TP × TN - FP × FN) / √((TP + FP)(TP + FN)(TN + FP)(TN + FN)). It runs from -1 to +1 with 0 meaning random, and swapping the positive class leaves it unchanged.
- When a scenario states the cost of each error type, multiply the confusion-matrix counts by the costs. The cheaper model can differ from the one with the best accuracy, F1 or MCC.
- An ROC curve plots TPR against FPR over all thresholds. AUC is the probability that a random positive outscores a random negative: 0.5 is random, below 0.5 is inverted, and only the order of the scores matters.
- With rare positives, a small FPR can still mean thousands of false alarms. A precision-recall curve exposes this where an ROC curve hides it.
- R2 = 1 - RSS/SST never falls when OLS predictors are added. Adjusted R2 = 1 - (1 - R2)(n - 1)/(n - p - 1) falls when a predictor does not earn its degree of freedom.
- RMSE = √(RSS/n) is in the units of y and punishes large errors more than MAE. The overall F statistic tests whether all regression coefficients are zero.
- AIC = 2k - 2 ln L and BIC = k ln(n) - 2 ln L, and lower is better for both. An extra parameter must raise ln L by more than 1 under AIC or by more than ln(n)/2 under BIC. AIC targets prediction, BIC targets the true model, and the models need not be nested but must share the same data.
- Entropy is -Σp log2 p (at most 1 bit for two classes) and Gini is 1 - Σp2 (at most 0.5 for two classes). Information gain is the parent's impurity minus the size-weighted impurity of the children, and the gain ratio corrects its bias toward many-valued features.
Sources
- Madhavan Mukund. (2025). Class Notes 23 Jan 2025 (DMML). Chennai Mathematical Institute. cmi.ac.in
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn. (n.d.). sklearn.metrics API reference. scikit-learn.org
- scikit-learn. (2016). 3.3. Model evaluation: quantifying the quality of predictions. scikit-learn.org
- Cornell Statistical Consulting Unit. (n.d.). Regression fit: R-squared, adjusted R-squared, RMSE, F test. cscu.cornell.edu
- Robert Nau. (n.d.). Linear regression models. Duke University. people.duke.edu
- Larry Wasserman. (n.d.). 36-705 Lecture 25. Carnegie Mellon University. stat.cmu.edu
- Charles Geyer. (n.d.). Model selection and averaging (Stat 5421 notes). University of Minnesota. stat.umn.edu
- Richard Johansson. (n.d.). Decision trees. Chalmers University of Technology. cse.chalmers.se
- Sebastian Raschka. (2018). Lecture 6: Decision Trees (STAT 479 notes). University of Wisconsin-Madison. sebastianraschka.com
- Key terms
- Confusion matrix
- A table counting each combination of actual class and predicted class; in a binary problem its four cells are true positives, false positives, false negatives and true negatives.
- Precision
- The share of cases a classifier flags as positive that really are positive: TP / (TP + FP). High precision means few false alarms.
- Recall
- The share of actual positive cases a classifier finds: TP / (TP + FN). Also called sensitivity or true positive rate; high recall means few misses.
- F1 score
- The harmonic mean of precision and recall, 2PR / (P + R), equal to 2TP / (2TP + FP + FN). It is high only when both are high and it ignores true negatives.
- Matthews correlation coefficient (MCC)
- A classifier score from -1 to +1 that uses all four confusion-matrix cells; it equals the correlation between predicted and actual binary labels and does not change if the positive class is swapped.
- ROC-AUC
- Receiver operating characteristic - area under the curve: the area under a plot of true positive rate against false positive rate across all thresholds, equal to the probability that a random positive is scored above a random negative.
- Adjusted R-squared
- R-squared corrected for the number of predictors, 1 - (1 - R2)(n - 1)/(n - p - 1); unlike R-squared it falls when an added predictor does not improve fit enough to justify the degree of freedom it uses.
- Root mean square error (RMSE)
- The square root of the mean squared prediction error, in the same units as the target; squaring makes it weight large errors more heavily than mean absolute error does.
- AIC and BIC
- Akaike and Bayesian information criteria, 2k - 2 ln L and k ln(n) - 2 ln L, which score likelihood-based models fitted to the same data by fit minus a parameter penalty; lower is better, and BIC's penalty is heavier once n is 8 or more.
- Information gain
- The reduction in impurity from a decision-tree split: the parent node's entropy (or Gini impurity) minus the size-weighted impurity of its child nodes.
Probability, Distributions and Synthetic Data
- Choose among the normal, uniform, Poisson, t, binomial and power-law distributions from how the data arise, and compute probabilities with the correct PMF, PDF or CDF.
- Diagnose skewness, kurtosis and heteroskedasticity, and state what each one does to standard statistical methods.
- Apply Bayes' rule, expected value, Monte Carlo simulation and bootstrapping to a decision and to the uncertainty around it.
- Classify missing data as MCAR, MAR or MNAR, and plan a stratified split and oversampling that do not leak information into the test set.
Three disputes an hour and a pager that will not stop
A fictional payments company we will call Harbor Pay logs an average of 3 disputed card transactions per hour. Its on-call fraud analyst is paged whenever a single hour brings 6 or more. Before signing up for the rota, the analyst asks how often the pager will go off. It goes off in about 8.4 percent of hours, which is roughly two pages a day. Raising the threshold to 8 disputes cuts that to about one page every three and a half days. Both numbers come from one formula and one running total, and you will compute them yourself in a few minutes.
That small calculation contains most of this lesson. To get it you have to decide what kind of variable an hourly count is, pick a distribution that matches how the counts arise, read a probability off a cumulative table, and judge whether the assumptions hold. Harbor Pay's team will keep asking questions. How likely is an alerted transaction to be fraud? What does a bad day cost? How sure are we of our estimates? What do the blank fields mean? How do we train a model on a class that makes up 1 percent of the data? Each question adds one step to a procedure you can reuse on the exam and at work. All Harbor Pay figures are invented for teaching.
Exam objectives: CompTIA DataX DY0-001, objective 1.2: Explain probability and synthetic modeling concepts and their uses.[1] The objective lists six distributions (normal, uniform, Poisson, t, binomial and power law), the shape measures skewness and kurtosis, heteroskedasticity versus homoskedasticity, the probability density function (PDF), the probability mass function (PMF) and the cumulative distribution function (CDF), four probability tools (Monte Carlo simulation, bootstrapping, Bayes' rule and expected value), three types of missingness, oversampling and stratification.
Here is the procedure, in the order Harbor Pay meets each step:
- Decide whether the variable is counted or measured. That tells you whether you need a PMF or a PDF. The CDF works for both.
- Match the way the data arise to a distribution family.
- Check the shape: skewness, kurtosis, and whether the variance stays constant.
- Update a probability with new evidence using Bayes' rule.
- Turn probabilities into a decision with expected value.
- Use Monte Carlo simulation for what you cannot solve on paper.
- Measure the uncertainty of an estimate from the data itself with bootstrapping.
- Audit the missing values and name the mechanism behind them.
- Split and rebalance the data with stratification and oversampling.
After the first run through, we change one input and run the procedure again. The decision flips.
Step 1: Counted or measured? The PMF, the PDF and the CDF
A random variable is a quantity whose value comes out of a chance process, such as the number of disputes in an hour or the dollar amount of the next dispute. By convention the variable is written in upper case (X) and a particular value in lower case (x). The first question about any random variable is whether its values can be counted. Disputes per hour take the values 0, 1, 2 and so on, so they are discrete. A dispute amount, or the time between two disputes, is measured on a continuous scale.
A discrete variable is described by a probability mass function (PMF), written p(x) = P(X = x). It puts a lump of probability on each possible value. A valid PMF obeys two rules: every probability lies between 0 and 1 inclusive, and all the probabilities add up to 1.[2] Watch the names here. The OpenStax textbook calls this discrete function a "probability distribution function (PDF)". The DataX exam, like most data science writing, keeps PDF for the continuous case and PMF for the discrete one, so translate when you read older texts.
A continuous variable is described by a probability density function (PDF), written f(x). A density is not a probability. The probability that X lands in an interval is the area under the curve over that interval:
P(a ≤ X ≤ b) = ∫ab f(x) dx
Two consequences follow, and both turn up as exam distractors. First, the probability of any single exact value is zero, because a single point has no width. Asking for the probability that a dispute is exactly $83.17, correct to infinitely many decimal places, is asking for the area of a line. Second, a density can be larger than 1. A uniform distribution on the interval 0 to 0.25 has density 4 everywhere on that interval, because the total area must still be 4 × 0.25 = 1. A density of 4 tells you how tightly probability is packed. It is not a 400 percent probability.
Advanced texts treat the two cases as one idea: a PMF is a density with respect to counting, and the integral over a count becomes a sum. In practice, use sums for counts, integrals for measurements, and the same logic otherwise.
The cumulative distribution function (CDF), F(x) = P(X ≤ x), covers both kinds. For a discrete variable it is the running total of the PMF, so its graph is a staircase that jumps at each possible value. For a continuous variable it is the integral of the PDF from the far left up to x, so it is smooth, and its slope at any point equals the density there. Every CDF starts at 0, never decreases, and ends at 1.
| Function | Applies to | What its value means | How you get a probability |
|---|---|---|---|
| PMF, p(x) | Discrete variables | P(X = x), a real probability | Add the PMF over the values you want |
| PDF, f(x) | Continuous variables | Density per unit of x; can exceed 1 | Area under f over an interval |
| CDF, F(x) | Both | P(X ≤ x), always between 0 and 1 | P(a < X ≤ b) = F(b) - F(a) |
The CDF does most of the work because most practical questions are about thresholds. "Six or more disputes" is 1 - F(5). A p-value from Lesson 1 is a tail area read from the CDF of a test statistic. A percentile is the CDF run backwards: the 95th percentile is the x where F(x) = 0.95. That inverse function, called the quantile function, is also how simulations generate random values, as you will see in the uniform section below.
The upshot: a PMF gives the probability of an exact count, a PDF gives a density whose areas are probabilities, and the CDF gives "at most x" for either kind. That is why threshold questions are answered with the CDF.
Step 2: Match the story to a distribution family
A distribution family is a formula with a few adjustable parameters. Choosing one is not curve-fitting by eye. You ask how the numbers come into existence, then pick the family whose assumptions match that story. The Gallery of Distributions in the e-Handbook of Statistical Methods from the National Institute of Standards and Technology (NIST) describes more than a dozen continuous families and two discrete ones. The exam names six.
| Family | Type | Parameters | Mean; variance | How the data arise | Typical uses |
|---|---|---|---|---|---|
| Normal | Continuous | μ (mean), σ (standard deviation) | μ; σ2 | The sum or average of many small, independent effects | Measurement error, sample means, regression residuals |
| Student's t | Continuous | ν (degrees of freedom) | 0 if ν > 1; ν/(ν - 2) if ν > 2 | A standardized mean when σ is estimated from a small sample | t-tests and confidence intervals with small n |
| Uniform | Continuous (a discrete version also exists) | a, b (the ends of the range) | (a + b)/2; (b - a)2/12 | Every value in an interval is equally likely | Random number generation, simulation inputs, flat priors |
| Binomial | Discrete | n (trials), p (success probability) | np; np(1 - p) | Successes in a fixed number of independent yes/no trials | Conversions out of n visitors, defects in a batch |
| Poisson | Discrete | λ (average count per interval) | λ; λ | Independent events in a fixed interval at a steady average rate | Arrivals, calls, failures per day, defects per square metre |
| Power law (Pareto; Zipf when discrete) | Usually continuous | α (density exponent), xmin (where the law starts) | Finite only if α > 2; finite only if α > 3 | Rich-get-richer or multiplicative growth: most values small, a few enormous | City sizes, word frequencies, wealth, the tail of transaction sizes |
Before you plug numbers into any software, check its parameters. NIST warns that different sources may give formulas that look different from its own. Sometimes the versions are mathematically equivalent, and sometimes they use a different parameterization.[3] SciPy's normal distribution, for example, takes the standard deviation as its scale argument, not the variance. Its exponential distribution takes a scale equal to 1/λ rather than the rate λ. Passing a variance where a standard deviation belongs is a silent error. Nothing crashes, and every probability you compute is wrong.
Binomial and Poisson distributions: two ways to count
The Binomial distribution describes the number of successes when you repeat a yes/no trial a fixed number of times. OpenStax lists the conditions. There must be a fixed number of trials, n. Each trial has only two outcomes, success with probability p or failure with probability q = 1 - p. The n trials must be independent and repeated under identical conditions.[2] The PMF counts the ways to arrange k successes among n trials and multiplies by the probability of any one arrangement:
P(X = k) = C(n, k) pk (1 - p)n - k, where C(n, k) = n! / (k! (n - k)!)
The mean of X is μ = np, and the standard deviation is the square root of npq. Worked example: Harbor Pay audits a random sample of 40 disputes each day. Historically, 5 percent of disputes turn out to have been filed by mistake. Let X be the number of mistaken disputes in today's audit.
- Mean: np = 40 × 0.05 = 2. Standard deviation: √(40 × 0.05 × 0.95) = √1.9 = 1.38.
- P(X = 0) = 0.9540 = 0.1285. On about one audit day in eight, nobody filed by mistake.
- P(X = 2) = C(40, 2) × 0.052 × 0.9538 = 780 × 0.0025 × 0.1424 = 0.2777.
The Poisson distribution needs no fixed number of trials. It gives the probability of a number of events occurring in a fixed interval of time or space, provided the events happen at a known average rate.[2] The events must also occur independently of the time since the last event, so one dispute does not make the next one more or less likely. Its PMF has a single parameter, λ, the average count per interval:
P(X = k) = e-λ λk / k!
The Poisson distribution has one striking property: its mean and its variance both equal λ. That gives you a quick diagnostic. If hourly dispute counts average 3 but their variance is 9, the counts are overdispersed. Something is making events cluster, perhaps one compromised merchant triggering a burst of disputes. A Poisson model would then underestimate the bad hours. A negative binomial model, which lets the variance exceed the mean, is the usual next step.
The two counting distributions are related. OpenStax gives a rule of thumb: the Poisson distribution may be used to approximate the binomial when the probability of success is small, at or below 0.05, and the number of trials is large, at least 20.[2] The audit example meets both conditions, with p = 0.05 and n = 40, so set λ = np = 2 and compare:
| k | Binomial P(X = k) | Poisson P(X = k) |
|---|---|---|
| 0 | 0.1285 | 0.1353 |
| 1 | 0.2706 | 0.2707 |
| 2 | 0.2777 | 0.2707 |
| 3 | 0.1851 | 0.1804 |
| 4 | 0.0901 | 0.0902 |
| P(X ≤ 4) | 0.9520 | 0.9473 |
Now solve the pager problem. Disputes arrive at λ = 3 per hour. Compute each PMF value, then keep a running total. That total is the CDF.
| k | P(X = k) = e-3 3k/k! | F(k) = P(X ≤ k) |
|---|---|---|
| 0 | 0.0498 | 0.0498 |
| 1 | 0.1494 | 0.1991 |
| 2 | 0.2240 | 0.4232 |
| 3 | 0.2240 | 0.6472 |
| 4 | 0.1680 | 0.8153 |
| 5 | 0.1008 | 0.9161 |
| 6 | 0.0504 | 0.9665 |
| 7 | 0.0216 | 0.9881 |
| 8 | 0.0081 | 0.9962 |
"Six or more" is the complement of "five or fewer": P(X ≥ 6) = 1 - F(5) = 1 - 0.9161 = 0.0839. Over 24 hours that gives 24 × 0.0839 ≈ 2.0 pages a day. With a threshold of 8, P(X ≥ 8) = 1 - F(7) = 1 - 0.9881 = 0.0119. That is 24 × 0.0119 ≈ 0.29 pages a day, or one page every 1/0.29 ≈ 3.5 days. Before trusting either number, compare the variance of the real hourly counts with their mean. If disputes cluster, the true page rate will be higher than these figures.
Normal distribution and Student's t-distribution: the bell curve and its heavier-tailed cousin
The Normal distribution is the symmetric bell curve. Its PDF, for mean μ and variance σ2, is:
f(x) = (1 / (σ √(2π))) exp( -(x - μ)2 / (2σ2) )
About 68 percent of its probability lies within one standard deviation of the mean, 95 percent within 1.96 standard deviations, and 99.7 percent within three. The normal distribution appears so often because of the central limit theorem: the average of many independent values with finite variance is approximately normal, whatever the shape of the individual values. That condition, finite variance, matters. The power-law section below shows a distribution without it.
Student's t-distribution appears when you standardize a sample mean using the sample standard deviation s instead of the unknown true σ. For normal data, the statistic (Ȳ - μ) / (s / √n), where Ȳ is the sample mean, follows a t-distribution with n - 1 degrees of freedom. It looks like the normal but has heavier tails, because s is itself uncertain when n is small. As the degrees of freedom grow, s becomes a reliable stand-in for σ and the t-distribution approaches the normal. You saw the consequence in Lesson 1's t-tests: small samples need a larger critical value.
| Degrees of freedom | Value leaving 2.5 percent in the upper tail |
|---|---|
| 4 (n = 5) | 2.776 |
| 9 (n = 10) | 2.262 |
| 29 (n = 30) | 2.045 |
| Infinite (the normal) | 1.960 |
At one degree of freedom, the t-distribution is the Cauchy distribution, whose tails are so heavy that it has no mean at all. NIST's handbook shows what that does to two summary statistics you will meet properly in Step 3: skewness, which measures asymmetry, and kurtosis, which measures how heavy the tails are. NIST generated 10,000 values from a Cauchy distribution, which is perfectly symmetric and so should show skewness near zero, yet the sample skewness came out at 69.99 and the kurtosis at 6,693.[4] A handful of enormous tail values produced those numbers. A summary statistic is only meaningful if the moment it estimates exists.
Continuous uniform distribution: the distribution inside every simulation
The Continuous uniform distribution on an interval from a to b gives every value the same density, f(x) = 1/(b - a). Its CDF is a straight ramp, F(x) = (x - a)/(b - a). Its mean is the midpoint, (a + b)/2, and its variance is (b - a)2/12. It has no tails at all, so it sits at the light-tailed extreme: its kurtosis, the tail-weight measure defined in Step 3, is lower than that of almost any distribution you will meet. A fair die is its discrete cousin: six values, each with probability 1/6.
You rarely meet uniform data in the wild, but you use the uniform distribution constantly. A computer's random number generator produces uniform draws between 0 and 1, and every other distribution is built from them. The basic method is inverse transform sampling. If U is uniform on 0 to 1 and F is any CDF, then F-1(U) has the distribution F. For a discrete distribution, you walk down the CDF column and stop at the first value whose cumulative probability reaches U.
Try it with the Poisson table above. Suppose the generator gives U = 0.93. F(5) = 0.9161 is below 0.93, and F(6) = 0.9665 is the first value at or above it, so the simulated hour has 6 disputes. For U = 0.40, F(1) = 0.1991 is too small and F(2) = 0.4232 is enough, so the hour has 2 disputes. Feed in thousands of uniform draws and the simulated counts follow Poisson(3). The same idea drives Monte Carlo simulation, the interpolation step in the Synthetic Minority Oversampling Technique (SMOTE, an oversampling method taught in Step 9), and the flat prior in a Bayesian analysis that wants to express no preference among values in a range.
Power law: when the tail is the story
A Power law distribution has a density proportional to a negative power of x, above some starting point xmin:
f(x) = C x-α for x ≥ xmin, with C = (α - 1) xminα - 1, and P(X > x) = (x / xmin)-(α - 1)
Take logs and you get log f(x) = log C - α log x. On a plot with logarithmic axes, the density is a straight line with slope -α. The tail probability has a second useful property: multiplying x by 10 always divides P(X > x) by the same factor, 10α - 1. The distribution has no typical size, which is why power laws are called scale-free.
In software and in most working documents you will not find a function called "power law". The continuous version above is the Pareto distribution (type I), and the discrete version used for ranked counts such as word frequencies is the Zipf distribution, behind Zipf's law. Here the parameterization trap from Step 2 returns. Many libraries describe a Pareto distribution by the exponent of its tail probability, α - 1, often called the shape or b, rather than by the density exponent α. SciPy's pareto function, for example, takes b = α - 1. A density exponent of 2.5 is a shape of 1.5, and confusing the two changes whether the mean exists.
Worked example: suppose Harbor Pay's dispute amounts above xmin = $100 follow a power law with density exponent α = 2.5. Then α - 1 = 1.5.
- P(amount > $1,000) = (1,000/100)-1.5 = 10-1.5 = 0.0316, about 1 dispute in 32.
- P(amount > $10,000) = 100-1.5 = 0.001, about 1 in 1,000. Each tenfold step divides the probability by 101.5 ≈ 31.6.
- Mean = xmin (α - 1)/(α - 2) = 100 × 1.5 / 0.5 = $300. The mean is finite because α > 2.
- The variance needs α > 3, so here it is infinite. The sample variance never settles: every so often a giant dispute arrives and the estimate jumps.
That last line has practical consequences. Without finite variance, the central limit theorem does not apply in its usual form, a t-test on raw amounts is unreliable, and a model that minimizes squared error is dominated by a handful of rows. A straight line on a log-log plot is suggestive, not proof. A lognormal distribution can look nearly straight over a wide range. Practitioners estimate α by maximum likelihood above a chosen xmin and compare the fit against alternatives before calling anything a power law.
The upshot: choose the family from how the data arise. Fixed trials point to the binomial, a steady rate in an interval to the Poisson, sums of many small effects to the normal, a small sample with estimated spread to the t, equal chances to the uniform, and a few giants among many small values to a power law. Then check that the assumption about the moments holds.
Step 3: Read the shape with skewness and kurtosis
Skewness measures symmetry, or more precisely the lack of it.[4] NIST gives the Fisher-Pearson coefficient for data Y1 to YN:
g1 = [ Σ (Yi - Ȳ)3 / N ] / s3
Here Ȳ is the mean and s is the standard deviation computed with N, not N - 1, in the denominator. Cubing keeps the sign of each deviation and exaggerates large ones, so a long right tail produces a positive value. A normal distribution has skewness 0, negative values mean a longer left tail, and positive values mean a longer right tail. A quick check: in right-skewed data the mean usually sits above the median.
Worked example: five dispute amounts, in hundreds of dollars, are 1, 2, 3, 4 and 10. The mean is 20/5 = 4.
| Y | Y - Ȳ | (Y - Ȳ)2 | (Y - Ȳ)3 | (Y - Ȳ)4 |
|---|---|---|---|---|
| 1 | -3 | 9 | -27 | 81 |
| 2 | -2 | 4 | -8 | 16 |
| 3 | -1 | 1 | -1 | 1 |
| 4 | 0 | 0 | 0 | 0 |
| 10 | 6 | 36 | 216 | 1,296 |
| Sum | 0 | 50 | 180 | 1,394 |
- Variance with N in the denominator: s2 = 50/5 = 10, so s = 3.162 and s3 = 31.62.
- Third moment: 180/5 = 36. Skewness g1 = 36/31.62 = 1.14, clearly right-skewed. The single value of 10 does almost all the work.
- Many programs report an adjusted coefficient, G1, which multiplies g1 by √(N(N - 1))/(N - 2). NIST lists the factor as 1.49 for N = 5, 1.19 for N = 10 and 1.08 for N = 20, approaching 1 as N grows.[4] Here G1 = 1.49 × 1.14 = 1.70. Two tools can therefore disagree by half on a small sample and both be right.
Kurtosis measures whether data are heavy-tailed or light-tailed relative to a normal distribution.[4] It is the fourth standardized moment, [Σ (Yi - Ȳ)4 / N] / s4. The fourth power makes it respond to tails and outliers, not to the height of the peak, despite what older textbooks say about "peakedness." The normal distribution has kurtosis 3. In NIST's sample of 10,000 normal values, the skewness was 0.03 and the kurtosis was 2.96.[4] Because 3 is the reference point, many tools subtract it and report excess kurtosis, so a normal sample shows about 0. NIST warns that many sources use the word kurtosis when they are actually computing excess kurtosis.[4] Before you interpret a kurtosis value, find out which convention produced it.
For the five amounts, the fourth moment is 1,394/5 = 278.8 and s4 = 100, so the kurtosis is 2.79 and the excess kurtosis is -0.21. That seems strange for data with an obvious outlier, but five points are far too few for a fourth moment to mean anything. Kurtosis estimates need large samples. In small ones, look at the histogram.
When skewness or kurtosis is large, you have two options. The first is to transform the data. NIST notes that taking the log or square root of a data set is often useful when the data show moderate right skewness.[4] The Box-Cox family of power transformations generalizes that idea. The second option is to model with a distribution that fits the shape, such as the power law or lognormal for heavy right tails.
Homoskedasticity and heteroskedasticity: does the spread stay put?
These terms are usually applied to a model's errors, that is, to the variance of y given x. Write a regression as y = β0 + β1x + ε, where ε is the error. Homoskedasticity means the error variance is the same at every value of x: Var(ε | x) = σ2. Heteroskedasticity means the error variance changes with x. You will also see the spellings homoscedasticity and heteroscedasticity, which mean the same things.
Harbor Pay fits ordinary least squares (OLS) regression to predict the loss on a dispute from the transaction amount, then groups the residuals by amount band (fictional figures):
| Amount band | Disputes in band | Mean residual | Residual standard deviation |
|---|---|---|---|
| Under $100 | 4,100 | $0 | $9 |
| $100 to $1,000 | 2,300 | $1 | $62 |
| $1,000 to $10,000 | 310 | -$4 | $480 |
The mean residual is near zero in every band, so the line is not systematically off. The spread, though, grows about fiftyfold. On a plot of residuals against fitted values, this looks like a megaphone opening to the right. Here is what it does and does not break:
- Not broken: if the model is otherwise correct, the OLS coefficient estimates remain unbiased. Heteroskedasticity does not make the slope wrong on average.
- Broken: the usual standard-error formula assumes a single σ2. The standard errors, t-statistics, p-values and confidence intervals are therefore unreliable. OLS is also no longer the most efficient estimator, and prediction intervals are too wide for small amounts and too narrow for large ones.
- Detect it with a residual-versus-fitted plot, or formally with the Breusch-Pagan or White test.
- Fix it by modeling log(loss) instead of loss, by weighted least squares with weights proportional to 1/variance, or by keeping OLS and reporting heteroskedasticity-consistent (robust) standard errors.
The distributions above predict some heteroskedasticity. Poisson counts have variance equal to their mean, so a model of counts is heteroskedastic by nature: busy hours vary more than quiet ones. Time-series data raise a related problem when the variance itself changes over time, with calm periods and volatile periods arriving in clusters.
Step 4: Update the probability with Bayes' rule
Harbor Pay's fraud model raises an alert on a transaction. How likely is the transaction to be fraud? Borrow the numbers from a worked example in Will Penny's Bayesian inference notes at University College London, which takes a disease with a prevalence of ten percent and a test with a sensitivity of 95 percent.[5] The same example gives the test a specificity of 85 percent. Translated to fraud: 10 percent of scored transactions are fraudulent, the model alerts on 95 percent of frauds, and it correctly clears 85 percent of legitimate transactions, so it falsely alerts on the other 15 percent.
Bayes' theorem, which the exam calls Bayes' rule, reverses a conditional probability:
P(fraud | alert) = P(alert | fraud) × P(fraud) / P(alert)
Penny calls P(fraud) the prior and P(alert | fraud) the likelihood.[5] The denominator is called the evidence, or the marginal likelihood. It is the total probability of an alert from either source:
P(alert) = 0.95 × 0.10 + 0.15 × 0.90 = 0.095 + 0.135 = 0.230, so P(fraud | alert) = 0.095 / 0.230 = 0.413
The same result is easier to see in natural frequencies. Picture 1,000 scored transactions:
| Alert | No alert | Total | |
|---|---|---|---|
| Fraud | 95 | 5 | 100 |
| Legitimate | 135 | 765 | 900 |
| Total | 230 | 770 | 1,000 |
Of 230 alerts, 95 are fraud: 41.3 percent. The model catches 95 percent of fraud, yet most of its alerts are false, because legitimate transactions outnumber frauds nine to one. A small false-alarm rate applied to a large group can outweigh a high hit rate applied to a small one. If this looks familiar from Lesson 2, it should: P(fraud | alert) is the model's precision, also called positive predictive value, and Bayes' rule shows why precision depends on the base rate while sensitivity does not.
Step 5: Turn the probability into a decision with expected value
The Expected value of a random variable is its probability-weighted average. OpenStax describes it as a prediction of the long-term results of a statistical experiment repeated many times.[2] For a discrete variable, E[X] = Σ x p(x). For a continuous one, E[X] = ∫ x f(x) dx. Check it on the Poisson table: 0(0.0498) + 1(0.1494) + 2(0.2240) + 3(0.2240) + 4(0.1680) + 5(0.1008) + 6(0.0504) + 7(0.0216) + 8(0.0081) = 2.96. The values from 9 upward supply the missing 0.04, and the total is λ = 3. An expected value need not be a possible outcome: no hour has 2.96 disputes.
Expected value is linear: E[aX + bY] = aE[X] + bE[Y], whether or not X and Y are independent. That makes totals easy. Disputes arrive at 3 an hour, so 72 a day. With independent amounts averaging $300, the expected daily dispute loss is 72 × $300 = $21,600.
Now the decision. Suppose declining a legitimate transaction costs about $60 in lost margin and customer goodwill, and approving a fraudulent one costs about $200 (fictional figures). For an alerted transaction, P(fraud) = 0.413.
| Action | Cost if fraud | Cost if legitimate | Expected cost at P(fraud) = 0.413 |
|---|---|---|---|
| Approve | $200 | $0 | 0.413 × $200 = $82.61 |
| Decline | $0 | $60 | 0.587 × $60 = $35.22 |
Declining has the lower expected cost, so the policy is to decline alerted transactions. The break-even point is where the two expected costs are equal: p × 200 = (1 - p) × 60, so p = 60/260 = 0.231. Above a posterior of 23.1 percent, decline. Below it, approve.
Expected value has two limits. It ignores spread: two policies with the same expected cost can have very different worst days. And it assumes the mean exists, which fails for a power law with α ≤ 2. The worst days are what Monte Carlo simulation measures.
The upshot: Bayes' rule turns a model's hit and false-alarm rates into the probability you actually need, and expected value turns that probability into an action. The prior can move the posterior across the break-even line by itself.
Step 6: Simulate what you cannot solve: Monte Carlo simulation
Harbor Pay's finance team wants to know the daily dispute loss it will exceed on 1 day in 100: the 99th percentile. The expected value is $21,600, but no tidy formula gives the percentiles of a Poisson number of power-law amounts. A Monte Carlo method estimates such a quantity by brute repetition. You draw random inputs from the distributions you assume, compute the output, repeat many thousands of times, and summarize the outputs as if they were data.
import numpy as np
rng = np.random.default_rng(seed=410) # fixed seed: the same draws on every run
N_DAYS = 10_000 # number of simulated days
lam_day = 72 # 3 disputes per hour x 24 hours
alpha, x_min = 2.5, 100.0 # power-law tail for dispute amounts
daily_loss = np.empty(N_DAYS)
for d in range(N_DAYS):
n = rng.poisson(lam_day) # how many disputes today
u = rng.uniform(size=n) # n uniform draws on [0, 1)
amounts = x_min * (1 - u) ** (-1 / (alpha - 1)) # inverse-CDF sampling
daily_loss[d] = amounts.sum()
print(daily_loss.mean())
print(np.percentile(daily_loss, [50, 95, 99]))
Every idea from Steps 1 and 2 appears in those lines. The Poisson distribution supplies the count. Uniform draws are turned into power-law amounts by inverting the CDF: set u = F(x) = 1 - (x/xmin)-(α - 1) and solve for x. The seed makes the run reproducible, so a colleague can check it. Before reading the percentiles, check that the output agrees with what you already know:
- The simulated mean should land near $21,600. Expect it to wander more than usual between seeds, because the amounts have infinite variance.
- The median day should fall below the mean, because a few huge disputes pull the mean up.
- Simulated hours, if you record them, should exceed 5 disputes about 8.4 percent of the time, matching the CDF calculation.
Monte Carlo estimates carry their own sampling error, and you can compute it. An estimated probability p from N independent runs has standard error √(p(1 - p)/N). For the pager probability, p = 0.084 and N = 10,000 give √(0.084 × 0.916 / 10,000) = 0.0028, so the estimate is good to about ±0.005 at 95 percent confidence. The error shrinks with √N, so halving it takes four times as many runs. Rare-tail quantities such as a 99th percentile need far more runs than the mean does.
The weakness of Monte Carlo is that it cannot be better than its inputs. If disputes really arrive in bursts, Poisson inputs will understate bad days however many runs you do. The same machinery generates synthetic data sets for testing pipelines, runs power analyses before experiments, plans capacity, and underlies the sampling methods of Bayesian computation.
Step 7: Measure uncertainty from the data itself: bootstrapping
The team has 250 real dispute amounts from last month and reports a median of $142. How precise is that? No simple textbook formula gives the standard error of a median from skewed data. Bootstrapping answers the question by treating the sample as a stand-in for the population:
- Draw 250 values from the 250 observed amounts with replacement, so some amounts appear twice or more and others not at all.
- Compute the median of that resample.
- Repeat thousands of times, for example B = 5,000.
- The spread of the 5,000 medians estimates the sampling variability of the median. Its 2.5th and 97.5th percentiles form a 95 percent percentile confidence interval.
A tiny illustration: from the sample 40, 55, 70, 120, 900, one resample might be 55, 55, 120, 900, 40, with median 55. Another might be 70, 900, 900, 40, 120, with median 120. The medians differ because each resample includes different points. On average, a resample of size n leaves out a fraction (1 - 1/n)n of the original points, which approaches e-1 ≈ 36.8 percent. That variation between resamples stands in for the variation between real samples.
medians = np.empty(5_000)
for b in range(5_000):
resample = rng.choice(amounts, size=amounts.size, replace=True)
medians[b] = np.median(resample)
low, high = np.percentile(medians, [2.5, 97.5]) # 95 percent percentile interval
Bootstrapping and Monte Carlo both repeat a random draw thousands of times, so they are easily confused. The difference is where the randomness comes from.
| Question | Monte Carlo simulation | Bootstrapping |
|---|---|---|
| Draws come from | Distributions you assume | The observed sample, with replacement |
| It answers | What outcomes a model produces | How much a statistic varies from sample to sample |
| It needs | A trustworthy model of the inputs | A representative sample of independent observations |
| Typical output | A loss distribution, a probability of overrun | A standard error or confidence interval |
| It goes wrong when | The assumed inputs are wrong | Data are dependent, n is tiny, or the statistic is an extreme such as the maximum |
The bootstrap does not create information. It cannot produce a value larger than the largest one observed. That is why it handles extremes and heavy tails badly, and why, for the power-law amounts, a bootstrap of the median is trustworthy while a bootstrap of the mean is not. Time series break the independence assumption, so they need a block bootstrap that resamples runs of consecutive observations. Lesson 15, on tree-based models, reuses the idea: a random forest trains each tree on a bootstrap sample, a technique called bagging.
Step 8: Audit the holes: three types of missing data
Three of Harbor Pay's columns contain blanks. Statisticians describe Missing data with an indicator R that records whether each value was observed, and they ask what R depends on. Marina Meila's University of Washington lecture notes give the definitions. Under MCAR, missing completely at random, the missingness is independent of any variables.[6] Under MAR, missing at random, the missingness depends only on what is observed.[6] When missingness is neither MCAR nor MAR, it is called MNAR, missing not at random.[6] In MNAR, whether a value is missing depends on the unobserved value itself.
| Column | What the team found | Mechanism | Safe handling |
|---|---|---|---|
| device_id | A logging sampler dropped the field for a random 2 percent of events, unrelated to any value | MCAR | Dropping incomplete rows is unbiased; you lose 2 percent of the rows and some power |
| billing_zip | Blank far more often for mobile-app orders (the channel is recorded); within each channel, unrelated to the ZIP itself | MAR | Impute using channel and other observed columns; do not simply drop rows |
| merchant_refund_rate | Self-reported at onboarding; merchants with high refund rates tend to leave it blank | MNAR | Get the value from another source, model the missingness, run a sensitivity analysis, add a missing-value indicator |
Why the mechanism matters: under MCAR, Meila's notes say you can ignore the rows with missing values and use the sample median of the rest as an estimate.[6] The complete rows are a random subsample. Under MAR you cannot, because the missingness may depend on an observed variable X.[6] If the complete rows have a different mix of X, here more web orders and fewer mobile ones, statistics from them are biased. The fix is to impute each missing value from its observed neighbors, for example by drawing a ZIP from complete records with the same channel and region, or by multiple imputation, which creates several filled-in data sets so the uncertainty of the fill is carried forward.
MNAR is the hard case. The blanks hide exactly the high refund rates, and no amount of modeling the observed columns can recover what was never seen. You can only bring in outside information, such as refund data from the card networks, or report how the conclusions change under different assumptions about the missing values. A missing-value indicator column is often useful here, because the fact of leaving the field blank predicts risk.
You can partly test the boundary between MCAR and MAR: fit a model predicting R from the observed columns. If channel predicts missingness, the data are not MCAR. The boundary between MAR and MNAR cannot be tested from the data alone, because it concerns values you do not have. It rests on knowledge of how the data were collected. That is why the exam frames missingness questions as scenarios. The mechanism is in the story, not in the spreadsheet.
Step 9: Split and rebalance: stratified sampling and oversampling
Harbor Pay's labeled training data has 10,000 transactions, of which 100 (1 percent) are fraud. This is class imbalance. Lemaître, Nogueira and Aridas, the authors of the imbalanced-learn toolbox, note that imbalanced data substantially compromise learning, because most standard machine learning algorithms expect a balanced class distribution.[7] Imbalance causes two separate problems, each with its own remedy.
Problem one: the test set may not represent the minority class. Hold out 25 percent at random, 2,500 rows. The number of frauds that land in the test set follows a hypergeometric distribution, because you sample without replacement from the combined groups.[2] With r = 100 frauds among N = 10,000 rows and a sample of n = 2,500, the mean is 25 and the variance is 2,500 × 0.01 × 0.99 × (7,500/9,999) = 18.6, a standard deviation of 4.3. Roughly 95 percent of random splits put between 16 and 34 frauds in the test set. A recall measured on 16 frauds and a recall measured on 34 are not equally trustworthy, and the training set loses whatever the test set took.
Stratified sampling removes that luck. You divide the population into groups called strata, here fraud and legitimate, and sample the same fraction within each. In scikit-learn's train_test_split, passing the class labels to the stratify parameter makes the function split the data in a stratified fashion on those labels.[8] Passing an integer as random_state makes the split reproducible from run to run.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
# test set: 25 fraud + 2,475 legitimate; training set: 75 fraud + 7,425 legitimate
The same idea gives stratified k-fold cross-validation. In surveys, stratification also allows disproportionate allocation: a small subgroup can be deliberately oversampled so it has enough respondents, then weighted back to its population share during analysis.
Problem two: the model barely sees the minority class. With 75 frauds against 7,425 legitimate rows, a classifier can reach 99 percent accuracy by never predicting fraud. Oversampling balances the data by generating new minority-class samples until a chosen ratio is reached.[7] Random oversampling simply duplicates existing minority rows. The Synthetic Minority Oversampling Technique (SMOTE) was published by Chawla, Bowyer, Hall and Kegelmeyer.[7] Instead of duplicating, it creates new rows. It picks a minority point xi, picks one of its nearest minority neighbors xnn, draws λ uniformly between 0 and 1, and places a synthetic point on the line between them: xnew = xi + λ (xnn - xi).
from imblearn.over_sampling import SMOTE
X_res, y_res = SMOTE(random_state=42).fit_resample(X_train, y_train)
# training only: 75 real frauds grow to 7,425 (7,350 synthetic); the test set is untouched
The order of operations is the whole game. Split first, then oversample only the training data. Inside cross-validation, oversample within each training fold. If you run SMOTE before splitting, synthetic points interpolated from test-set frauds end up in training. The model has then effectively seen the test cases, and the test metrics are inflated. Even done correctly, 7,350 synthetic frauds built from 75 real ones is about 98 synthetic rows per real fraud, so the model can memorize a small region. The imbalanced-learn authors warn that over-sampling can lead to overfitting, which cleaning under-sampling methods can help avoid.[7] The alternatives are undersampling the majority class, using class weights in the loss function, and moving the decision threshold. Whatever you choose, judge the result with precision, recall and the other Lesson 2 metrics on an untouched, stratified test set.
The upshot: stratification keeps class proportions honest across splits, and oversampling changes the training mix. Stratify the split, then oversample only the training portion.
Second run: a new merchant segment flips the decision
Harbor Pay now signs a grocery chain. The same fraud model scores its transactions, with the same 95 percent sensitivity and 85 percent specificity. Grocery fraud is rarer, though: 1 percent of scored transactions instead of 10. That one input changes. Run Steps 4 and 5 again with 10,000 transactions:
| Alert | No alert | Total | |
|---|---|---|---|
| Fraud | 95 | 5 | 100 |
| Legitimate | 1,485 | 8,415 | 9,900 |
| Total | 1,580 | 8,420 | 10,000 |
P(fraud | alert) = 95/1,580 = 0.060. The expected cost of approving is 0.060 × $200 = $12.03, and the expected cost of declining is 0.940 × $60 = $56.39. Approving, or sending the alert to a cheap manual review, now wins by a wide margin. The posterior of 6.0 percent sits far below the 23.1 percent break-even line. The model has not changed at all, only the prior.
What would bring the decline policy back? The posterior must reach 0.231. Write the false-alarm rate as FPR (false positive rate) and solve 0.0095 / (0.0095 + 0.99 × FPR) ≥ 0.231. Multiplying out gives 0.0095 × 0.769 ≥ 0.231 × 0.99 × FPR, so FPR ≤ 0.0073/0.2287 = 0.032. The model would need a specificity of at least 96.8 percent for this segment. That is a concrete target for the modeling team, derived from Bayes' rule and expected value alone.
The change ripples through the other steps. The Poisson rate in the Monte Carlo inputs drops, so loss percentiles must be recomputed. With 1 fraud in 100, stratification matters more: an unstratified test set might hold only a dozen grocery frauds. Steps 1 and 2 stay the same, because the type of variable and the way it arises have not changed. A good procedure tells you which conclusions survive a change and which you must redo.
Exam cues: words in the stem and where they point
| The stem says | Points to | Often confused with |
|---|---|---|
| Count of events per hour, day or area at a steady average rate | Poisson | Binomial, which needs a fixed number of trials |
| Number of successes out of n independent trials with the same p | Binomial | Poisson |
| Small sample, population standard deviation unknown | t-distribution | Normal |
| Every value in a range equally likely; random number generator | Uniform | Normal |
| A few items account for most of the total; straight line on a log-log plot; Pareto or Zipf | Power law | Lognormal or normal |
| Lack of symmetry; mean pulled above the median; long right tail | Positive skewness | Kurtosis |
| Heavy tails or outliers relative to a normal distribution | High kurtosis | Skewness or large variance |
| Residual spread fans out as fitted values grow | Heteroskedasticity | Multicollinearity or autocorrelation |
| Probability of an exact count | PMF | |
| Probability of "at most" or "at least" a value; percentile | CDF | PMF or PDF |
| Prior, likelihood, base rate, update after new evidence | Bayes' rule | Expected value |
| Probability-weighted average payoff; long-run average | Expected value | Median or most likely value |
| Repeatedly simulate from assumed distributions | Monte Carlo simulation | Bootstrapping |
| Resample the observed data with replacement | Bootstrapping | Monte Carlo or cross-validation |
| Missingness unrelated to any variable | MCAR | MAR |
| Missingness explained by another recorded column | MAR | MCAR or MNAR |
| Missingness depends on the missing value itself | MNAR | MAR |
| Keep class proportions equal in training and test sets | Stratification | Oversampling |
| Create extra or synthetic minority examples | Oversampling (SMOTE) | Stratification or undersampling |
Common misconceptions
- "A PDF value of 2.5 must be an error, since probabilities cannot exceed 1." A density is not a probability. Only areas under the PDF are probabilities. A uniform distribution on 0 to 0.25 has density 4 throughout.
- "Kurtosis measures how pointed the peak is." Kurtosis is the fourth standardized moment and responds to tails and outliers. Also check whether a tool reports kurtosis (normal = 3) or excess kurtosis (normal = 0).
- "Heteroskedasticity makes regression coefficients biased." In an otherwise correct model the coefficients stay unbiased. What breaks is the standard errors, and with them the p-values and confidence intervals.
- "Oversample first, then split, so both sets are balanced." That leaks information about test cases into training and inflates test metrics. Split with stratification, then oversample only the training data.
- "Bootstrapping and Monte Carlo are the same thing." Both repeat random draws, but Monte Carlo samples from assumed distributions while the bootstrap resamples the observed data. Neither can add information that is not in its inputs.
- "If the data look missing at random, dropping incomplete rows is fine." Only MCAR makes complete-case analysis unbiased. Under MAR, dropping rows biases estimates whenever the complete rows differ on observed variables, and MNAR cannot be detected from the data alone.
What to remember
- A PMF gives P(X = x) for counts and sums to 1. A PDF gives densities, can exceed 1, and gives probabilities only as areas. The CDF, F(x) = P(X ≤ x), answers threshold questions for both, and "at least k" is 1 - F(k - 1).
- Binomial: fixed n independent trials with the same p, mean np, variance np(1 - p). Poisson: events in a fixed interval at a steady rate, mean = variance = λ. Poisson approximates the binomial when p ≤ 0.05 and n ≥ 20.
- The t-distribution has heavier tails than the normal because σ is estimated, and it approaches the normal as degrees of freedom grow. At one degree of freedom it is the Cauchy distribution, which has no mean.
- A power law (Pareto when continuous, Zipf when discrete) with density exponent α has a finite mean only if α > 2 and a finite variance only if α > 3. Many libraries take the shape α - 1 instead of α.
- Skewness (third moment) measures asymmetry and is 0 for a normal distribution. Kurtosis (fourth moment) measures tail weight and is 3 for a normal, or 0 if reported as excess kurtosis.
- Heteroskedasticity leaves OLS coefficients unbiased but makes their usual standard errors unreliable. Fix it with a log transform, weighted least squares or robust standard errors.
- With 10 percent prevalence, 95 percent sensitivity and 85 percent specificity, P(positive is real) = 0.095/0.230 = 0.413. At 1 percent prevalence the same model gives 0.060.
- Monte Carlo simulation samples from assumed distributions, and its error shrinks with √N. Bootstrapping resamples observed data with replacement to estimate the variability of a statistic.
- MCAR: complete-case analysis is unbiased. MAR: impute from observed variables. MNAR: missingness depends on the hidden value and cannot be detected from the data alone. Stratify the split, then oversample only the training data.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- OpenStax. (n.d.). Introductory Statistics 2e, Chapter 4 Review (expected value, binomial, Poisson). openstax.org
- NIST. (n.d.). Gallery of Distributions (NIST/SEMATECH e-Handbook of Statistical Methods, 1.3.6.6). itl.nist.gov
- NIST. (n.d.). Measures of Skewness and Kurtosis (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- Will Penny. (n.d.). Bayesian Inference notes. University College London, Wellcome Centre for Human Neuroimaging. fil.ion.ucl.ac.uk
- Marina Meila. (2025). Lecture VII: Missing Data. University of Washington, Department of Statistics (STAT 403). sites.stat.washington.edu
- Lemaître, Nogueira, Aridas. (2017). Imbalanced-learn: A Python Toolbox to Tackle the Curse of Imbalanced Datasets in Machine Learning. Journal of Machine Learning Research. jmlr2020.csail.mit.edu
- scikit-learn. (n.d.). sklearn.model_selection.train_test_split. scikit-learn.org
- Key terms
- Probability mass function (PMF)
- For a discrete random variable, the function p(x) = P(X = x) giving the probability of each possible value; every value lies between 0 and 1 and all of them sum to 1.
- Probability density function (PDF)
- For a continuous random variable, a function f(x) whose area over an interval equals the probability of landing in that interval; a density value can exceed 1 and the probability of any single exact value is zero.
- Cumulative distribution function (CDF)
- The function F(x) = P(X <= x), defined for discrete and continuous variables alike; it rises from 0 to 1, never decreases, and its inverse gives percentiles.
- Excess kurtosis
- Kurtosis minus 3, so that a normal distribution scores 0; positive values indicate heavier tails and more outliers than a normal distribution, negative values lighter tails.
- Heteroskedasticity
- A condition in which a model's error variance changes with the predictors, for example residuals that fan out as fitted values grow; it leaves OLS coefficients unbiased but makes their usual standard errors unreliable.
- Missing at random (MAR)
- Missingness that depends only on observed variables, such as a field left blank more often on a recorded channel; dropping incomplete rows can bias results, so values are imputed from the observed variables.
- Missing not at random (MNAR)
- Missingness that depends on the unobserved value itself, such as high earners declining to report income; it cannot be detected or corrected from the observed data alone.
- Monte Carlo simulation
- Estimating a quantity by repeatedly drawing random inputs from assumed distributions, computing the output each time, and summarizing the many outputs; its error shrinks in proportion to one over the square root of the number of runs.
- Bootstrapping
- Estimating the sampling variability of a statistic by repeatedly resampling the observed data with replacement, recomputing the statistic each time, and using the spread of the results as a standard error or confidence interval.
- Stratification
- Dividing data into groups such as classes and sampling the same fraction within each, so that training and test sets keep the original class proportions.
The Linear Algebra and Calculus Behind Data Science
- Diagnose a singular or ill-conditioned feature matrix using rank, span, basis vectors, eigenvalues and trace, and explain why software uses a decomposition instead of an explicit inverse.
- Compute Euclidean, Manhattan and cosine distances and radial basis function similarity, and choose the right measure for a given data problem.
- Use partial derivatives, the chain rule, exponentials and logarithms to derive and carry out one gradient descent step for logistic regression.
Four invoices and a regression that will not solve
Invoice 1 in the fictional table below charged a net price of $10 plus $1 of tax, for a total of $11. Three more invoices follow the same pattern with different amounts. A colleague wants to predict how many days each invoice takes to be paid, and puts all three money columns into an ordinary least squares (OLS) regression. The software either refuses to fit, or it returns large coefficients with opposite signs that swing wildly when one row is dropped. Nothing is missing and nothing is mistyped. The problem is in the linear algebra.
| Invoice | Net price ($) | Tax ($) | Total price ($) | Days to pay |
|---|---|---|---|---|
| 1 | 10 | 1 | 11 | 14 |
| 2 | 20 | 4 | 24 | 21 |
| 3 | 30 | 3 | 33 | 25 |
| 4 | 40 | 2 | 42 | 30 |
Before you are halfway through, you will be able to name the cause in three equivalent ways. The feature matrix has deficient rank. A matrix built from it has an eigenvalue of zero. And that matrix has no inverse. After that, the same mathematics solves two other everyday problems: deciding which support tickets are "near" each other, and taking one training step for a churn model by hand.
Exam objectives: CompTIA DataX DY0-001 objective 1.3, "Explain the importance of linear algebra and basic calculus concepts."[1] The objective's linear algebra list has rank, span, trace, eigenvalues and eigenvectors, basis vectors, the identity matrix, and four matrix operations: multiplication, transposition, inversion and decomposition. It also lists four distance metrics (Euclidean, radial, Manhattan and cosine) and four calculus ideas (partial derivatives, the chain rule, exponentials and logarithms). The verb is "explain", so expect questions about why a concept matters in a modeling scenario, not long hand calculations. Working small examples is still the fastest way to see why.
Matrix and vector operations: the language of the failure
Data science stores each observation as a vector and a whole table of observations as a matrix. A vector is an ordered list of numbers, such as invoice 1's features (10, 1, 11). A matrix is a rectangular grid of numbers. The invoice feature matrix X has n = 4 rows (observations) and p = 3 columns (features), so its shape is 4 × 3. The target, days to pay, is a column vector y of shape 4 × 1.
Four vector operations come before any matrix work. You add two vectors of the same length entry by entry. You scale a vector by multiplying every entry by one number. The dot product of two equal-length vectors multiplies them entry by entry and adds the results. For the net and tax columns, (10, 20, 30, 40) · (1, 4, 3, 2) = 10 + 80 + 90 + 80 = 260. The Euclidean norm, or length, of a vector is the square root of its dot product with itself: ||x|| = sqrt(x · x). The norm comes back in the distance section.
Matrix multiplication is a collection of dot products. In the product AB, the entry in row i and column j is the dot product of row i of A with column j of B. That rule fixes the shapes: A must have as many columns as B has rows, and an (n × p) matrix times a (p × q) matrix gives an (n × q) result. It also means order matters. AB and BA are usually different, and often only one of them is defined. The prediction vector Xβ is a matrix-vector product, where β (beta) is the vector of coefficients. Each invoice's prediction is the dot product of its feature row with β.
Matrix transposition flips a matrix over its main diagonal so that rows become columns. XT ("X transpose") has shape 3 × 4. Two facts carry most of the weight in practice. First, the transpose of a product reverses the order: (AB)T = BTAT. Second, XTX is always square and symmetric. Its entry (j, k) is the dot product of feature column j with feature column k, and a dot product gives the same value whichever vector comes first.
| Expression | Shapes multiplied | Result shape | What the entries mean |
|---|---|---|---|
| Xβ | (4 × 3)(3 × 1) | 4 × 1 | One prediction per invoice |
| XT | none (a flip) | 3 × 4 | Each row is now one feature |
| XTX | (3 × 4)(4 × 3) | 3 × 3 | Dot products between feature columns |
| XXT | (4 × 3)(3 × 4) | 4 × 4 | Dot products between invoices |
| XTy | (3 × 4)(4 × 1) | 3 × 1 | Dot product of each feature with the target |
| I3 | none | 3 × 3 | 1 on the diagonal, 0 elsewhere |
The identity matrix I is the square matrix with 1 on the diagonal and 0 everywhere else. Multiplying by it changes nothing: AI = IA = A, just as multiplying a number by 1 changes nothing. Its columns are the standard basis vectors of the next section. Its main job is to define the inverse, and it appears directly in ridge regression, as you will see shortly.
Matrix inversion undoes a matrix. The inverse A-1 of a square matrix A is the matrix with AA-1 = A-1A = I. Not every square matrix has one. The determinant, a single number computed from a square matrix's entries that gives the factor by which the matrix scales area or volume, tells you whether a square matrix has an inverse.[2] The rule is that the matrix is invertible exactly when its determinant is not zero. A determinant of zero means the matrix flattens space into fewer dimensions, and a flattening cannot be undone. Computing an inverse means solving linear systems, one for each column of the result.[3] That cost, and the rounding error that comes with it, is why practitioners avoid explicit inverses. The decomposition section comes back to this.
Now put the invoice problem in this vocabulary. OLS chooses the coefficients β that minimize the residual sum of squares (RSS), the total of the squared gaps between y and the predictions Xβ. Setting the derivatives of RSS to zero (worked in the calculus section) gives the normal equations XTXβ = XTy. Their textbook solution is β = (XTX)-1XTy, so the fit needs the inverse of the 3 × 3 matrix XTX. Each entry below is a column dot product. For example, the net-with-net entry is 102 + 202 + 302 + 402 = 3000.
| Column | Net | Tax | Total |
|---|---|---|---|
| Net | 3000 | 260 | 3260 |
| Tax | 260 | 30 | 290 |
| Total | 3260 | 290 | 3550 |
Look at the third row: 3260, 290, 3550. It is exactly the first row plus the second (3000 + 260, 260 + 30, 3260 + 290). When one row of a square matrix is a combination of the others, its determinant is zero. So this matrix has no inverse, and the textbook formula cannot be evaluated. Being square was never enough.
So what?: XTX holds the dot products between your features, and OLS needs its inverse. When one feature is built from others, that inverse does not exist, so the coefficient formula breaks before any statistics come into it.
Span, basis vectors and rank: why the inverse did not exist
A linear combination of vectors multiplies each vector by a number and adds the results. Total price is the linear combination 1 × net + 1 × tax. The linear span of a set of vectors is everything you can build this way. Think of each column as a point in four-dimensional space, one dimension per invoice. The span of the net and tax columns is then a flat plane in that space, and the total column already lies in the plane. Adding total to the model gives the predictions no new direction to move in.
A set of vectors is linearly independent when none of them is a linear combination of the others. Put another way, the only weights that combine them into the zero vector are all zeros. The invoice columns are dependent, because 1 × net + 1 × tax - 1 × total = 0 in every row.
A vector space basis, or basis for short, is a linearly independent set of vectors that spans a space, and each member is a basis vector. The familiar example is the standard basis. Its i-th vector ei has a 1 in position i and 0 everywhere else. In three dimensions these are e1 = (1, 0, 0), e2 = (0, 1, 0) and e3 = (0, 0, 1), which are the columns of the 3 × 3 identity matrix. Once a basis is fixed, every vector in the space has exactly one set of coordinates, and the number of basis vectors is the dimension of the space. A basis does not have to be the standard one. Principal component analysis (PCA) is a change of basis: it describes each observation with new basis vectors that point along the directions of greatest variance.
The matrix rank, usually just called rank, is the dimension of the span of a matrix's columns, which is the largest number of linearly independent columns it has. You can find it by row reduction. Put the matrix in row echelon form, then count the pivots, the first nonzero entry in each nonzero row.[3] The invoice matrix reduces in two rounds:
Start After R2-2R1, R3-3R1, R4-4R1 After R4+R2
[10 1 11] [10 1 11] [10 1 11]
[20 4 24] [ 0 2 2] [ 0 2 2]
[30 3 33] [ 0 0 0] [ 0 0 0]
[40 2 42] [ 0 -2 -2] [ 0 0 0]
Two pivots, so the rank is 2. You get the same rank whether you count rows or columns, because for any matrix the row rank equals the column rank.[3] That is why the rank of an n × p matrix can never exceed the smaller of n and p. A matrix whose rank equals its number of columns has full column rank. The invoice matrix would need rank 3 and has only 2. XTX always has the same rank as X, so the 3 × 3 matrix in the previous section is stuck at rank 2 and cannot be inverted.
Span also shows what OLS does geometrically. Every possible prediction vector Xβ lies in the span of the columns of X, called the column space. OLS picks the point in that span closest to y. The distance from a point to a subspace is measured along the line segment that meets the subspace at a right angle.[4] So the OLS prediction is the foot of the perpendicular dropped from y onto the column space. This explains the strange coefficients. The span is the same plane whether the model uses two columns or three, so the fitted predictions are unique. The coefficients are not. If β fits, then β + t(1, 1, -1) fits exactly as well for any number t, because X(1, 1, -1) is the zero vector. A solver that has to pick one of infinitely many equally good coefficient vectors can pick a strange one.
So what?: rank deficiency does not make predictions worse. It makes coefficients non-unique, and that matters whenever someone reads a coefficient as the effect of a feature.
Eigenvalues and eigenvectors: the zero that names the culprit
An eigenvector of a square matrix A is a nonzero vector v that A only stretches or shrinks, without turning it: Av = λv. The number λ (lambda) is the matching eigenvalue. An eigenvalue of 2 doubles vectors in that direction. An eigenvalue of 0 collapses them to the zero vector.
Try the direction v = (1, 1, -1) on the invoice XTX:
Row 1: 3000(1) + 260(1) + 3260(-1) = 0
Row 2: 260(1) + 30(1) + 290(-1) = 0
Row 3: 3260(1) + 290(1) + 3550(-1) = 0
The result is the zero vector, so v is an eigenvector with eigenvalue 0. A square matrix has an eigenvalue of 0 exactly when it is singular (not invertible), so this is the same diagnosis from a third angle. It is also more useful than the word "singular", because the eigenvector names the culprit. Weights (1, 1, -1) on (net, tax, total) say that net + tax - total is zero in every row. When software reports a near-zero eigenvalue of XTX, look at its eigenvector to see which features are tangled together.
The matrix trace, or trace, of a square matrix is the sum of its diagonal entries. For the invoice XTX it is 3000 + 30 + 3550 = 6580. Two standard identities make the trace and the determinant quick checks on eigenvalues. The trace equals the sum of the eigenvalues, and the determinant equals their product. Here the product is 0, because one eigenvalue is 0, and the other two eigenvalues must add to 6580.
Eigenvalues also predict what an inverse will do. If A is invertible, A-1 has the reciprocal eigenvalues 1/λ, and they belong to the same eigenvectors as the eigenvalues of A.[4] An eigenvalue of 0 would need the reciprocal 1/0, which is another way to see that no inverse exists. A tiny eigenvalue turns into a huge one in the inverse, so the coefficient estimates swing wildly along that eigenvector's direction.
That is where one changed input flips the result. Suppose invoice 4's total had been keyed as $43 instead of $42. Total is no longer exactly net + tax, row reduction now finds three pivots, and X has full column rank 3. Formally, XTX is invertible and the fit "works". Now apply the same v = (1, 1, -1) to the new X: Xv = (0, 0, 0, -1). Two facts turn this into a bound on the smallest eigenvalue. First, vT(XTX)v = (Xv) · (Xv) = ||Xv||2, which is 1 here, while vTv = ||v||2 = 3. Second, for a symmetric matrix A, the smallest eigenvalue is the minimum of the ratio vTAv / vTv over all nonzero v (this ratio is called the Rayleigh quotient). Any particular v therefore gives an upper bound, so the smallest eigenvalue is at most 1/3. The new trace is 3000 + 30 + 3635 = 6665, so the largest eigenvalue is at least the average of the three, about 2222. The ratio of largest to smallest eigenvalue, called the condition number of XTX, is therefore at least 6665. Rank says the problem can be solved. The eigenvalues say it barely can. This is multicollinearity, which is usually measured feature by feature with the variance inflation factor (VIF).
The identity matrix supplies the standard repair. Ridge regression replaces XTX with XTX + αI for some positive α (alpha). Many texts write this constant as λ, which clashes with eigenvalue notation, so this lesson uses α. Adding αI adds α to every eigenvalue and keeps the same eigenvectors, because (A + αI)v = λv + αv. Even the zero eigenvalue becomes α, so the matrix becomes invertible. Choosing α is a validation question for later lessons on regularization.
Eigenvalues also drive PCA. The eigenvectors of a covariance matrix are the principal directions, and each eigenvalue is the variance of the data along its direction. The trace of a covariance matrix is the sum of the original features' variances, and it is also the sum of the eigenvalues. So the share of variance explained by component k is λk divided by the trace. With eigenvalues 8, 1.5 and 0.5 (trace 10), the first component explains 80 percent and the first two explain 95 percent. The same ratio is what practitioners use to decide how many components to keep.
So what?: a zero eigenvalue means singular, a near-zero eigenvalue means unstable, and the eigenvector tells you which combination of features is responsible. The trace lets you check eigenvalues quickly and turn them into explained-variance shares.
Matrix decomposition: solving without inverting
A matrix decomposition, also called a factorization, rewrites one matrix as a product of simpler matrices, much as 12 can be written 2 × 2 × 3. The simpler pieces are diagonal, triangular or orthogonal. An orthogonal matrix has columns of length 1 at right angles to each other. Each kind is cheap and numerically stable to work with.
Eigendecomposition writes A = SDS-1. The columns of S are eigenvectors, and D is a diagonal matrix of the eigenvalues. In a basis made of eigenvectors, the matrix becomes diagonal and therefore simple. Powers, for example, become easy: Ak = SDkS-1, where Dk just raises each diagonal entry to the k-th power. The catch is existence. An n × n matrix has an eigendecomposition when it has n linearly independent eigenvectors.[2] Having n distinct eigenvalues is enough to guarantee this.[4] Repeated eigenvalues, by contrast, can make a matrix defective, meaning it cannot be diagonalized at all.[2] The matrices data scientists decompose most often, covariance matrices and XTX, are real and symmetric. A real symmetric matrix always decomposes as QΛQT (capital lambda for the diagonal of eigenvalues), with orthonormal eigenvectors in Q. This result is called the spectral theorem.
Singular value decomposition (SVD) writes any matrix, square or not, as X = UΣVT. U and V have orthonormal columns. Σ (capital sigma) is diagonal, and its nonnegative entries are the singular values, usually listed largest first. Unlike eigendecomposition, the SVD always exists, even for non-square matrices.[2] Its properties tie together everything in this lesson so far:
- The rank of X equals the number of nonzero singular values. The invoice matrix has two nonzero singular values and one zero.
- The columns of V are eigenvectors of XTX, and the squared singular values are its eigenvalues.
- Keeping only the k largest singular values gives the best rank-k approximation of X. That is the basis of truncated SVD, of PCA computed on centered data, and of matrix-factorization recommenders such as those fitted by alternating least squares (ALS).
- Inverting only the nonzero singular values gives the pseudo-inverse. It solves rank-deficient least squares by choosing, out of the infinitely many coefficient vectors that fit equally well, the one with the smallest length.
Two more factorizations complete the set to recognize. QR decomposition writes X = QR, where Q has orthonormal columns and R is upper-triangular. OLS can then be solved from Rβ = QTy by back-substitution, without ever forming XTX. That matters because forming XTX squares the condition number of X, so a mildly ill-conditioned X becomes a badly ill-conditioned XTX.
Cholesky decomposition writes a symmetric positive-definite matrix A as LLT, with L lower-triangular. Positive-definite means xTAx > 0 for every nonzero vector x, which for a symmetric matrix is the same as all of its eigenvalues being positive. XTX is positive-definite exactly when X has full column rank, so the invoice matrix fails this test: its zero eigenvalue gives vT(XTX)v = 0. Cholesky is the fast route when XTX is well conditioned. It is also a common way to draw correlated samples from a multivariate normal distribution, the kind of synthetic data Lesson 3 discussed.
| Decomposition | Form | Exists for | Typical data science use |
|---|---|---|---|
| Eigendecomposition | A = SDS-1 | Square matrices with n independent eigenvectors | Matrix powers, Markov chain long-run behavior |
| Spectral (symmetric) form | A = QΛQT | Every real symmetric matrix | PCA on a covariance matrix, diagnosing XTX |
| SVD | X = UΣVT | Every real matrix, any shape | Rank, PCA, low-rank approximation, pseudo-inverse, recommenders |
| QR | X = QR | Every real matrix | Numerically stable OLS |
| Cholesky | A = LLT | Symmetric positive-definite matrices | Fast solves, correlated random sampling |
In code, the difference looks like this. The lines are NumPy-style pseudocode, not a specific library's exact signatures:
# fragile: forms X^T X, then inverts it explicitly
beta = inv(X.T @ X) @ X.T @ y
# sturdier: a least-squares solver factors X itself (QR or SVD)
beta = lstsq(X, y)
# ridge: solve the shifted system; still no explicit inverse
beta = solve(X.T @ X + alpha * I, X.T @ y)
So what?: the formula β = (XTX)-1XTy is for understanding, not for computing. Software solves the same problem through a decomposition, and the SVD in particular both reveals rank problems and keeps working when they are present.
Distance metrics: which support ticket is nearest?
A help desk wants to show agents the past ticket most like each new one. Each ticket becomes a vector of word counts. To call two tickets "similar", you need an operation that takes two vectors and returns one number measuring how alike they are. Different operations encode different ideas of "alike", so the choice of metric decides which ticket comes back. Here are three fictional tickets, counting the words "refund", "password" and "late":
| Ticket | Vector | Content |
|---|---|---|
| A | (2, 0, 1) | Short complaint: late order, wants refund |
| B | (4, 0, 2) | Same complaint written at twice the length |
| C | (0, 3, 1) | Password reset, mentions it is late at night |
The four measures in the objective, for vectors x and y with entries xi and yi:
| Measure | Formula | Range | What it responds to |
|---|---|---|---|
| Euclidean distance (L2) | sqrt(Σ(xi - yi)2) = ||x - y|| | 0 and up | Straight-line gap; squaring lets one large difference dominate |
| Manhattan distance (L1) | Σ|xi - yi| | 0 and up | Total gap summed along each axis, like walking city blocks |
| Cosine distance | 1 - (x · y) / (||x|| ||y||) | 0 to 2 (0 to 1 for nonnegative data) | Only the angle between vectors; length is ignored |
| Radial basis function (RBF) similarity | exp(-γ||x - y||2) | Above 0, up to 1 | Closeness, with γ (gamma) setting how fast similarity fades |
Work ticket A against B and C. Euclidean distance: A - B = (-2, 0, -1), so the distance is sqrt(4 + 0 + 1) = sqrt(5) ≈ 2.24. A - C = (2, -3, 0), so the distance is sqrt(4 + 9 + 0) = sqrt(13) ≈ 3.61. Manhattan distance: |-2| + 0 + |-1| = 3 to B, and 2 + 3 + 0 = 5 to C. Cosine similarity divides the dot product by the product of the lengths. A · B = 8 + 0 + 2 = 10, and ||A|| ||B|| = sqrt(5) × sqrt(20) = sqrt(100) = 10, so the cosine is 1 and the cosine distance is 0. A · C = 1 and ||A|| ||C|| = sqrt(5) × sqrt(10) ≈ 7.07, so the cosine is about 0.141 and the distance about 0.859. All three measures agree that B is nearer to A than C is.
Now change one input. Ticket D is the same refund complaint pasted into a long email thread: D = (20, 0, 10). Its Euclidean distance from A is sqrt(182 + 0 + 92) = sqrt(405) ≈ 20.12, and its Manhattan distance is 18 + 9 = 27. Both now rank the password ticket C (3.61 and 5) as closer to A than D. The cosine distance from A to D is still exactly 0, because D points in the same direction as A. The ranking flips depending on the metric. Euclidean and Manhattan measure differences in magnitude. Cosine measures only direction. For text and embeddings, where length mostly reflects how wordy someone was, cosine usually matches what "similar" should mean. For sensor readings, where magnitude is the signal, it would throw information away.
Euclidean and Manhattan also disagree about how gaps combine. Compare a pair of points that differ by (3, 3) with a pair that differ by (6, 0). Manhattan scores both at 6. Euclidean scores the first sqrt(18) ≈ 4.24 and the second 6, because squaring punishes one large gap more than two moderate ones. Both are members of the Minkowski family: Manhattan uses power 1 and Euclidean power 2. Manhattan is the natural choice when movement really happens along axes, such as street grids or warehouse aisles. It is also a common choice when you do not want a single extreme coordinate to dominate.
The radial basis function kernel answers the objective's "radial" entry. It is a similarity, not a distance. It turns squared Euclidean distance into a score that is 1 for identical points and fades toward 0 as points move apart. It is also written exp(-||x - y||2 / (2σ2)), so γ = 1/(2σ2). With γ = 0.1, A-to-B similarity is exp(-0.1 × 5) = exp(-0.5) ≈ 0.61, A-to-C is exp(-1.3) ≈ 0.27, and A-to-D is exp(-40.5), about 2.6 × 10-18, effectively zero. Raise γ to 1 and A-to-B drops to exp(-5) ≈ 0.0067: a larger γ makes the kernel nearsighted. The RBF kernel is the usual choice for curved decision boundaries in support vector machines (SVM). Because it is built from Euclidean distance, it inherits Euclidean's sensitivity to scale.
Scale breaks Euclidean, Manhattan and RBF whenever features are measured in different units. Take two fictional customers who differ by $5,000 in income and 30 years in age. Their Euclidean distance is sqrt(50002 + 302) = sqrt(25,000,900) ≈ 5000.09, so age adds less than a tenth of a unit. Suppose income has a standard deviation of $20,000 and age 12 years. After standardizing, the gaps become 0.25 and 2.5, the distance is sqrt(0.0625 + 6.25) ≈ 2.51, and age now dominates. So standardize when features sit on different scales or units, as dollars against years do, before a distance-based method such as k-nearest neighbors (KNN) or k-means. Same-unit features are a different case. The ticket vectors are all word counts on one scale, and centering or standardizing sparse counts would destroy their zeros and distort their meaning. For counts or term frequency inverse document frequency (TF-IDF) weights, use cosine directly or normalize each vector to length 1. After that normalization, squared Euclidean distance equals 2 × cosine distance, because ||x - y||2 = 2 - 2(x · y) for unit vectors, so the two measures rank neighbors the same way.
Finally, not every "distance" is a true metric. A true metric must be non-negative, zero only for identical points, symmetric, and must satisfy the triangle inequality, d(x, y) + d(y, z) ≥ d(x, z).[5] Euclidean and Manhattan qualify. Cosine distance does not. Take unit vectors at 0, 45 and 90 degrees. Each 45-degree step has cosine distance 1 - 0.707 = 0.293, so the two steps sum to 0.586. Yet the direct 0-to-90 distance is 1 - 0 = 1. That matters in practice, because scikit-learn's BallTree neighbor-search structure requires a true metric when you supply your own distance function.[5]
In scikit-learn, the function pairwise_distances computes a full distance matrix from a feature array.[6] Its documented metric names include "euclidean", "manhattan" (also accepted as "cityblock") and "cosine". This is the documentation's own example, which uses squared Euclidean distance:
>>> from sklearn.metrics.pairwise import pairwise_distances
>>> X = [[0, 0, 0], [1, 1, 1]]
>>> Y = [[1, 0, 0], [1, 1, 0]]
>>> pairwise_distances(X, Y, metric='sqeuclidean')
array([[1., 2.],
[2., 1.]])
Read it as a grid. Row i is the i-th vector in X, and column j is the j-th vector in Y. From (0, 0, 0), the squared distance to (1, 0, 0) is 1 and to (1, 1, 0) is 2. From (1, 1, 1), the squared distances are 0 + 1 + 1 = 2 and 0 + 0 + 1 = 1.
So what?: choose the metric by deciding what "similar" means for the data. Use cosine when only direction matters, Euclidean or Manhattan when magnitude matters, and RBF when you want a smooth similarity with tunable reach. Standardize when features have different units or scales; for same-unit counts or TF-IDF weights, use cosine or length-normalize instead.
Exponentials and logarithms: the functions inside probability models
The churn model in the next section outputs a probability. The function that turns its raw score into a probability is built from the exponential function exp(z) = ez, where e ≈ 2.71828. Three properties explain why ez is everywhere in data science. It is always positive, so it can turn any score into a valid rate, weight or probability. It turns addition into multiplication: ea+b = eaeb. And it is its own derivative, which keeps the gradients of exponential models tidy.
The logarithmic function runs the exponential backwards. logb(x) = y means exactly that by = x, so the two functions swap inputs and outputs.[7] The base b must be positive and not 1, and x must be positive. Logarithms reverse the exponential's trade of operations, turning multiplication into addition: log(ac) = log(a) + log(c).[8] The power rule, log(ar) = r log(a), lets you solve for an unknown exponent. To solve 5x = 2, take the natural logarithm of both sides. That gives x ln 5 = ln 2, so x = ln 2 / ln 5 ≈ 0.6931 / 1.6094 ≈ 0.431.
Two edge cases cause real bugs. The logarithm of 1 is 0 in every base. The logarithm of 0 has no value: it heads to minus infinity as x shrinks toward 0. The logarithm of a negative number is undefined. That is why a count feature containing zeros is usually transformed as ln(1 + x) rather than ln(x).
Which base does an unmarked "log" mean? It depends on who wrote it. In computer science it often means base 2.[7] In mathematics texts it almost always means base 10.[7] In statistical and machine learning (ML) code it usually means the natural log, base e, written ln: Python's math.log and NumPy's log both compute it. Bases differ only by a constant factor, since logb(x) = ln(x) / ln(b). Changing the base changes the units (bits for base 2, nats for base e) but never which model wins a comparison.
Logarithms do four jobs in data science:
- Products to sums. A likelihood multiplies one probability per observation. With 2,000 observations at probability 0.5 each, the product is 2-2000, about 10-602. That is far below the smallest positive 64-bit floating-point number, about 4.9 × 10-324, so the computer stores 0. The log-likelihood is 2000 × ln 0.5 ≈ -1386.3, a perfectly ordinary number. The logarithm always increases, so maximizing the log-likelihood picks the same parameters as maximizing the likelihood.
- Compressing skew. Income, prices and file sizes are right-skewed. A log transform pulls in the long tail and often makes the relationships more linear.
- Multiplicative effects become additive. On a log scale, equal steps are equal ratios. The 2010 Haiti earthquake registered 7.0 on the Richter scale and the 2011 Honshu earthquake 9.0.[7] Each Richter unit is a factor of 10 in measured wave amplitude, so two units mean 100 times larger amplitude. Released energy grows faster, roughly 1,000-fold over the same two units, which is why "stronger" needs a definition before you quote a ratio.
- Log-odds. Logistic regression models the log-odds ln(p / (1 - p)) as a linear function of the features. Its inverse is the sigmoid, so a coefficient w multiplies the odds by ew for each one-unit increase in its feature.
| Where | Formula | What exp or log is doing |
|---|---|---|
| Sigmoid (logistic regression, neural networks) | σ(z) = 1 / (1 + e-z) | Squeezes any real score into the interval from 0 to 1 |
| Softmax (multiclass output) | ezk / Σj ezj | Makes positive scores that sum to 1 |
| RBF kernel | exp(-γ||x - y||2) | Turns distance into a similarity between 0 and 1 |
| Log-loss and log-likelihood | -Σ ln pi | Turns a product into a sum and prevents underflow |
| Entropy (Lesson 2) | -Σ p log2 p | Measures impurity in bits |
| Bayesian information criterion (BIC) (Lesson 2) | k ln(n) - 2 ln(L) | Penalty that grows with the log of the sample size |
| Exponential smoothing (time-series forecasting) | Weights shrink by a constant factor per step back | Geometric decay of older observations |
Partial derivatives and the chain rule: one training step by hand
Training a model means adjusting its parameters to optimize an objective function that measures how well the model explains the data.[2] Such problems are usually solved with optimization algorithms that use gradient information.[2] A gradient is built from partial derivatives. For any model made of layers or linked functions, it is computed with the chain rule.
A partial derivative measures how a function of several variables changes when you move one variable and hold all the others constant. It is written ∂f/∂x and read "the partial of f with respect to x". To compute one, treat every other variable as a fixed number and differentiate as usual, with all the ordinary differentiation rules.[9] Take OpenStax's example f(x, y) = x2 - 3xy + 2y2 - 4x + 5y - 12. Holding y fixed gives ∂f/∂x = 2x - 3y - 4. The terms 2y2, 5y and -12 vanish because they are constants as far as x is concerned. Holding x fixed gives ∂f/∂y = -3x + 4y + 5.
Stack the partial derivatives into a vector and you have the gradient vector, ∇f = (∂f/∂x, ∂f/∂y). At the point (1, 1) it is (2 - 3 - 4, -3 + 4 + 5) = (-5, 6). The gradient points in the direction of steepest increase. Gradient descent therefore steps the opposite way: new parameters = old parameters - η × gradient, where η (eta) is the learning rate. Second derivatives describe curvature. When the mixed second-order partial derivatives are continuous, the order of differentiation does not matter.[9] In the example, differentiating 2x - 3y - 4 by y gives -3, and differentiating -3x + 4y + 5 by x also gives -3. That is why the matrix of second derivatives, the Hessian, is symmetric.
Partial derivatives are also where the normal equations come from. Fit one coefficient w with no intercept, using net price as x. RSS(w) = Σ(yi - wxi)2, and ∂RSS/∂w = -2Σxi(yi - wxi). Set it to zero and you get w = Σxiyi / Σxi2. With the invoice data, Σxi2 = 3000 (the top-left entry of XTX) and Σxiyi = 140 + 420 + 750 + 1200 = 2510. So w = 2510 / 3000 ≈ 0.837 days per dollar. This is (XTX)-1XTy for a 1 × 1 matrix. With several coefficients, the same step gives -2XT(y - Xβ) = 0, which rearranges to XTXβ = XTy.
The chain rule finds the derivative of a composition of functions, a function applied to the output of another.[10] In one variable, the derivative of f(g(x)) is f'(g(x)) × g'(x): multiply the derivative of each link. With several variables, add one product for each path. If z = f(x, y) and both x and y depend on t, then dz/dt = (∂z/∂x)(dx/dt) + (∂z/∂y)(dy/dt). The variables x and y in the middle, which drop out of the final answer, are called intermediate variables. OpenStax's worked case has z = 3x2 - 2xy + y2, x = 3u + 2v and y = 4u - v, and it needs six partial derivatives.[10] Then ∂z/∂u = (6x - 2y)(3) + (-2x + 2y)(4) = 10x + 2y, which is 38u + 18v once x and y are written in terms of u and v.
Now the churn model. A logistic regression with one feature computes z = wx + b, then p = σ(z) = 1 / (1 + e-z). Its log-loss for one example is L = -[y ln p + (1 - y) ln(1 - p)], where y is 1 for churned and 0 for stayed. The loss depends on w through the chain w → z → p → L, so ∂L/∂w = (∂L/∂p)(∂p/∂z)(∂z/∂w). Each link is short:
- ∂L/∂p = -y/p + (1 - y)/(1 - p), using the fact that the derivative of ln p is 1/p.
- ∂p/∂z = σ(z)(1 - σ(z)) = p(1 - p). This comes from the chain rule applied to (1 + e-z)-1: the derivative is e-z / (1 + e-z)2, and that equals σ(z) × e-z/(1 + e-z) = σ(z)(1 - σ(z)).
- ∂z/∂w = x and ∂z/∂b = 1.
Multiply the first two links and the algebra collapses: (-y/p + (1 - y)/(1 - p)) × p(1 - p) = -y(1 - p) + (1 - y)p = p - y. So ∂L/∂w = (p - y)x and ∂L/∂b = p - y. The table runs one step with w = 0.5, b = -1, x = 2 and learning rate η = 0.1. It does this twice, once for a customer who churned (y = 1) and once, with that single input changed, for a customer who stayed (y = 0).
| Quantity | Formula | Churned, y = 1 | Stayed, y = 0 |
|---|---|---|---|
| Score | z = wx + b | 0.5(2) - 1 = 0 | 0 |
| Probability | p = σ(z) | 0.5 | 0.5 |
| Loss before | -[y ln p + (1 - y) ln(1 - p)] | -ln 0.5 ≈ 0.693 | ≈ 0.693 |
| Link 1 | ∂L/∂p | -1/0.5 = -2 | 1/0.5 = 2 |
| Link 2 | ∂p/∂z = p(1 - p) | 0.25 | 0.25 |
| Link 3 | ∂z/∂w = x | 2 | 2 |
| Gradient for w | (p - y)x | -1 | +1 |
| Gradient for b | p - y | -0.5 | +0.5 |
| New w | w - η(∂L/∂w) | 0.6 | 0.4 |
| New b | b - η(∂L/∂b) | -0.95 | -1.05 |
| New probability | σ(new w × 2 + new b) | σ(0.25) ≈ 0.562 | σ(-0.25) ≈ 0.438 |
| Loss after | same loss formula | -ln 0.562 ≈ 0.576 | -ln 0.562 ≈ 0.576 |
Read the table column by column. In both cases the loss falls from 0.693 to 0.576. Flipping the label flips the sign of every gradient, so the same step that raises w for a churner lowers it for a stayer, and each time the probability moves toward the true label. The product of three links also shows why the chain rule matters beyond this toy model. A neural network is a long composition of layers. Backpropagation is the chain rule applied over and over, and autoencoders, for example, minimize reconstruction error exactly this way.[2] It also explains the vanishing-gradient problem in deep networks. The sigmoid's derivative p(1 - p) is never more than 0.25, so a chain through ten sigmoid layers multiplies in a factor no larger than 0.2510, about 10-6, before the weights are counted. That is one reason modern networks use the rectified linear unit (ReLU) instead.
So what?: for logistic regression with log-loss, the chain rule collapses three links into the gradient (p - y)x, so the update size is simply the prediction error times the feature value.
Exam cues: matching the stem to the concept
| Stem says | Points to | Commonly confused with |
|---|---|---|
| One feature is a sum or multiple of others; perfect multicollinearity; matrix is singular | Rank deficiency; XTX has no inverse | A scaling or missing-data problem |
| Nearly singular; unstable coefficients; large condition number | Near-zero eigenvalue; fix with ridge or by dropping a feature | Exact rank deficiency |
| Every vector reachable as a combination of these vectors | Span | Basis, which also requires independence |
| Smallest independent set that generates the space; coordinates | Basis vectors | Span |
| Sum of the diagonal; total variance in PCA | Trace (equals the sum of eigenvalues) | Determinant (product of eigenvalues) |
| Proportion of variance explained by a component | That eigenvalue divided by the trace | That eigenvalue divided by the largest eigenvalue |
| Direction the transformation only scales | Eigenvector | Basis vector of the standard basis |
| Works for any rectangular matrix; low-rank approximation | SVD | Eigendecomposition (square only, may not exist) |
| Multiplying by it changes nothing; added to the diagonal in ridge | Identity matrix | A matrix of all ones |
| Documents of different lengths; embeddings; angle | Cosine distance | Euclidean distance |
| City blocks; L1; sum of absolute differences | Manhattan distance | Euclidean (L2) |
| Straight-line; L2; square root of summed squares | Euclidean distance | Manhattan distance |
| Gaussian kernel; gamma controls width; SVM kernel | RBF | Cosine similarity |
| Rate of change in one parameter with the others fixed | Partial derivative | Total derivative |
| Backpropagation; derivative of composed functions | Chain rule | Product rule |
| Turn a product of probabilities into a sum; right-skewed feature; log-odds | Logarithm | Exponential |
| Sigmoid; softmax; constant-rate growth or decay | Exponential | Logarithm |
Common misconceptions
- "Any square matrix can be inverted." A square matrix is invertible only when it has full rank, which is the same as a nonzero determinant and no zero eigenvalue. The invoice XTX is square, symmetric and singular.
- "If the software returned coefficients, the design matrix is fine." Keying one total as $43 instead of $42 turned a singular matrix into an invertible one with a condition number of at least 6665. The fit runs, but the coefficients are unstable. Check the eigenvalues or the VIF, not just whether the fit ran.
- "Rank deficiency ruins predictions." The prediction is the projection of y onto the column space, and that projection is unique. Only the coefficients become non-unique, so the harm falls on interpretation.
- "A smaller Euclidean distance always means more similar." Euclidean distance responds to magnitude and to units. A long ticket about the same topic can sit farther away than a short ticket about a different topic, and a feature in dollars can drown out a feature in years.
- "Cosine distance is a true metric." It fails the triangle inequality. Two 45-degree steps cost 0.293 each, but the direct 90-degree pair costs 1, so neighbor-search structures that need a true metric cannot use it directly.
- "log means base 10, and log of zero is just zero." In most data science code, log is the natural log. The log of 1 is 0, but the log of 0 is undefined, which is why features with zeros get ln(1 + x).
The short version
- Rank is the number of linearly independent columns. It equals the number of pivots after row reduction and the number of nonzero singular values, and it can never exceed the smaller of a matrix's row and column counts.
- When a feature is a linear combination of others, XTX is singular. It has zero determinant, a zero eigenvalue and no inverse, and the OLS coefficients are not unique even though the predictions are.
- The span of some vectors is every linear combination of them. A basis is an independent set that spans, and the standard basis vectors are the columns of the identity matrix.
- The trace is the sum of the diagonal and equals the sum of the eigenvalues. In PCA, a component's share of variance is its eigenvalue divided by the trace.
- An inverse has the reciprocal eigenvalues and the same eigenvectors. A near-zero eigenvalue means unstable estimates, and ridge regression adds αI to raise every eigenvalue by α.
- The SVD exists for every real matrix. Eigendecomposition needs a square matrix with n independent eigenvectors. QR and Cholesky solve least squares without an explicit inverse, and Cholesky needs a symmetric positive-definite matrix.
- Euclidean distance is the square root of summed squared differences, Manhattan distance is the sum of absolute differences, cosine distance is 1 minus the cosine of the angle (it ignores length), and RBF similarity is exp(-γ × squared distance).
- A partial derivative holds the other variables fixed, and the chain rule multiplies derivatives along a composition. For logistic regression with log-loss, the gradient for a weight is (p - y)x.
- Exponentials and logarithms are inverse functions. Logs turn products into sums, prevent underflow in likelihoods, compress skew and define log-odds.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Marc Peter Deisenroth, A. Aldo Faisal, Cheng Soon Ong. (2020). Mathematics for Machine Learning. Cambridge University Press (authors' free PDF). mml-book.github.io
- Lior Silberman. (2022). 223 notes (Math 223 Linear Algebra). University of British Columbia. personal.math.ubc.ca
- J. Wells. (2022). MAT 2114 Intro to Linear Algebra. Virginia Tech. personal.math.vt.edu
- scikit-learn developers. (n.d.). sklearn.metrics.DistanceMetric. scikit-learn.org
- scikit-learn developers. (n.d.). sklearn.metrics.pairwise_distances. scikit-learn.org
- OpenStax. (n.d.). 4.3 Logarithmic Functions (Precalculus 2e). openstax.org
- OpenStax. (n.d.). 1.5 Exponential and Logarithmic Functions (Calculus Volume 1). openstax.org
- OpenStax. (n.d.). 4.3 Partial Derivatives (Calculus Volume 3). openstax.org
- OpenStax. (n.d.). 4.5 The Chain Rule (Calculus Volume 3). openstax.org
- Key terms
- Rank
- The number of linearly independent columns (equivalently, rows) in a matrix. It equals the number of pivots after row reduction and the number of nonzero singular values.
- Span
- The set of all vectors that can be formed as linear combinations of a given set of vectors. For a feature matrix, the span of its columns contains every prediction vector a linear model can produce.
- Basis vector
- A member of a basis, which is a linearly independent set of vectors that spans a space so that every vector has unique coordinates. The standard basis vectors are the columns of the identity matrix.
- Trace
- The sum of the diagonal entries of a square matrix, equal to the sum of its eigenvalues. For a covariance matrix it is the total variance used to compute PCA explained-variance shares.
- Eigenvalue and eigenvector
- For a square matrix A, a nonzero vector v that satisfies Av = lambda times v is an eigenvector, and the scalar lambda is its eigenvalue. An eigenvalue of zero means the matrix is singular.
- Singular value decomposition
- The factorization X = U Sigma V-transpose, which exists for every real matrix. U and V have orthonormal columns and the singular values are nonnegative. It reveals rank and gives the best low-rank approximations.
- Cosine distance
- One minus the cosine of the angle between two vectors, where the cosine is their dot product divided by the product of their lengths. It ignores vector length, which suits text and embeddings, and it is not a true metric.
- Radial basis function kernel
- The similarity exp(-gamma times the squared Euclidean distance) between two points. It equals 1 for identical points and decays toward 0 as they move apart, and a larger gamma makes it decay faster.
- Partial derivative
- The rate of change of a function of several variables with respect to one variable while all the other variables are held constant. The gradient is the vector of all partial derivatives.
- Chain rule
- The rule for differentiating a composition of functions by multiplying the derivatives of each link, and adding the products when several paths connect the variables. Backpropagation applies it repeatedly.
Modeling Time: Temporal Models Compared
- Distinguish autoregressive, moving average and ARIMA models by their equations and autocorrelation signatures, and identify p, d and q from ACF and PACF values.
- Choose between a time series model, a longitudinal design, survival analysis and a causal design from the shape of the data and the question asked.
- Compute a Kaplan-Meier survival curve by hand and contrast it with parametric and Cox proportional hazards models when data are censored.
- Compute and critique a difference-in-differences estimate, and explain how DAGs, randomized controlled trials and A/B tests identify treatment effects.
One subscription company, four questions about time
Take a fictional meal-kit company called Larder and four files on its analytics server. The first holds 104 weekly order totals. The second holds one spending figure per customer per month for 18,000 customers. The third holds each customer's sign-up date and, for the 6,200 who have left, a cancellation date. The fourth records that a new pricing page went live in the North region on 1 March while the South kept the old one. Every row in all four files carries a date, so all four are temporal data. Yet each file answers a different question, and each question needs a different family of model.
Exam objectives: CompTIA DataX DY0-001 objective 1.4, "Compare and contrast various types of temporal models."[1] The objective names time series models (autoregressive (AR), moving average (MA) and autoregressive integrated moving average (ARIMA) models), longitudinal studies, survival analysis (parametric and non-parametric) and causal inference (directed acyclic graphs (DAGs), difference-in-differences, A/B testing of treatment effects and randomized controlled trials).
| Business question | Shape of the data | Model family | What it estimates | Assumption that carries the weight |
|---|---|---|---|---|
| How many orders next week? | One long series, one value per week | Time series: AR, MA, ARIMA | Future values of the same series | The series is stationary, or becomes stationary after differencing |
| How does a customer's monthly spend change over the first year? | Many customers, each measured several times | Longitudinal study (panel or repeated measures) | Change within each person and differences between people | Measurements from the same person are correlated, and the model says so |
| How long until a customer cancels, and what shortens that time? | One duration per customer; some still unfinished | Survival analysis: Kaplan-Meier, exponential, Weibull, Cox | Survival curve, hazard, hazard ratios | Unfinished cases (censoring) are not systematically riskier or safer than the rest |
| Did the new pricing page cause more cancellations? | Treated and untreated groups, ideally before and after | Causal inference: DAG, randomized controlled trial, A/B test, difference-in-differences | An average treatment effect | Random assignment, parallel trends, or no unmeasured confounding |
Read the table by its second column first. In an exam stem, the shape of the data usually gives the family away before any method name appears. One unit observed many times is a time series. Many units, each observed a few times, is longitudinal. A duration where some cases are still running is survival. A question containing "cause", "effect of", "because of" or "would have happened" is causal, whatever the data look like. The last column matters just as much. Each family is only as good as its central assumption, and most wrong exam options quietly break that assumption.
Worth holding on to: classify a temporal problem by two things: the shape of the data (one long series, many short series, durations with censoring, treated versus untreated groups) and the question (forecast, describe change, time to event, cause). The model family follows from those two.
Stationarity: the condition behind AR, MA and ARIMA
A time series is a sequence of measurements of one quantity taken at equally spaced times: Larder's weekly orders, hourly server load, a monthly price index. The three time series models on the exam all predict the next value from the series' own past. That only works if the past is a fair guide to the future. The formal version of that idea is stationarity.
A series is weakly stationary when its mean and variance do not change over time, and the correlation between two values depends only on how far apart they are, not on when they occur. The correlation between this week and last week should be about the same in 2025 as in 2026. If the mean is climbing, a coefficient fitted on early data describes a different process from the one producing later data, and the forecast inherits the mismatch.
The Box-Jenkins method, the classic recipe for building these models, starts here: decide whether the series is stationary and whether it has seasonality that must be modeled. Two plots do most of the work. A run sequence plot (the series drawn against time) should show a constant level and spread. The autocorrelation function (ACF) is the correlation of the series with itself shifted back k steps, plotted for k = 1, 2, 3 and so on. Hyndman and Athanasopoulos put the ACF test simply: the ACF of a stationary series falls to zero fairly fast, and the ACF of a non-stationary series falls slowly.[2]
The companion plot is the partial autocorrelation function (PACF). It shows the correlation at lag k after removing whatever lags 1 to k-1 already explain. Most software draws a band of roughly plus or minus 2/√N around zero on both plots, where N is the number of observations. Spikes inside the band are treated as noise. With N = 100 the band is about plus or minus 0.20; with N = 144 it is about plus or minus 0.17.
The standard repair for a drifting mean is differencing: replace each value with its change from the previous value. Transformations such as logarithms fix a different problem, a variance that grows with the level of the series. Box and Jenkins recommend differencing a non-stationary series one or more times until it becomes stationary.[3] Here is what one round of differencing does to six fictional weeks of Larder orders.
| Week | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Orders yt | 500 | 512 | 530 | 541 | 560 | 574 |
| First difference yt - yt-1 | none | 12 | 18 | 11 | 19 | 14 |
The raw orders climb by about 15 a week, so their average depends on which weeks you pick. The differences hover around 15 with no trend. A model fitted to the differences has one stable target. To forecast the level, you add the predicted changes back onto the last observed value, which is the "integration" step that puts the I in ARIMA.
Three refinements matter in practice. If the trend itself curves, a second difference (the change in the change) may be needed. If the pattern repeats each year, a seasonal difference subtracts the value one season earlier, such as yt - yt-12 for monthly data. And differencing a series that was already stationary does harm: it adds an artificial negative correlation at lag 1 and inflates the forecast variance. Difference only as many times as the evidence requires.
Autoregressive models: today leans on yesterday's values
An autoregressive model (AR) predicts the current value as a weighted sum of the previous p values plus a fresh random shock. In the notation the NIST/SEMATECH e-Handbook of Statistical Methods uses, an AR(p) model is:
Xt = δ + φ1Xt-1 + φ2Xt-2 + ... + φpXt-p + At
Here δ (delta) is a constant, each φ (phi) is a coefficient fitted from data, p is the order (how many past values enter), and At is white noise: a random shock with mean zero, constant variance and no correlation with any other period's shock. The model is a regression of the series on its own lags, which is where the name comes from.
Work an AR(1) with fictional values δ = 20 and φ1 = 0.6. First find the long-run mean μ. In a stationary series the expected value is the same every period, so μ = 20 + 0.6μ, which gives μ = 20 / (1 - 0.6) = 50. Suppose last week's value was 60, ten above the mean.
- One step ahead: 20 + 0.6 × 60 = 56, now 6 above the mean.
- Two steps ahead: 20 + 0.6 × 56 = 53.6, now 3.6 above.
- Three steps ahead: 20 + 0.6 × 53.6 = 52.16, now 2.16 above.
The gap shrinks by the factor 0.6 at each step: 10, 6, 3.6, 2.16. A shock never disappears exactly, but its influence fades geometrically. The theoretical ACF of an AR(1) at lag k is φ1k, here 0.6, 0.36, 0.22, 0.13. That is the exponential decay the NIST handbook names as the AR(1) signature.[4] The PACF tells a different story. Once lag 1 is accounted for, lag 2 adds nothing, so the PACF has one spike and then drops to zero. In general the PACF of an AR(p) cuts off after lag p, which is why the PACF is the tool for finding the order of an autoregression.
Now change one input. Set φ1 = 1 and δ = 0, giving Xt = Xt-1 + At. This is a random walk. There is no mean to return to (the formula for μ now divides by zero), every shock stays in the series permanently, the variance grows with time, and the ACF barely decays. The series is not stationary. One difference turns it into white noise, so a random walk is ARIMA(0,1,0). An AR(1) is stationary only when -1 < φ1 < 1. A negative coefficient such as φ1 = -0.6 is still stationary, but its ACF alternates in sign: -0.6, 0.36, -0.22. The NIST identification table lists that alternating decay as an autoregressive signature too.
Moving average models: today leans on yesterday's surprises
A moving-average model (MA) in the Box-Jenkins sense is not a rolling average. It predicts the current value from the mean, the current shock and a weighted sum of past shocks, which are the forecast errors of earlier periods:
yt = μ + εt + θ1εt-1 + ... + θqεt-q
Each ε (epsilon) is a white noise shock, each θ (theta) is a fitted coefficient, and q is the order. The 7-day moving average on a dashboard is a smoothing tool that averages observed values to show a trend. It describes data. An MA(q) model is a generating process for data. The exam can put the two side by side, and they are not the same thing.
Work an MA(1) with fictional values μ = 20 and θ1 = 0.8. Last week the model expected 20 and the actual value was 25, so last week's shock was +5.
- One step ahead: 20 + 0.8 × 5 = 24. Next week's own shock is unknown, so its expected value of zero is used.
- Two steps ahead: 20. Last week's shock is now two periods back, outside the model's one-period window.
Compare the two models. In the AR(1), a shock fades gradually and never quite vanishes. In the MA(1), a shock has full influence for exactly q periods and then none. The ACF shows the same contrast. For an MA(1) the lag-1 autocorrelation is θ1 / (1 + θ12) = 0.8 / 1.64 ≈ 0.49, and every later lag is zero. In general the ACF of an MA(q) cuts off after lag q, so the NIST handbook reads the order from where the ACF drops to zero.[4] The PACF of an MA process decays gradually instead and does not help to find q.
Two details catch experienced people. First, sign conventions differ. The NIST handbook writes the MA terms with minus signs (At - θ1At-1), while Hyndman and Athanasopoulos and many software packages use plus signs. Check your library's documentation before you interpret the sign of a fitted θ. Second, MA models are constrained to be invertible: for an MA(1), -1 < θ1 < 1. That condition lets the model be rewritten as an autoregression with fading weights, so recent shocks matter more than distant ones. Estimation software normally enforces it for you.
A model that contains both kinds of terms, p lags of the series and q lags of the shocks, is an autoregressive moving average (ARMA) model, written ARMA(p, q). The table below sets the theoretical plot patterns side by side.
| Process | ACF pattern | PACF pattern | Memory of one shock |
|---|---|---|---|
| AR(p) | Decays gradually, smoothly or alternating in sign | Cuts off after lag p | Fades geometrically, never exactly zero |
| MA(q) | Cuts off after lag q | Decays gradually | Full for q periods, then gone |
| ARMA(p, q) | Decays, starting after a few lags | Decays | A mixture of both |
| White noise | All lags near zero | All lags near zero | None |
| Non-stationary, such as a random walk | Very slow decay or none | Large spike near 1 at lag 1 | Permanent |
Worth holding on to: AR terms use past values, so the ACF decays and the PACF cuts off at p. MA terms use past shocks, so the ACF cuts off at q and the PACF decays. Whichever plot cuts off sharply names the model and its order.
ARIMA(p, d, q): differencing plus both kinds of memory
Combine differencing with autoregression and a moving average and you get a non-seasonal autoregressive integrated moving average (ARIMA) model.[2] Fitted to the differenced series, its predictors include both lagged values of the series and lagged errors. The model is written ARIMA(p, d, q):
- p is the number of autoregressive lags.
- d is the number of times the series was differenced.
- q is the number of moving average lags.
When d = 0 the model is an ARMA(p, q). Many familiar models turn out to be special cases:
| Model | ARIMA form | What it says |
|---|---|---|
| White noise | ARIMA(0,0,0) with no constant | Nothing in the past predicts the future |
| Random walk | ARIMA(0,1,0) with no constant | Next value is the last value plus a shock |
| Random walk with drift | ARIMA(0,1,0) with a constant | The same, plus a steady average change each period |
| Autoregression | ARIMA(p,0,0) | Past values of a stationary series |
| Moving average | ARIMA(0,0,q) | Past shocks of a stationary series |
Box-Jenkins modeling runs in three stages: identification, estimation and validation. Identification chooses d, then p and q, from plots. Estimation fits the coefficients, usually by maximum likelihood. Validation checks that the residuals look like white noise: a residual ACF with no significant spikes, often backed by a portmanteau test such as Ljung-Box. If structure remains in the residuals, the model has missed something, and you go back to identification.
Here is identification worked end to end on a fictional series of 144 weekly order totals, so the noise band is about plus or minus 2/√144 = 0.17. The raw series has ACF values 0.96, 0.93, 0.90, 0.87, 0.84 at lags 1 to 5. That is almost no decay, so the series is not stationary, and you difference once (d = 1). The differenced series gives:
| Lag | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| ACF | 0.62 | 0.39 | 0.23 | 0.15 | 0.09 |
| PACF | 0.62 | 0.04 | -0.05 | 0.03 | 0.02 |
The ACF decays gradually, each value roughly 0.62 times the one before, so this is autoregressive behavior. The PACF has one spike outside the band at lag 1 and nothing after it, so p = 1. Nothing calls for an MA term, so q = 0. The candidate is ARIMA(1,1,0). As a check, an AR(1) with φ = 0.62 predicts ACF values of 0.62, 0.38, 0.24, 0.15 and 0.09, which matches.
Now change the input. Suppose the differenced series had instead produced these values:
| Lag | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| ACF | 0.48 | 0.05 | -0.03 | 0.02 | 0.01 |
| PACF | 0.48 | -0.29 | 0.20 | -0.14 | 0.10 |
Now the ACF has a single spike and then sits inside the band, which is the MA(1) signature. The PACF alternates and shrinks. Its lag-2 and lag-3 values do poke outside the band, and a hasty reader might call this AR(3). But a decaying PACF is exactly what an MA process produces. The candidate becomes ARIMA(0,1,1). Solving 0.48 = θ / (1 + θ2) for the invertible root gives θ ≈ 0.75.
Real plots are noisier than these, because sample ACF and PACF values are themselves random, and mixed ARMA models are especially hard to read from them. For that reason, practice has shifted toward information criteria such as the Final Prediction Error (FPE) and the Akaike Information Criterion (AIC), the criteria from Lesson 2.[4] Hyndman and Athanasopoulos's ARIMA() function in R chooses d with unit-root tests and then picks p and q (and the seasonal orders) by minimizing the AICc, a small-sample corrected AIC.[2] One caution: compare information criteria only between models with the same d, because differencing changes the data the likelihood is computed on.
Seasonal patterns need extra terms. Box-Jenkins models extend to seasonal autoregressive and seasonal moving average terms, and for monthly data you would typically add one seasonal AR term or one seasonal MA term at lag 12. The extended model is called a seasonal autoregressive integrated moving average (SARIMA) model, which is the name on the exam's acronym list. It is written ARIMA(p,d,q)(P,D,Q)m, where the capital letters are the seasonal orders and m is the season length. ARIMA(2,1,0)(1,1,1)12 is a monthly model with two AR lags, one ordinary difference, one seasonal AR term, one seasonal difference and one seasonal MA term.
Know the practical limits too. Effective fitting needs a reasonably long series: Chatfield recommends at least 50 observations, and many others recommend at least 100.[3] ARIMA is univariate and linear, and it assumes the process stays the same over time. Its long-horizon behavior depends on d. With d = 0, forecasts revert to the series mean and the prediction intervals level off at a fixed width. With d = 1 and no constant, forecasts stay flat at the last level; with d = 1 and a constant, they follow a straight line whose slope is the drift. With d = 2 and no constant, they extend the recent trend as a straight line. Whenever d is 1 or more, the prediction intervals keep widening as the horizon grows.
Worth holding on to: pick d by differencing until the ACF dies out quickly. Then read p from a PACF cutoff and q from an ACF cutoff. When the plots are ambiguous, compare candidates with AIC or AICc at the same d, and keep the model whose residuals look like white noise.
Longitudinal studies: many short series instead of one long one
A longitudinal study measures the same units (people, stores, machines) repeatedly over time. The resulting table is often called panel data. It differs from a time series in its proportions: a time series is usually one unit observed hundreds of times, while a longitudinal data set is usually hundreds or thousands of units observed a handful of times each. It also differs from a repeated cross-section, which draws a fresh sample at each wave. A repeated cross-section can show that average spend rose. Only a longitudinal design can show that each customer's spend rose.
Longitudinal data are usually stored in long format, one row per unit per occasion:
| customer_id | month | spend | plan |
|---|---|---|---|
| A | 1 | 40 | Basic |
| A | 2 | 44 | Basic |
| A | 3 | 48 | Basic |
| B | 1 | 80 | Family |
| B | 2 | 82 | Family |
| B | 3 | 86 | Family |
| C | 1 | 60 | Basic |
| C | 2 | 63 | Basic |
| C | 3 | 66 | Basic |
Look at the two kinds of variation. Between people, spend ranges from 40 to 86. Within each person, spend changes slowly: A rises 4 a month, B 3 a month, C 3 a month, an average within-person slope of about 3.3. An ordinary least squares (OLS) regression of spend on month treats the nine rows as nine independent observations. In fact they are three people, and rows from the same person are correlated. The point estimate may be reasonable, but the standard errors come out too small, so p-values are too optimistic. This error is sometimes called pseudo-replication.
Three standard tools handle the correlation explicitly:
- Mixed-effects models (also called multilevel or hierarchical models) give each unit its own random intercept, and optionally its own random slope, around shared fixed effects. Here, each customer would get a personal baseline spend, plus a common growth rate near 3.3 per month.
- Generalized estimating equations (GEE) estimate population-averaged effects with a working correlation structure and robust standard errors.
- A fixed effects model (the within estimator) uses only change within each unit. That removes every trait of a unit that does not change over time, whether it was measured or not.
The strength of the design is that each unit serves as its own comparison, which separates change over time from stable differences between units. Its characteristic weakness is attrition. Customers who cancel stop producing spend rows. If the reason they left is related to the spend you would have seen, such as unhappy low spenders leaving first, the missing rows are missing not at random (MNAR), and averages of the survivors drift upward for reasons that have nothing to do with growth. Longitudinal data also feed the next two sections. Survival analysis is often run on a longitudinal cohort, and difference-in-differences is a longitudinal comparison of groups.
Survival analysis: time until an event, with unfinished stories
Survival analysis models the time T from a defined origin, such as sign-up, to an event, such as cancellation. The name comes from medicine, where the event is death, but the same methods handle customer churn, machine failure, loan default and time to hire. What makes it a separate family is censoring: for some units you know only that the event had not happened by a certain time.
- Right censoring is the usual case. A customer is still subscribed when the data are pulled, or is lost to follow-up. You know T is greater than the observed time.
- Left censoring means the event happened before observation began, at an unknown time.
- Interval censoring means the event happened between two checks, for example between two monthly inspections.
- Type II censoring is a design in which a test stops after the k-th failure out of n units, as in reliability testing.
Two functions describe the distribution of T. The survival function S(t) = P(T > t) is the probability of still being event-free at time t. The hazard function h(t) is the instantaneous event rate at time t among units still at risk. They are linked: the density is f(t) = h(t)S(t), and S(t) = exp(-H(t)), where H(t) is the cumulative hazard. A hazard is a rate, not a probability, so it can exceed 1 when time is measured in large units.
Why not just average the durations? A censored duration is a lower bound, not a value. If you drop the 11,800 Larder customers who are still subscribed, you keep only people who left, and the average tenure comes out far too short. If you treat their current tenure as if they had left, the average is still too short. If you convert the problem to "cancelled: yes or no", you throw away timing, and a customer followed for one month counts the same as one followed for two years. Every valid survival method instead uses each censored case for exactly what it shows: survival up to the censoring time.
That only works under independent censoring: being censored must carry no information about a unit's risk. If customers who move abroad are lost to the data and are also more likely to have cancelled, censoring is informative, and every method below is biased.
Non-parametric survival: the Kaplan-Meier estimator by hand
A non-parametric method assumes no distribution for T. The standard one is the Kaplan-Meier estimator, also called the product-limit estimator. At each event time ti, let ni be the number still at risk just before ti and di the number of events at ti. Then:
Ŝ(t) = product over all event times ti ≤ t of (1 - di / ni)
Each factor is the conditional probability of getting through that event time, given that you reached it. Censored units count in the risk set up to their censoring time and then leave without causing a drop in the curve. Take eight fictional customers with tenures in months, where + marks a censored (still subscribed) customer: 2, 3+, 4, 4, 6+, 7, 9+, 10.
| Month | What happened | At risk ni | Events di | Factor 1 - d/n | Ŝ(t) |
|---|---|---|---|---|---|
| 2 | 1 cancellation | 8 | 1 | 7/8 = 0.875 | 0.875 |
| 3 | 1 censored | 7 | 0 | 1 | 0.875 |
| 4 | 2 cancellations | 6 | 2 | 4/6 = 0.667 | 0.583 |
| 6 | 1 censored | 4 | 0 | 1 | 0.583 |
| 7 | 1 cancellation | 3 | 1 | 2/3 = 0.667 | 0.389 |
| 9 | 1 censored | 2 | 0 | 1 | 0.389 |
| 10 | 1 cancellation | 1 | 1 | 0 | 0 |
Follow the arithmetic: 0.875 × 0.667 = 0.583, then 0.583 × 0.667 = 0.389. The median survival time is the first time at which Ŝ(t) falls to 0.5 or below, which is month 7. Half these customers are expected to last about seven months.
Now run the common shortcut on the same data: drop the three censored customers and take the median of the rest. The remaining tenures are 2, 4, 4, 7 and 10, with a median of 4 months. The shortcut has cut the median from 7 to 4, because it threw away three people who were known to have lasted at least 3, 6 and 9 months. With heavy censoring the error can flip a business decision. A retention program that looks unnecessary with a seven-month median looks urgent at four.
Kaplan-Meier curves are compared with the log-rank test, a non-parametric test of the null hypothesis that two or more groups have the same survival function. It is most powerful when one group's hazard is a constant multiple of the other's. The Nelson-Aalen estimator is the matching non-parametric estimate of the cumulative hazard H(t). The limits of Kaplan-Meier follow from its strength. Because it assumes nothing, it cannot extrapolate past the last observed time. It handles covariates only by splitting the data into groups. And its right-hand tail rests on very few units at risk, so read it with its confidence band.
Parametric and semi-parametric survival models
A parametric survival model assumes T follows a named distribution and estimates its parameters by maximum likelihood. Censoring enters the likelihood naturally: an observed event contributes its density f(ti), and a censored case contributes its survival probability S(ti), because all you know is that it lasted at least that long. Kulich's notes on censored data analysis call forming this likelihood, when the event and censoring times are independent, the most important result for parametric models.[5]
The simplest choice is the exponential distribution, with S(t) = e-λt and a hazard that is the same constant λ at every time. A constant hazard means the process has no memory: a customer in month 20 is as likely to cancel this month as one in month 2. With right-censored data, the maximum likelihood estimate is λ̂ = (number of events) / (total time at risk). Apply it to the eight customers above. There are 5 events, and the total time at risk is 2 + 3 + 4 + 4 + 6 + 7 + 9 + 10 = 45 months, so λ̂ = 5/45 ≈ 0.111 per month. The exponential median is ln 2 / λ = 0.693 / 0.111 ≈ 6.2 months, close to the Kaplan-Meier median of 7, and the mean is 1/λ = 9 months. Notice that every customer, censored or not, contributes time at risk to the denominator.
The Weibull distribution relaxes the constant hazard with a shape parameter k. When k < 1 the hazard falls over time, as with subscriptions where most cancellations come in the first weeks. When k = 1 it reduces to the exponential. When k > 1 the hazard rises, as with parts that wear out. Log-normal and log-logistic models allow a hazard that rises and then falls. Parametric models give smooth curves, work well with small samples when the shape is right, and can extrapolate beyond the follow-up period. That last ability is also their danger: the wrong family gives confident wrong answers precisely where there are no data to contradict it.
Between the two sits the Cox proportional hazards model:
h(t | x) = h0(t) × exp(β1x1 + ... + βkxk)
Covariates multiply an unspecified baseline hazard h0(t) by a constant factor. Kulich points out that the model cannot be estimated by ordinary maximum likelihood because it is not parametric: the baseline hazard is an unknown, arbitrary function.[5] Cox's partial likelihood removes h0(t) from the estimation, so you get coefficients without choosing a distribution. Because the covariate part has a fixed form and the baseline is left free, the model is called semi-parametric. If a question forces it into a two-way split of parametric versus non-parametric, its unspecified baseline hazard is the non-parametric part.
Each exp(β) is a hazard ratio. Suppose a fitted coefficient for the Family plan is β = -0.4. Then exp(-0.4) ≈ 0.67: at any given tenure, Family-plan customers cancel at about two-thirds the instantaneous rate of Basic customers. That is a statement about rates at each moment, not "they cancel 0.67 months later" and not "67 percent of them cancel." The proportional hazards assumption says this ratio is the same at month 1 and at month 20. Check it with Schoenfeld residuals or log-minus-log plots. If it fails, one remedy is to interact a covariate with a function of time, which lets its effect change explicitly over time.
| Approach | Examples | Assumption about the hazard | Covariates | Main strength | Main weakness |
|---|---|---|---|---|---|
| Non-parametric | Kaplan-Meier, Nelson-Aalen, log-rank test | None | Only by splitting into groups | Shows the data with no shape imposed | No extrapolation; unstable tail |
| Semi-parametric | Cox proportional hazards | Baseline left free; covariates scale it by a constant | Many, continuous or categorical | Hazard ratios without choosing a distribution | Proportional hazards must hold |
| Parametric | Exponential, Weibull, log-normal | Fully specified family | Many | Smooth curves, predicted durations, extrapolation | Wrong family, wrong answers, worst beyond the data |
Worth holding on to: censored cases are information, not noise. Kaplan-Meier uses them without assuming a shape, parametric models use them through S(t) in the likelihood, and Cox estimates hazard ratios while leaving the baseline hazard unspecified.
Causal inference: why forecasting is not explaining
Everything so far describes or predicts. Larder's executives want something else: did the North pricing page cause more cancellations? Causal inference frames this with potential outcomes, the framework also called the Rubin causal model. Each customer has Y(1), the outcome with the new page, and Y(0), the outcome without it. The causal effect for that customer is Y(1) - Y(0). But each customer saw only one page, so one of the two is always unobserved. Causal inference is therefore a missing-data problem: half of every individual comparison is missing.
Because individual effects are unobservable, analysts target averages. The average treatment effect (ATE) is E[Y(1) - Y(0)] over everyone. The average treatment effect on the treated (ATT) is the same average taken only over those who actually got the treatment. The naive comparison, the treated group's mean minus the untreated group's mean, splits into two parts:
E[Y | D=1] - E[Y | D=0] = ATT + (E[Y(0) | D=1] - E[Y(0) | D=0])
Here D = 1 marks treatment, and the bracketed term is selection bias: it asks whether the treated would have differed from the untreated even without treatment. A business-analytics text from Bookdown states the same decomposition in words, writing the first term as the average treatment effect.[6] Strictly, the identity delivers the ATT. It equals the ATE only when the treated would gain, on average, what everyone would gain, for example when the effect is the same for every unit. When effects vary and the units that got treated differ from the rest, the two averages differ. Under random assignment they coincide. If North customers were more price-sensitive to begin with, the naive gap mixes their sensitivity with the page's effect.
Every causal design is a strategy for making that selection term zero, or for removing it. Without an experiment, each method buys identification with an assumption of its own, and the assumptions differ from method to method. So before choosing an estimator, ask two questions. How did units come to be treated? Which average effect, for which population, do you want?
Directed acyclic graphs: drawing the assumptions first
A directed acyclic graph (DAG) is a diagram of causal assumptions. Each node is a variable, and each arrow is a direct causal effect. "Directed" means every arrow has a direction. "Acyclic" means no chain of arrows leads back to where it started, which fits time: a cause comes before its effect. The Bookdown chapter's example is the basic danger: a confounder Z that causes both X and Y obscures the true relationship between X and Y.[6]
Three structures decide what to control for:
| Structure | Arrows | Larder example | Control for the middle variable? |
|---|---|---|---|
| Fork (confounder) | X ← Z → Y | Region affects both which page a customer saw and how often customers cancel | Yes. It opens a non-causal path from X to Y |
| Chain (mediator) | X → M → Y | New page → perceived price → cancellation | No, if you want the total effect; controlling for it removes part of the effect |
| Collider | X → C ← Y | New page → support ticket ← intention to cancel | No. Conditioning on a collider creates a spurious association |
The collider case surprises people, so here is the mechanism. Suppose the page and the intention to cancel each independently raise the chance of filing a support ticket. Among customers who filed tickets, those who did not see the new page must mostly have filed because they intended to cancel. Within the ticket-filers, the page and cancellation now look negatively related, even if the page has no effect at all.
The rule that ties these together is the backdoor criterion. To estimate the effect of X on Y, adjust for a set of variables that blocks every path from X to Y that starts with an arrow into X, and include no descendants of X. A DAG does not estimate anything. It tells you which regression, matching or weighting to run, and which variables must stay out of it. Time ordering helps: a variable measured after treatment can be a mediator or a collider, but it cannot be a confounder of that treatment.
Randomized controlled trials and A/B testing of treatment effects
In a randomized controlled trial (RCT), the investigator assigns treatment by a random mechanism. In DAG terms, randomization deletes every arrow into the treatment, because nothing about a unit, measured or not, influences which arm it lands in. The treated and control groups then have the same expected Y(0), the selection bias term is zero in expectation, and a simple difference in means estimates the ATE. Without randomization, regression or matching recovers a causal effect only if you have measured every variable that drives both treatment and outcome, which rules out selection on anything unmeasured. Randomization is the design that balances unmeasured variables, in expectation, by construction. Other designs, such as instrumental variables or difference-in-differences, can cope with some unmeasured confounding too, but only by adding assumptions of their own.
An A/B testing experiment is an RCT run inside a digital product. Users are randomly split between the current version (A, control) and a variant (B, treatment), and a metric is compared. Work a fictional checkout test with the two-proportion method from Lesson 1:
| Arm | Users | Conversions | Rate |
|---|---|---|---|
| A (control) | 10,000 | 1,200 | 12.0% |
| B (variant) | 10,000 | 1,320 | 13.2% |
- Estimated treatment effect: 0.132 - 0.120 = 0.012, or 1.2 percentage points.
- Standard error: √(0.120 × 0.880 / 10,000 + 0.132 × 0.868 / 10,000) = √(0.00001056 + 0.00001146) ≈ 0.0047.
- Test statistic: z = 0.012 / 0.0047 ≈ 2.56, a two-sided p-value of about 0.01.
- 95% confidence interval: 0.012 ± 1.96 × 0.0047, about 0.3 to 2.1 percentage points.
The randomization is what licenses the word "caused." The statistics only say how precisely the effect was measured. Because A/B tests run over time, their characteristic failures are temporal:
- Peeking. Checking the p-value daily and stopping at the first value under 0.05 inflates the false positive rate far above 5 percent. Fix the sample size in advance, or use a sequential design built for repeated looks.
- Weekly cycles. Behavior differs by day of week, so run whole weeks, or the result describes a particular mix of days.
- Novelty and primacy effects. Users may click a new design because it is new, or avoid it because it is unfamiliar. Early effects can fade or grow, so look at the effect over time.
- Sample ratio mismatch. A planned 50/50 split that arrives as 10,000 against 9,400 signals a broken assignment or logging step. A chi-squared goodness-of-fit test flags it, and the result should not be trusted until the cause is found.
- Interference. If one user's treatment affects another's outcome, as in marketplaces or social features, the simple comparison is biased. Randomize by cluster instead.
| Feature | Classic RCT | Product A/B test |
|---|---|---|
| Typical setting | Medicine, public policy, field experiments | Websites, apps, email, pricing |
| Logic of identification | Random assignment | Random assignment (the same logic) |
| Typical outcome horizon | Weeks to years, often with follow-up visits | Days to weeks, logged automatically |
| Protocol | Pre-registration, ethics review, blinding where possible | Experiment platform, guardrail metrics, often many tests at once |
| Typical threats | Dropout, non-compliance, small samples | Peeking, sample ratio mismatch, novelty effects, interference |
Worth holding on to: an A/B test is an RCT. Randomization removes selection bias in expectation, including bias from variables nobody measured. The p-value only measures precision, and the time a test runs brings its own threats: peeking, weekly cycles and novelty.
Difference-in-differences: comparing changes instead of levels
Larder could not randomize the pricing page. It launched in the North for operational reasons. Difference in differences (DiD) uses variation over time (before against after) and across groups (treated against untreated) to recover a causal effect.[7] It therefore needs outcome data from both before and after the treatment. The idea is to let the untreated group show what would have happened to the treated group anyway, so the result is an effect on the treated, an ATT. Monthly cancellations per 1,000 subscribers (fictional) were:
| Region | February (pre) | April (post) | Change |
|---|---|---|---|
| North (new page) | 30 | 42 | +12 |
| South (old page) | 25 | 31 | +6 |
| Difference | 5 | 11 | +6 |
The DiD estimate is (42 - 30) - (31 - 25) = 12 - 6 = 6 extra cancellations per 1,000 subscribers per month. Compare the two shortcuts. A before-and-after comparison in the North alone says 12, but it ignores whatever raised cancellations everywhere between February and April. Sant'Anna's lecture notes name exactly this weakness of pre-post analysis: it does not account for trends in outcomes.[7] A post-period comparison across regions says 11, but it ignores the fact that the North already ran 5 higher. Subtracting the South's change removes shared time shocks. Subtracting the pre-period gap removes stable differences between regions.
The same estimate comes from a regression, y = β0 + β1Post + β2Treat + β3(Treat × Post) + error. Here β0 is the control group's pre-period mean (25), β1 is the change common to both groups (6), β2 is the stable gap between groups (5), and β3 is the treated group's extra change relative to the control group, which is the DiD estimate (6).[6] The regression form also produces standard errors for hypothesis testing, and it extends to covariates, many groups and many periods. Those standard errors should allow outcomes within a group to be correlated over time, which is the longitudinal problem again. Cluster-robust standard errors do that, but they need many clusters: with two regions they are unreliable or cannot be computed at all. With few groups, analysts use alternatives such as the wild cluster bootstrap or permutation (placebo) inference, and the strongest fix is usually more comparison units.
Everything rests on parallel trends: without the treatment, the two groups' outcomes would have moved by the same amount. Cunningham's Causal Inference: The Mixtape pairs it with no anticipation, meaning units do not change their behavior before the treatment starts.[8] Parallel trends concerns a counterfactual, so no statistical test can prove it, though visual inspection helps when there are many time points.[6] Cunningham lists the supporting evidence: event studies, which plot the treated-minus-control gap period by period around the start date, and falsification exercises.[8] Now run the example again, changing only the history before February.
| Month | November | December | January | February |
|---|---|---|---|---|
| Run 1: North | 29 | 30 | 30 | 30 |
| Run 1: South | 24 | 25 | 25 | 25 |
| Run 1 gap | 5 | 5 | 5 | 5 |
| Run 2: North | 18 | 22 | 26 | 30 |
| Run 2: South | 25 | 25 | 25 | 25 |
| Run 2 gap | -7 | -3 | 1 | 5 |
In Run 1 the gap is a flat 5 for four months, so parallel trends is plausible and the estimate of 6 is credible. In Run 2 the gap was already widening by 4 a month. Projecting that trend two more months, to April, predicts a gap of 13 with no new page at all. The observed gap is 11. The same post-period numbers now suggest no harm, and possibly a small benefit. The 2 × 2 table cannot tell these histories apart, which is why a DiD result without a pre-trend check is incomplete. The projection is itself an assumption, linear differential trends, so the honest conclusion in Run 2 is that this comparison group does not identify the effect.
Two modern complications are worth knowing. When adoption is staggered, with different units treated at different times, and effects vary across units or over time, the standard two-way fixed effects (TWFE) regression can be biased.[6] Part of the problem is that units treated early end up serving as controls for units treated later, even though their own outcomes are still moving because of the treatment. Estimators designed for staggered timing compare each cohort only with units not yet treated or never treated. Second, DiD does not strictly need panel data: it can be estimated from repeated cross-sections, which are easier to obtain, or from panel data, which are harder to obtain.[6]
Worth holding on to: DiD subtracts the control group's change from the treated group's change. That removes shared shocks and stable gaps, but only parallel trends turns the result into a causal effect, so always look at the pre-period gap before trusting the estimate.
Exam cues: matching the stem to the model
| Cue in the stem | Points to | Commonly confused with | How to tell them apart |
|---|---|---|---|
| Forecast next quarter from the series' own history | ARIMA family | Regression on other features | The only predictors are the series' own past |
| ACF cuts off after lag q; PACF decays | MA(q) | AR(p) | AR is the mirror image: the PACF cuts off and the ACF decays |
| Upward trend; ACF decays very slowly | Difference first (d of 1 or more) | Adding more AR lags | Slow ACF decay means non-stationary, not high order |
| Spikes at lag 12 in monthly data | Seasonal term (SARIMA) | An AR(12) with eleven useless lags | A seasonal term uses one parameter at the seasonal lag |
| Same patients or customers measured at each visit | Longitudinal study: mixed-effects or GEE | Time series; pooled OLS | Many units, few occasions, correlation within units |
| Still subscribed at study end; lost to follow-up | Right censoring, so survival analysis | Logistic regression on churned yes or no | The question is about time to the event |
| Survival curve with no distribution assumed | Kaplan-Meier (non-parametric) | Exponential or Weibull (parametric) | Parametric models name a distribution |
| Hazard ratio adjusted for covariates; baseline unspecified | Cox proportional hazards (semi-parametric) | Kaplan-Meier | Kaplan-Meier handles groups, not continuous covariates |
| Constant hazard; memoryless | Exponential model | Weibull | Weibull's shape lets the hazard rise or fall |
| Researcher randomly assigns treatment | RCT | Observational cohort | Who decided who got treated? |
| Users randomly split between two web versions | A/B test | Before-and-after comparison | Concurrent random arms, not sequential periods |
| Policy in one region but not another, data before and after | Difference-in-differences | A/B test | The groups were not randomly assigned |
| Which variables to control for; confounder, mediator, collider | DAG | Feature importance | A DAG encodes causal assumptions, not predictive power |
Common misconceptions
- "A moving average model is a rolling average of past values." A rolling average smooths observed values for display. An MA(q) model writes the current value as the mean plus current and past random shocks. Its fingerprint is an ACF that cuts off after lag q.
- "Differencing more is always safer." Differencing an already stationary series adds artificial negative correlation at lag 1 and widens forecast intervals. Difference until the ACF decays quickly, and no further.
- "Average tenure of customers who left tells you how long customers stay." Dropping censored customers keeps only the short stories. In the eight-customer example, it cut the median from 7 months to 4.
- "A hazard ratio of 1.5 means the group lasts 1.5 times shorter." It means a 50 percent higher instantaneous event rate at every time point, assuming proportional hazards. It is not a ratio of durations or of final proportions.
- "A big before-and-after change in the treated group proves the policy worked." A pre-post comparison absorbs every trend and shock in the period. DiD subtracts a comparison group's change, and even then only parallel trends justifies a causal reading.
- "Controlling for more variables always reduces bias." Controlling for a mediator removes part of the effect you want, and controlling for a collider creates a spurious association. The DAG decides what goes in the model.
Where this leaves us
- The data shape picks the family: one long series means time series, many units measured repeatedly means longitudinal, durations with censoring mean survival, and a "did it cause" question means causal inference.
- AR(p) predicts from past values, so its ACF decays and its PACF cuts off after lag p. MA(q) predicts from past shocks, so its ACF cuts off after lag q and its PACF decays.
- ARIMA(p, d, q) differences a series d times to make it stationary, then fits AR and MA terms. A slowly decaying ACF signals that differencing is needed. SARIMA adds seasonal terms, such as lag 12 for monthly data.
- When ACF and PACF plots are ambiguous, compare candidate ARIMA models with AIC or AICc at the same d, and accept a model only if its residuals behave like white noise. Stationary (d = 0) forecasts revert to the mean with intervals that level off; with d of 1 or more, intervals keep widening.
- Longitudinal data have correlated rows within each unit. Mixed-effects models, GEE or fixed effects handle that correlation; pooled OLS gives standard errors that are too small. Attrition is often missing not at random.
- Kaplan-Meier is non-parametric: multiply (1 - d/n) at each event time, and read the median where the curve first reaches 0.5. Censored units stay in the risk set until they leave.
- Parametric survival models assume a distribution, such as the exponential with its constant hazard (λ̂ = events / total time at risk) or the Weibull. Cox proportional hazards is semi-parametric and reports hazard ratios, exp(β).
- The naive treated-minus-control gap equals the ATT plus selection bias. Randomization in an RCT or A/B test removes that bias in expectation, including bias from unmeasured variables. A DAG shows which variables to adjust for: confounders yes, mediators and colliders no.
- Difference-in-differences equals the treated group's change minus the control group's change, which is β3 in the interaction regression. It is causal only under parallel trends and no anticipation, so check the pre-period gap.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Rob J. Hyndman and George Athanasopoulos. (2021). Forecasting: Principles and Practice, Chapter 9: ARIMA models. OTexts. otexts.com
- NIST. (n.d.). Box-Jenkins Models (NIST/SEMATECH e-Handbook of Statistical Methods, 6.4.4.5). itl.nist.gov
- NIST. (n.d.). Box-Jenkins Model Identification (NIST/SEMATECH e-Handbook of Statistical Methods, 6.4.4.6). itl.nist.gov
- Michal Kulich. (2021). Censored Data Analysis (NMST531) extended notes. Charles University. www2.karlin.mff.cuni.cz
- Bookdown. (n.d.). Chapter 11 Difference in Differences. bookdown.org
- Pedro H. C. Sant'Anna. (2025). Difference-in-Differences: Introduction (lecture notes). Emory University. psantanna.com
- Scott Cunningham. (2021). Causal Inference: The Mixtape, Foundational Ideas in Causal Inference. Scott Cunningham (Yale University Press). mixtape.scunning.com
- Key terms
- Stationarity
- Property of a time series whose mean, variance and autocorrelation at each lag do not change over time; AR, MA and ARIMA models require it, after differencing if necessary.
- Differencing
- Replacing each value of a series with its change from the previous value (or from one season earlier) to remove trend or seasonality and make the series stationary.
- ARIMA(p, d, q)
- Autoregressive integrated moving average model: the series is differenced d times, then modeled with p lags of its own values and q lags of past forecast errors.
- Autocorrelation function (ACF)
- The correlation of a series with itself shifted back by each lag k; it cuts off after lag q for an MA(q) process and decays gradually for an AR process.
- Censoring
- In survival data, knowing only partial information about an event time, most often that the event had not yet happened when observation ended (right censoring).
- Kaplan-Meier estimator
- Non-parametric estimate of the survival function, computed as the product of (1 - events / number at risk) over every event time up to t.
- Hazard function
- The instantaneous rate at which the event occurs at time t among units still event-free at t; it is constant for the exponential distribution.
- Cox proportional hazards model
- Semi-parametric survival regression in which covariates multiply an unspecified baseline hazard by exp(beta), giving hazard ratios that are assumed constant over time.
- Directed acyclic graph (DAG)
- A diagram of causal assumptions in which arrows show direct effects and no path loops back; it identifies confounders to adjust for and mediators or colliders to leave out.
- Parallel trends assumption
- The difference-in-differences assumption that, without treatment, the treated and comparison groups' outcomes would have changed by the same amount over time.
Module 2: Modeling, Analysis and Outcomes
Exploratory analysis, common data problems, enrichment and augmentation, iterative model design, justifying a final model, and communicating results.
Exploratory Data Analysis
- Establish what one row of a data set represents, separate object attributes from behaviors, and classify every feature as nominal, ordinal, binary, discrete or continuous before choosing an analysis.
- Choose and interpret the right univariate view (bar plot, histogram, density plot, box and whisker plot, violin plot, Q-Q plot) for a feature's type and the question asked.
- Choose and interpret multivariate views (scatter plot, scatter plot matrix, correlation plot, heat map, line plot, Sankey diagram) and recognize when a summary such as a correlation coefficient or an event-level count misleads.
A customer file with 12,480 rows and a column called plan_tier
The file is called customers_2026q3.csv, a comma-separated values (CSV) file. It is a fictional export from a meal-kit subscription company we will call Harvest Box, and it has 12,480 rows and 11 columns. One column, plan_tier, holds only the numbers 1, 2 and 3. Another, churned, holds the words yes and no. The head of retention wants to know which customers leave and why. Before anyone fits a model, someone has to look at this file in an organized way, and this lesson's exam objective is about exactly that looking.
Exam objectives: 2.1 Given a scenario, use the appropriate exploratory data analysis (EDA) method or process. The objective names univariate analysis, multivariate analysis, identification of object behaviors and attributes, twelve charts and graphs, and feature type identification across categorical, discrete, continuous, ordinal, nominal and binary variables.[1]
Exploratory data analysis is the stage where you study a data set to learn its structure before you commit to a model. The NIST/SEMATECH e-Handbook of Statistical Methods, the free statistics reference maintained by the US National Institute of Standards and Technology, calls EDA an approach or philosophy for data analysis rather than a fixed menu of techniques.[2] It relies mostly on graphs, with a few numerical summaries alongside them.[2] The defining move is the order of operations: EDA puts off the usual assumption about which model the data follow, and lets the data show their structure first.[2] The handbook traces the approach to John Tukey's 1977 book, Exploratory Data Analysis.[2]
One distinction from the handbook matters for the exam. EDA and statistical graphics are often used as if they meant the same thing, but they do not.[2] A chart is a tool. EDA is the process that decides which chart to draw, in what order, and what to do with what the chart shows. That is why objective 2.1 begins "Given a scenario". The questions describe a situation and ask which method fits, so you need the decision procedure as well as the chart names. If the basic charts themselves are new to you, the Atlas Data+ course introduces them at a gentler pace.
The procedure in seven steps
Each step's output is the next step's input. You cannot pick a chart until you know a feature's type. You cannot trust a feature's type, or any count, until you know what one row represents.
- Name the object. Decide what one row describes, and separate the object's attributes from its behaviors.
- Identify feature types. Classify every column as nominal, ordinal, binary, discrete or continuous, and set aside identifiers and dates.
- Univariate analysis of categorical features. Count the categories, usually with bar plots.
- Univariate analysis of numeric features. Describe center, spread and shape with histograms, density plots, box and whisker plots and violin plots.
- Check distributional assumptions. Compare a feature with a theoretical distribution using a Q-Q plot.
- Multivariate analysis. Look at pairs and groups of features with scatter plots, scatter plot matrices, correlation plots and heat maps.
- Time and flow. Use line plots for ordered sequences and Sankey diagrams for movement between states.
Here is the same procedure as a Python sketch using pandas and seaborn. You do not need to run it. It shows that each step is one or two short calls, so the hard part is choosing, not typing.
import pandas as pd
import seaborn as sns
df = pd.read_csv('customers_2026q3.csv')
print(df.dtypes) # Steps 1-2: how each column is stored
print(df.nunique()) # distinct values per column
print(df.isna().sum()) # missing values per column
sns.countplot(data=df, x='plan_tier') # Step 3
sns.histplot(data=df, x='avg_spend') # Step 4
sns.violinplot(data=df, x='plan_tier', y='avg_spend') # Step 4, by group
num_cols = ['tenure_months', 'boxes_q3', 'avg_spend', 'delivery_minutes_late', 'satisfaction']
sns.pairplot(data=df[num_cols + ['churned']], hue='churned') # Step 6
sns.heatmap(df[num_cols].corr(method='spearman'), vmin=-1, vmax=1, center=0, annot=True)We will run all seven steps on the Harvest Box file. Then we will rerun the first steps on a second file that answers the same business question at a different grain, and watch one of the conclusions flip.
The core of it: EDA is a sequence of decisions. The first two decisions, what a row is and what type each column is, determine which charts are valid for everything after them.
Step 1: The object, its attributes and its behaviors
The object is the entity that one row describes. Statisticians call this the unit of observation, and data engineers call it the grain of the table. In customers_2026q3.csv, one row is one customer, observed over the third quarter of 2026 (July to September). customer_id has 12,480 distinct values in 12,480 rows, and that is the quickest check that the grain really is one customer. If the file held only 11,900 distinct IDs, some customers would appear twice, and every count in the file would be inflated.
The objective's phrase "identification of object behaviors and attributes" asks you to split the columns that describe the object into two kinds. An attribute describes what the object is: region, plan tier, signup date. It is roughly fixed at the moment of the snapshot. A behavior describes what the object did: boxes ordered, minutes of late delivery experienced, whether it cancelled. Behaviors are almost always aggregates over a time window, and a behavior without a stated window is ambiguous.
| Column | Kind | Window or timing | Why it matters |
|---|---|---|---|
| customer_id | Identifier | None | Defines the grain; never a model feature |
| signup_date | Attribute | Fixed at signup | Source of tenure_months |
| region | Attribute | As of 1 July | A grouping for comparisons |
| plan_tier | Attribute | As of 1 July | A customer can change tier during the quarter |
| auto_renew | Attribute | As of 1 July | A setting, not an action |
| satisfaction | Behavior (survey reply) | Survey sent in August | Only customers who replied have a value |
| boxes_q3 | Behavior | July to September | A count over the window, which overlaps the churn window |
| avg_spend | Behavior | July to September, per box | Undefined when boxes_q3 is 0 |
| delivery_minutes_late | Behavior | July to September, per box | Undefined when boxes_q3 is 0 |
| tenure_months | Attribute derived from a date | Measured on 30 September | Changes with the measurement date |
| churned | Behavior (the outcome) | Cancelled by 30 September | The target; anything measured after it, or in the same window, can leak |
Two findings fall out of this table before a single chart is drawn. First, avg_spend and delivery_minutes_late must be missing for customers who ordered zero boxes, because an average over zero boxes does not exist. That missingness is structural, not a data-quality failure; Lesson 7, Diagnosing Common Data Problems, covers how to treat missing values.
Second, churned is the outcome, and the outcome sets a timing rule for every behavior. A behavior measured after a customer cancelled, such as a refund amount, leaks the answer into any model built on it. A behavior measured in the same window as the outcome can leak too. A customer who cancelled on 10 August orders no boxes in September, so a low boxes_q3 is partly a consequence of churning, not only a warning sign of it. For describing the quarter, which is what this EDA does, the overlap is harmless. A real churn model would measure behaviors in a window that ends before the outcome window opens: for example, behaviors from April to June predicting cancellations from July to September. Knowing each behavior's window is how you catch both kinds of leak.
A column profile makes the rest of the procedure concrete. The numbers below are fictional, but the patterns are common in real exports.
| Column | Stored as | Distinct values | Missing | Examples |
|---|---|---|---|---|
| customer_id | int64 | 12,480 | 0 | 100482, 100483 |
| signup_date | object (text) | 1,204 | 0 | 2023-02-11 |
| region | object (text) | 4 | 0 | North, West |
| plan_tier | int64 | 3 | 0 | 1, 2, 3 |
| auto_renew | int64 | 2 | 0 | 0, 1 |
| satisfaction | float64 | 5 | 1,310 | 4.0, 2.0 |
| boxes_q3 | int64 | 14 | 0 | 0, 5, 13 |
| tenure_months | int64 | 58 | 0 | 1, 19, 58 |
| avg_spend | float64 | 8,912 | 388 | 44.50, 61.20 |
| delivery_minutes_late | float64 | 3,077 | 388 | 0.0, 12.5 |
| churned | object (text) | 2 | 0 | yes, no |
The 388 missing values in avg_spend and delivery_minutes_late match the 388 customers whose boxes_q3 is 0, which confirms the structural explanation. Now look at satisfaction: five distinct values, stored as float64. In pandas, an integer column that contains any missing value is normally stored as floating point, because the missing marker NaN (not a number) is itself a float. The storage type is telling you about missing survey replies, not about what the variable means. That is the whole lesson of Step 2 in miniature.
Step 2: Feature type identification
Feature type identification means deciding what kind of variable each column is, because the type limits which summaries and charts make sense. The exam lists six types: categorical, discrete, continuous, ordinal, nominal and binary. They are not six parallel boxes. They form a small hierarchy with two branches.
Categorical variables place each object into a group. In the classic levels-of-measurement scheme taught in social science, nominal and ordinal variables are both called categorical because their values are categories.[3] Three kinds matter here.
- Nominal variable. Categories with no order, such as region. If you code the categories with numbers, the numbers are only labels. Penn State's measurement course makes the point with marital status: giving divorced a larger code does not make it higher or better than never married.[3] seaborn's plotting library describes its Nominal scale as "a categorical scale without relative importance / magnitude".[4]
- Ordinal variable. Categories with a natural order but no guarantee of equal spacing. Basic, Plus and Premium are ordered, yet nothing says the step from Basic to Plus equals the step from Plus to Premium. The key difference from an interval scale is exactly that the distances between levels are not equal.[3]
- Binary variable. Exactly two values, often coded 0 and 1, such as auto_renew or churned. Penn State calls a two-option nominal variable dichotomous, which is another name for binary.[3] seaborn has a dedicated Boolean scale for a domain of True and False values.[4] A binary variable is the simplest categorical variable, and its mean is meaningful: the mean of a 0/1 column is the proportion of 1s.
Numeric variables (also called quantitative) hold quantities for which arithmetic means something. Two kinds matter.
- Discrete variable. Values you can count, usually whole numbers that come from counting something: boxes_q3, support tickets, logins. A mean of 5.05 boxes is meaningful even though no customer ordered 5.05 boxes.
- Continuous variable. Values that can fall anywhere in an interval and come from measuring: avg_spend in dollars, delivery minutes late. Every real recording rounds to some precision, but the quantity itself is continuous.
One trap catches experienced people. "Continuous" has two meanings. In the levels-of-measurement scheme, interval and ratio variables are called continuous because their levels are equally spaced.[3] In data science and on this exam, continuous is the partner of discrete: it is about which values are possible. A count such as boxes_q3 is ratio level, because it has a true zero and six boxes is twice three boxes, and it is also discrete. The two schemes answer different questions. Levels of measurement ask which arithmetic is meaningful; discrete versus continuous asks which values can occur.
The 1-to-5 satisfaction score shows why classification takes judgement. Penn State notes a running debate over whether Likert-type scales like this are ordinal or interval, and that many researchers treat them as interval.[3] For EDA, the safe default is ordinal: show counts per level and report the median. If you later compute a mean satisfaction, say that you are treating the scale as interval.
| Type | Branch | Harvest Box example | Sensible summaries | Typical univariate chart |
|---|---|---|---|---|
| Nominal | Categorical | region | Counts, proportions, mode | Bar plot sorted by frequency |
| Ordinal | Categorical | plan_tier, satisfaction | Counts, median, percentiles | Bar plot in category order |
| Binary | Categorical | auto_renew, churned | One proportion | Often just the number; a two-bar plot at most |
| Discrete | Numeric | boxes_q3 | Mean, median, counts per value | Bar per value, or a histogram with integer bins |
| Continuous | Numeric | avg_spend, delivery_minutes_late | Mean, standard deviation, quantiles, skewness | Histogram, density plot, box plot, violin plot, Q-Q plot |
Some columns resist the table, and they are where exam questions live.
- Identifiers such as customer_id are nominal labels with one category per row. They define the grain and should never enter a model as a number.
- Postal codes, phone prefixes and product codes are digits that label things. They are nominal, however numeric they look. The mean postal code of your customers is meaningless.
- plan_tier is stored as an integer but is ordinal. Treating it as continuous assumes Premium is exactly three times Basic.
- tenure_months is discrete in principle (whole months) but has 58 distinct values, so analysts usually plot and model it as continuous. With many distinct values, the distinction stops mattering for charts.
- signup_date is a date, a temporal type the exam does not list separately. You rarely analyze a raw date; you derive features from it, such as tenure, signup month or day of week, and classify those.
When a column is unclear, three questions settle it. Does arithmetic on the values mean anything? If not, it is categorical. If it is categorical, do the categories have a natural order (ordinal), exactly two values (binary), or neither (nominal)? If it is numeric, did the number come from counting (discrete) or measuring (continuous)?
The core of it: classify by meaning, not by storage type. Ask whether arithmetic makes sense, whether the categories have an order, and whether a number came from counting or measuring.
Step 3: Univariate analysis of the categorical features
Univariate analysis examines one variable at a time. For a categorical feature, the questions are which categories exist, how often each occurs, whether any are rare, and whether any labels are unexpected, such as "north" in lowercase next to "North".
The standard chart is the bar chart, which the exam calls a bar plot: one bar per category, with length showing a count or a proportion. Here are the Harvest Box counts.
| Feature | Category | Customers | Share |
|---|---|---|---|
| region | North | 3,910 | 31.3% |
| region | East | 3,150 | 25.2% |
| region | South | 2,760 | 22.1% |
| region | West | 2,660 | 21.3% |
| plan_tier | 1 Basic | 6,240 | 50.0% |
| plan_tier | 2 Plus | 4,370 | 35.0% |
| plan_tier | 3 Premium | 1,870 | 15.0% |
| churned | yes | 1,622 | 13.0% |
Notice the ordering. The nominal region bars are sorted by frequency, because no other order means anything and sorting makes the comparison easy. The ordinal plan_tier bars stay in tier order, because the order is information; sorting Premium between Basic and Plus would hide it.
The word "bar plot" covers two different charts, and confusing them is a common error. A count plot shows how many observations fall in each category; seaborn's countplot does exactly this.[4] seaborn's barplot, by contrast, shows the mean of a numeric variable within each category, with a confidence interval.[5] A bar plot of mean avg_spend by region is therefore already a two-variable view, and its bar heights are dollars, not customers. When a question shows bars, read the axis label before you read the bars.
For a binary feature, one number usually says it all: 1,622 of 12,480 customers churned, or 13.0%. That imbalance matters later. A model that always predicts "no churn" would be 87% accurate and useless, which is why model evaluation relies on measures built from the confusion matrix (Lesson 2), such as precision, recall and the Matthews correlation coefficient (MCC), rather than on accuracy alone.
Step 4: Univariate analysis of the numeric features
For a numeric feature, univariate analysis asks four things: where is the center, how wide is the spread, what is the shape, and are there outliers? seaborn's own documentation opens its distribution section by noting that statistical analyses depend on knowing how each variable is distributed.[5] Start with numbers, then draw.
| Statistic | Value |
|---|---|
| Minimum | 19.90 |
| First quartile (Q1, 25th percentile) | 38.20 |
| Median (50th percentile) | 44.50 |
| Third quartile (Q3, 75th percentile) | 52.60 |
| Maximum | 188.00 |
| Mean | 47.90 |
| Standard deviation | 14.80 |
| Skewness | 2.1 |
The mean (47.90) sits above the median (44.50), and the maximum is far further above Q3 than the minimum is below Q1. Both signs point to a right skew: a long tail of high spenders pulls the mean up. Skewness and kurtosis are among the quantitative EDA measures the NIST handbook lists.[6] A skewness of 2.1 is strongly positive. A number cannot show you where the tail is or whether there are two humps, though, which is why the next four charts exist. seaborn offers both classic histograms and the more computer-intensive kernel density estimation for this job.[5]
The histogram divides the range of a numeric variable into equal-width bins and draws a bar for the count in each bin. Its shape depends on the bin width you choose. Too wide, and two humps merge into one. Too narrow, and random noise looks like structure. One standard starting point is the Freedman-Diaconis rule: bin width = 2 × IQR × n-1/3, where IQR is the interquartile range (Q3 minus Q1) and n is the number of values. For avg_spend, IQR = 52.60 - 38.20 = 14.40 and n = 12,092. The cube root of 12,092 is about 22.95, so the width is 28.80 / 22.95, roughly $1.25. The range is 188.00 - 19.90 = 168.10, which gives about 134 bins. Most of the bins above $75 will be nearly empty, so in practice you also look at the main body on its own or plot on a log scale.
For a discrete feature with few values, such as boxes_q3 (0 to 13), skip the bin arithmetic and give each integer its own bar. A histogram with bins that do not line up with the integers produces a picket fence of alternating tall and empty bars, which is an artifact of the binning, not a property of the data.
The density plot replaces the bars with a smooth curve built by kernel density estimation (KDE). Each observation contributes a small bump, usually a normal curve, and the bumps are added up. The estimate at a point x is fh(x) = (1 / nh) Σ K((x - xi) / h), where K is the kernel (the bump shape), xi are the observations and h is the bandwidth (the bump width). The bandwidth plays the same role as bin width: small h gives a wiggly curve, large h smooths real humps away. Density plots are easier than histograms to overlay for several groups. They have two quirks. The curve can spill past a hard boundary, showing density below 0 minutes of lateness, which cannot exist. And the height of the curve is a density, not a probability: area under the curve is probability, so a height above 1 is possible when the units are small.
The box plot, which the exam calls a box and whisker plot, compresses a distribution into five landmarks. The box runs from Q1 to Q3, a line marks the median, and the whiskers reach out to the most extreme values within a fence. Under the common convention from Tukey, the fences sit 1.5 IQR beyond the box. Points outside them are drawn individually as possible outliers. Work it for avg_spend.
- IQR = Q3 - Q1 = 52.60 - 38.20 = 14.40.
- 1.5 × IQR = 21.60.
- Lower fence = Q1 - 21.60 = 16.60. The minimum, 19.90, is inside it, so the lower whisker ends at 19.90 and there are no low outliers.
- Upper fence = Q3 + 21.60 = 74.20. Suppose 212 customers spend more than that per box; the upper whisker stops at the largest value at or below 74.20, and those 212 appear as dots out to 188.00.
That is 212 of 12,092 customers, or 1.75%. For a truly normal distribution, these fences flag only about 0.7% of points, so the excess dots are another sign of the right skew. "Outlier" here means "worth a look", not "delete". A $188 box may be a large family order, which is real behavior, or a pricing bug, which is not, and only investigation tells you which. Box plots excel at comparing many groups side by side, because each group takes only a narrow column.
Their weakness is that the five landmarks say nothing about what happens between them. A distribution with two humps and a distribution with one can share the same box. The violin plot fixes this by drawing a kernel density estimate as a mirrored shape around each group's axis, usually with the box plot statistics or the raw observations inside.[4] seaborn describes the idea as using kernel density estimation to show the distribution the points are sampled from.[5]
Here is a case where the choice changes the conclusion. Plot avg_spend by plan_tier. The box plots for Basic and Plus look ordinary. The Premium box is simply wide, with a median of $64. The violin for Premium shows two distinct bulges, near $52 and near $78. Premium is really two subgroups, perhaps two-person households and large families buying the same tier (a hypothesis to check, not a finding). The box plot gave no hint of that, and any model that treats Premium spending as one population will be misspecified.
| Chart | What it shows well | What it hides or distorts | Reach for it when |
|---|---|---|---|
| Histogram | Shape, humps, gaps, skew, with honest counts | Shape shifts with bin width; awkward to overlay | First look at one feature |
| Density plot | Smooth shape; several groups overlaid | Spills past boundaries; depends on bandwidth; hides n | Comparing two to four groups' shapes |
| Box and whisker plot | Median, quartiles, flagged outliers; many groups at once | Multiple humps and gaps inside the box | Comparing spread across many groups |
| Violin plot | Full shape per group plus box statistics | Bandwidth effects; can imply data where there is none | Comparing groups when shape may differ |
The core of it: summary numbers locate a distribution, but only a shape-showing chart reveals skew, multiple humps and gaps. Box plots compare many groups compactly; violin plots are the choice when the shape within a group might matter.
Step 5: Testing a distribution with the Q-Q plot
Many methods assume a feature, or a model's errors, follow a particular distribution, most often the normal. The Q-Q plot checks that assumption directly. A name note first: the objective text prints "Quartile-Quartile (Q-Q) plot", but the standard name, and the one in CompTIA's own acronym list, is quantile-quantile. The NIST handbook's alphabetical gallery of graphical techniques lists the normal probability plot, the general probability plot and the quantile-quantile plot as separate entries.[7] Strictly, a quantile-quantile plot can compare two data sets with each other, while a probability plot compares one data set with a theoretical distribution. Most software and most exam questions use "Q-Q plot" for both, so expect the comparison-with-normal version.
The mechanism takes four steps.
- Sort the n observations from smallest to largest.
- Give the i-th sorted value a cumulative probability, commonly pi = (i - 0.5) / n. Other conventions differ slightly; the idea is the same.
- Find the theoretical quantile for each pi: the value zi below which a fraction pi of a standard normal distribution falls. This is the inverse of the cumulative distribution function (CDF), written Φ-1(pi).
- Plot each sorted value against its zi. If the data are normal with mean μ and standard deviation σ, each value is close to μ + σzi, so the points fall on a straight line with slope σ.
Work it with five avg_spend values, small enough to do by hand. (A real Q-Q plot would use all 12,092.)
| i | Sorted value ($) | pi = (i - 0.5)/5 | Normal quantile zi | Gap to next value | Gap to next z | Slope of segment |
|---|---|---|---|---|---|---|
| 1 | 31.00 | 0.1 | -1.28 | 8.50 | 0.76 | 11.2 |
| 2 | 39.50 | 0.3 | -0.52 | 4.50 | 0.52 | 8.7 |
| 3 | 44.00 | 0.5 | 0.00 | 7.00 | 0.52 | 13.5 |
| 4 | 51.00 | 0.7 | 0.52 | 45.00 | 0.76 | 59.2 |
| 5 | 96.00 | 0.9 | 1.28 |
Read the last column. If the data were normal, every segment would have roughly the same slope, because a straight line has one slope. The first three segments run between about 9 and 13. The last segment, from $51 to $96, has a slope near 59, more than four times steeper. On the plot, the rightmost point shoots up far above the line through the others. The upper tail is much longer than a normal distribution predicts, which is the Q-Q signature of right skew. A log transform is a common next step, and you would check it with a fresh Q-Q plot of the logged values.
| Pattern of points | Meaning |
|---|---|
| Close to a straight line | Consistent with the reference distribution |
| Bends upward at the right end, curving like a U | Right skew: long upper tail |
| Bends downward at the left end, curving like an upside-down U | Left skew: long lower tail |
| Below the line at the left, above it at the right (an S shape) | Heavy tails: more extreme values than normal on both sides |
| Above the line at the left, below it at the right | Light tails: fewer extremes than normal |
| Straight except one or two far-off points | Individual outliers |
| Horizontal steps | Discrete or heavily rounded values |
Why use a Q-Q plot rather than a histogram for this job? A histogram makes you judge whether a bar shape looks bell-like, and that judgement depends on the bin width. The Q-Q plot turns the question into "is this a straight line?", which the eye answers well, and it magnifies the tails, which is exactly where normality assumptions usually fail.
Step 6: Multivariate analysis
Multivariate analysis examines two or more variables together, to find relationships, differences between groups and interactions. Bivariate analysis, two variables at a time, is its most common form. The right chart depends on the type pair, which is why Step 2 came first.
| Variables | Chart | Harvest Box example |
|---|---|---|
| Numeric and numeric | Scatter plot | tenure_months against avg_spend |
| Many numeric features at once | Scatter plot matrix, correlation plot | All five numeric features |
| Categorical and numeric | Box or violin plot by group; bar plot of group means | avg_spend by plan_tier |
| Categorical and categorical | Heat map of a cross-tabulation; Sankey diagram for flows | Late-delivery rate by weekday and time window |
| Numeric over time | Line plot | Boxes shipped per week |
The scatter plot draws one point per object, placing it by two numeric values. It shows direction, form (straight, curved, clustered), strength and outliers in one view. The NIST handbook's interpretation gallery has entries for scatter plots showing a quadratic relationship.[6] It also covers the case where the spread of Y grows with X, called heteroscedasticity, which shows as a funnel shape.[6] With 12,480 points, scatter plots suffer from overplotting: dense regions become solid blots. Transparency, a random sample of points, or a two-dimensional histogram fixes this.
Analysts often summarize a scatter plot with the Pearson correlation coefficient, r. With means mx and my:
r = Σ (xi - mx)(yi - my) / √[ Σ (xi - mx)2 × Σ (yi - my)2 ]
The numerator adds up products of deviations. When large x goes with large y, most products are positive and r approaches +1. When large x goes with small y, r approaches -1. The denominator rescales so r always lies between -1 and +1. This mechanism has a blind spot: r measures only linear association. Here is a four-point proof.
- Take x = -2, -1, 1, 2 and y = x2 = 4, 1, 1, 4. y is completely determined by x.
- mx = 0 and my = 2.5.
- The products (x - 0)(y - 2.5) are (-2)(1.5) = -3, (-1)(-1.5) = 1.5, (1)(-1.5) = -1.5 and (2)(1.5) = 3.
- They sum to 0, so r = 0, whatever the denominator.
A perfect relationship, and r = 0. The negative products on the left cancel the positive ones on the right. Spearman's rank correlation, which is Pearson's r computed on the ranks of the values, does not rescue you here. Ranking the same four points also gives 0, because Spearman detects monotonic relationships (always rising or always falling), and a U-shape is neither. Spearman is still the right choice for ordinal features such as satisfaction, and it resists outliers better than Pearson.
Harvest Box has a version of this. In the fictional data, the Spearman correlation between tenure_months and avg_spend, shown in the matrix below, is 0.04. The scatter plot shows a U: customers in their first three months and those beyond three years spend more per box than those in between. A colleague reading only the coefficient would drop tenure as irrelevant to spend. The plot says otherwise.
When there are more than two numeric features, the scatter plot matrix draws every pair at once in a grid: row j and column k hold the scatter plot of feature j against feature k, and the diagonal usually shows each feature's own distribution. seaborn's pairplot shows the joint distribution for every pair and the marginal distribution for each variable.[5] With k features there are k(k - 1)/2 distinct pairs. Five features give 10 pairs in a 25-panel grid, which is easy to read. Thirty features give 435 pairs, which is not, so for wide data you first screen with a correlation plot and then draw scatter plots only for the pairs that matter. Coloring points by a category, such as churned, turns the matrix into a quick check of which features separate the classes.
A correlation plot displays a correlation matrix: the coefficient for every pair of features, one cell per pair. It is almost always drawn as a heat map, with a diverging color scale centered on zero so that strong positive and strong negative values both stand out.
| Feature | tenure | boxes | spend | late | satisfaction |
|---|---|---|---|---|---|
| tenure_months | 1.00 | 0.41 | 0.04 | -0.02 | 0.12 |
| boxes_q3 | 0.41 | 1.00 | -0.18 | 0.03 | 0.22 |
| avg_spend | 0.04 | -0.18 | 1.00 | 0.01 | 0.05 |
| delivery_minutes_late | -0.02 | 0.03 | 0.01 | 1.00 | -0.37 |
| satisfaction | 0.12 | 0.22 | 0.05 | -0.37 | 1.00 |
Read it the way you would read the colored version. The diagonal is always 1. The matrix is symmetric, so only one triangle carries information. The strongest cells are tenure with boxes (0.41: long-standing customers order more) and lateness with satisfaction (-0.37: late boxes go with unhappy customers). The near-zero tenure-spend cell is the U-shape that the coefficient hides. A correlation plot is a screening tool that tells you which scatter plots to draw. It is also the first check for multicollinearity: pairs of predictors so correlated that a linear model cannot separate their effects, a data problem usually quantified with the variance inflation factor (VIF).
A heat map is the more general idea: any rectangular table of numbers drawn as a grid of colors. seaborn's heatmap function plots rectangular data as a color-encoded matrix.[4] Its clustermap goes further and reorders the rows and columns by hierarchical clustering so that similar ones sit together.[4] A correlation plot is one kind of heat map; a heat map does not have to show correlations. Here is a heat map's worth of numbers that has nothing to do with correlation.
| Window | Mon | Tue | Wed | Thu | Fri | Sat |
|---|---|---|---|---|---|---|
| Morning (8-12) | 4 | 3 | 4 | 4 | 5 | 6 |
| Afternoon (12-17) | 5 | 4 | 5 | 5 | 7 | 8 |
| Evening (17-21) | 6 | 6 | 7 | 8 | 19 | 15 |
As colors, the Friday and Saturday evening cells would glow against a pale grid, and you would see the pattern in under a second. Heat maps suit two categorical dimensions with a numeric value in each cell, especially when there are too many cells to read as numbers: 24 hours by 7 days, or 50 products by 12 months.
The core of it: a correlation coefficient compresses a scatter plot into one number and can hide a strong curved relationship. Use correlation plots to screen, then look at the scatter plots behind the cells that matter.
Step 7: Line plots for sequences, Sankey diagrams for flows
A line chart, the exam's line plot, connects points in the order of the horizontal axis. Connecting points says "the values in between exist and change smoothly", so a line plot is honest only when the x-axis is ordered and continuous in meaning, which usually means time. seaborn's line mark connects data points after sorting them along the axis.[4] Drawing a line through unordered categories such as regions invents a trend that does not exist.
| Week | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Boxes | 4,960 | 4,940 | 4,920 | 4,980 | 4,950 | 4,910 | 4,970 | 4,930 | 3,610 | 5,020 | 4,990 | 4,960 | 4,880 |
As a line, this is a flat run near 4,950 with a sharp drop in week 9 and a small catch-up in week 10. The plot does not explain the drop, but it tells you exactly which week to ask the operations team about. If the data had several rows per x value, for example one row per box with a week column, seaborn's lineplot would aggregate them: it plots the mean at each x and uses bootstrapping to draw a confidence band around it.[5] That is usually what you want, but you should know the line is an estimate, not a raw value.
The Sankey diagram shows flow. Plotly's documentation defines it as a flow diagram in which the width of each arrow is proportional to the quantity flowing.[8] Matplotlib's documentation adds that Sankey diagrams typically show transfers of energy, material or cost between processes.[9] In data science, the flows are usually objects moving between states: customers between plan tiers, users through the steps of a sign-up page, budget from departments to projects.
For Harvest Box, the retention team wants to see how customers moved between 1 July and 30 September. The data for a Sankey diagram is a list of links, each with a source node, a target node and a value.[8]
| From (1 July) | To (30 September) | Customers |
|---|---|---|
| Basic | Basic | 4,880 |
| Basic | Plus | 540 |
| Basic | Churned | 820 |
| Plus | Plus | 3,330 |
| Plus | Premium | 310 |
| Plus | Basic | 180 |
| Plus | Churned | 550 |
| Premium | Premium | 1,528 |
| Premium | Plus | 90 |
| Premium | Churned | 252 |
import plotly.graph_objects as go
labels = ['Basic (Jul)', 'Plus (Jul)', 'Premium (Jul)',
'Basic (Sep)', 'Plus (Sep)', 'Premium (Sep)', 'Churned']
fig = go.Figure(go.Sankey(
node=dict(label=labels),
link=dict(source=[0, 0, 0, 1, 1, 1, 1, 2, 2, 2],
target=[3, 4, 6, 4, 5, 3, 6, 5, 4, 6],
value=[4880, 540, 820, 3330, 310, 180, 550, 1528, 90, 252])))
fig.show()Before you draw it, check that the flows are conserved, because a Sankey diagram with leaking flows is wrong at a glance. Basic's outflows are 4,880 + 540 + 820 = 6,240, which matches the 6,240 Basic customers in Step 3. Plus gives 3,330 + 310 + 180 + 550 = 4,370, and Premium gives 1,528 + 90 + 252 = 1,870. Both match. The churn links total 820 + 550 + 252 = 1,622, which matches the churned count. The diagram then shows something no bar plot can. The Plus tier ends the quarter with 3,960 customers, down from 4,370, but that net drop of 410 hides 630 customers arriving (540 from Basic, 90 from Premium) and 1,040 leaving. A line plot of tier totals would show only the net change.
Sankey diagrams stop working when there are too many nodes. A diagram of 200 start stations by 200 end stations is spaghetti. Group small nodes into "Other", or show only the largest flows.
The second run: same question, different grain
Now change one input. The data team sends a second file for the same quarter, deliveries_2026q3.csv, with one row per box delivered instead of one row per customer: 63,020 rows. Each row repeats the customer's plan_tier and region next to the delivery details. An analyst who skips Step 1 runs the Step 3 count of plan_tier on this file to answer "which plan is most common?"
| Plan | Customers | Share of customers | Mean boxes per customer | Rows in delivery file | Share of rows |
|---|---|---|---|---|---|
| Basic | 6,240 | 50.0% | 3.9 | 24,336 | 38.6% |
| Plus | 4,370 | 35.0% | 5.6 | 24,472 | 38.8% |
| Premium | 1,870 | 15.0% | 7.6 | 14,212 | 22.6% |
| Total | 12,480 | 100% | 5.05 | 63,020 | 100% |
Trace the reasoning step by step. In the delivery file, each Basic customer contributes 3.9 rows on average, so Basic's row count is 6,240 × 3.9 = 24,336. Each Plus customer contributes 5.6 rows, giving 4,370 × 5.6 = 24,472. Plus now has more rows than Basic, and the bar plot reports Plus as the most common plan. The answer has flipped. Basic is the most common plan among customers; Plus is the most common plan among boxes. Both statements are true, but only one answers the question that was asked.
The event-level file hides a second problem. The 388 customers who ordered nothing in Q3 have no deliveries, so they have no rows at all. They are invisible, and they are exactly the customers most likely to churn. Any churn analysis built on this file without a join back to the customer list starts by deleting its most important cases. The weekly line plot in Step 7 was fine on this file, because boxes shipped per week really is a question about boxes.
The fix is to aggregate to the grain the question needs. In pandas, deliveries.groupby('customer_id').size() gives boxes per customer, and a join to the customer table restores the attributes and the zero-box customers, who get a count of 0. Then the Step 3 bar plot is correct again.
The core of it: every count, histogram and proportion is computed per row, so it answers a question about whatever a row represents. Ask "one row equals one what?" before charting, and aggregate to the grain the question is about.
Choosing the chart under exam pressure
Scenario questions describe the data and the goal in a sentence or two. The table below maps the words a question stem tends to use to the method they point to, including the pairs people confuse.
| Words in the stem | Points to | Commonly confused with, and why that is wrong |
|---|---|---|
| Distribution of one numeric feature; shape; skew; bins | Histogram | Bar plot, which counts categories rather than binned numeric ranges |
| Smooth estimate of a distribution; overlaying a few groups; kernel | Density plot | Histogram, which shows binned counts instead of a smoothed curve |
| Median, quartiles, outliers; comparing many groups | Box and whisker plot | Violin plot, which adds shape but takes more space and attention |
| Shape within each group; two peaks; bimodal by group | Violin plot | Box plot, which can hide two peaks inside one box |
| Does the feature (or residual) follow a normal or other theoretical distribution; tails | Q-Q plot | Histogram, which shows shape but leaves the fit to eyeballing |
| Frequency of each category; counts per level | Bar plot | Histogram, which is for numeric ranges |
| Relationship between two numeric features; nonlinear; heteroscedastic | Scatter plot | Line plot, which implies an ordered sequence such as time |
| All pairwise relationships among several numeric features | Scatter plot matrix | Correlation plot, which shows only one summary number per pair |
| Matrix of correlation coefficients; screen for multicollinearity | Correlation plot | Scatter plot matrix, which shows raw points but does not scale to many features |
| Values across two categorical dimensions; hour by weekday; color-encoded grid | Heat map | Correlation plot, which is only the special case of a correlation matrix |
| Trend over time; ordered sequence; weekly or monthly values | Line plot | Scatter plot, which does not connect points in sequence |
| Flow; movement between states; source and target; width proportional to quantity | Sankey diagram | Heat map of a transition table, which shows the counts but not the flow |
| One variable at a time; describe each feature | Univariate analysis | Multivariate analysis, which looks at relationships between features |
| One row per event; per transaction; per order | Check the object; aggregate first | Charting directly, which counts events instead of entities |
| Ordered categories with unequal gaps; rating; tier; size band | Ordinal | Continuous, which assumes equal spacing |
| Labels with no order; codes; IDs; color; region | Nominal | Discrete, which describes counts that support arithmetic |
| Exactly two values; yes/no; 0/1; flag | Binary | Discrete, because the numbers are labels, not counts |
| Count of something; number of events | Discrete | Continuous, which describes measurements on a scale |
| Measured quantity; time, weight, money, temperature | Continuous | Discrete, which applies only when values come from counting |
Common misconceptions
- "A column stored as numbers is a numeric feature." Storage reflects how a computer holds values. plan_tier (1, 2, 3) is ordinal, postal codes and customer IDs are nominal, and a 0/1 flag is binary. Averaging them produces numbers that mean nothing.
- "A bar plot always shows counts." Some bar plots, such as seaborn's barplot, show a group mean with a confidence interval. A count plot shows frequencies. Read the axis label before interpreting bar heights.
- "A correlation near zero means the features are unrelated." Pearson's r measures linear association only. Four points on y = x2 give r = 0 despite a perfect relationship, and Spearman's rank correlation misses U-shapes too. Draw the scatter plot.
- "A box plot shows the shape of a distribution." It shows five landmarks and flagged outliers. Two humps, or a gap, can sit inside a single box. Use a histogram or a violin plot when shape matters.
- "EDA means making charts." NIST treats EDA as an approach: deciding what a row is, what each feature is, which views to draw, and what each finding implies for modeling. Charts are its tools.
- "Continuous means the same thing everywhere." In levels-of-measurement terms, continuous means interval or ratio. In data science, continuous contrasts with discrete. A count is ratio level and discrete at the same time.
Putting it together
- Confirm the grain before charting by asking "one row equals one what?" A table with one row per event counts events, overweights heavy users, and drops objects with zero events entirely.
- Attributes describe what an object is at the snapshot (region, tier). Behaviors describe what it did over a stated window (boxes ordered, churned). A behavior measured after the outcome, or in the same window as it, can leak into a model, so model features need a window that ends before the outcome window.
- Nominal means unordered categories, ordinal means ordered categories with unequal or unknown gaps, binary means exactly two values, discrete means counts, and continuous means measurements. Classify by meaning, not storage type.
- Use bar plots for categories. For numeric distributions use histograms (binned counts), density plots (KDE curves set by a bandwidth), box and whisker plots (quartiles and outliers) and violin plots (KDE shape per group). Box plots can hide two humps that a violin plot shows.
- Tukey's box plot fences are Q1 - 1.5 IQR and Q3 + 1.5 IQR. With Q1 = 38.20 and Q3 = 52.60, they are 16.60 and 74.20.
- A Q-Q plot sets sorted data against theoretical quantiles at p = (i - 0.5)/n. A straight line means a good fit. An upward bend at the right end means right skew, and an S shape means heavy tails.
- Pearson's r measures only linear association. y = x2 on x = -2, -1, 1, 2 gives r = 0, and Spearman also gives 0 for a U-shape, so always check the scatter plot behind a coefficient.
- A scatter plot matrix shows all k(k - 1)/2 pairs (10 pairs for 5 features). A correlation plot summarizes those pairs as a matrix, usually drawn as a heat map. A heat map is any matrix of values drawn as color.
- Line plots need an ordered x-axis, usually time. Sankey diagrams show flows between states, built from source, target and value links, with widths proportional to quantity; check that the flows are conserved before drawing.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- NIST. (n.d.). 1.1.1 What is EDA? (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- Penn State World Campus. (n.d.). Levels of Measurement (COMM 310). courses.worldcampus.psu.edu
- seaborn.pydata.org. (n.d.). API reference (seaborn). seaborn.pydata.org
- seaborn.pydata.org. (n.d.). An introduction to seaborn. seaborn.pydata.org
- NIST. (n.d.). Exploratory Data Analysis (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- NIST. (n.d.). 1.3.3 Graphical Techniques: Alphabetic (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- Plotly. (n.d.). Sankey Diagram in Python. plotly.com
- Matplotlib. (2019). Sankey API. matplotlib.org
- Key terms
- Exploratory data analysis (EDA)
- An approach to studying a data set, mostly through graphs, that looks for structure, outliers and violated assumptions before a model is chosen.
- Grain (unit of observation)
- The entity that one row of a table describes, such as one customer or one delivery. Every count and distribution computed from the table refers to this entity.
- Univariate analysis
- Examining one variable at a time for its categories and frequencies, or for its center, spread, shape and outliers.
- Multivariate analysis
- Examining two or more variables together to find relationships, group differences and interactions, for example with scatter plots or correlation matrices.
- Ordinal variable
- A categorical variable whose categories have a natural order but no guarantee of equal spacing, such as a 1-to-5 rating or Basic, Plus and Premium plan tiers.
- Nominal variable
- A categorical variable whose categories have no order, such as region or postal code. Numbers used as codes for it are labels, not quantities.
- Discrete variable
- A numeric variable whose values can be counted, usually whole numbers produced by counting, such as the number of orders in a quarter.
- Q-Q plot
- Quantile-quantile plot: a plot of a variable's sorted values against the matching quantiles of a theoretical distribution or a second data set. Points on a straight line indicate the distributions match.
- Violin plot
- A chart that draws a kernel density estimate as a mirrored shape for each group, often with box plot statistics inside, so the full distribution shape can be compared across groups.
- Sankey diagram
- A flow diagram built from source, target and value links, in which each band's width is proportional to the quantity flowing between two states.
Diagnosing Common Data Problems
- Diagnose each data issue named in DataX objective 2.2 from evidence such as autocorrelation patterns, residual plots, VIF values, row counts after a join and matrix density.
- Choose a first remedy for each issue, such as differencing, lag features, seasonal terms, aggregation to a common grain, ridge or PCA, sparse storage, transformations or new features, and state what the remedy costs.
- Compute first and seasonal differences, a variance inflation factor and a two-variable Mahalanobis distance by hand, and interpret each result.
A 0.91 correlation that pointed the wrong way
Here is a fictional review packet from a regional coffee chain. An analyst has eight months of figures, January to August, for monthly sales and monthly advertising spend, both in thousands of dollars. The slide says that sales and ad spend correlate at r = 0.91, so same-month advertising drives sales, so the chain should raise the ad budget in any month where it wants more sales. The correlation is computed correctly. The conclusion is wrong in three separate ways, and each one leads to a data problem CompTIA expects you to recognize.
Exam objectives: 2.2 Given a scenario, analyze common issues with data.[1] The objective names ten issues: difference observations, sparse data (in two forms, sparse matrices and sparse vectors), non-linearity, non-stationarity, lagged observations, multicollinearity, seasonality, granularity misalignment, insufficient features and multivariate outliers. In every one of them, a model can look healthy on paper while learning the wrong thing.
The packet's data follow, with three derived columns you will need. The symbol Δ (delta) means change from the previous month, so Δ sales for March is March sales minus February sales. The last column puts the previous month's Δ ad on the current row.
| Month | Sales | Ad spend | Δ sales | Δ ad | Δ ad, previous month |
|---|---|---|---|---|---|
| Jan | 100 | 10 | none | none | none |
| Feb | 103 | 13 | 3 | 3 | none |
| Mar | 108 | 13 | 5 | 0 | 3 |
| Apr | 110 | 17 | 2 | 4 | 0 |
| May | 116 | 16 | 6 | -1 | 4 |
| Jun | 117 | 18 | 1 | 2 | -1 |
| Jul | 121 | 23 | 4 | 5 | 2 |
| Aug | 128 | 21 | 7 | -2 | 5 |
We will debug the packet first. Then we take each remaining issue on the objective list the same way: a plausible wrong reading, the point where the reasoning breaks, the fix, and what the fix costs.
Bug one: two upward trends always correlate (non-stationarity)
Look at the levels. Sales climb from 100 to 128 and ad spend from 10 to 21. Pearson's r asks whether two variables sit above or below their own means at the same time. In a trending series, the early months sit below the mean and the late months sit above it, for both variables, whatever happens from one month to the next. In this packet the January and August rows alone contribute about 152 of the 259 units in the numerator of r. That is roughly 59 percent of the evidence from two months out of eight. The 0.91 mostly says that both numbers were small in winter and large in summer.
The property that is missing is stationarity. The NIST/SEMATECH e-Handbook of Statistical Methods (NIST is the US National Institute of Standards and Technology) describes a stationary process as one whose mean, variance and autocorrelation structure do not change over time.[2] Put more briefly, a stationary series behaves the same way whenever you happen to observe it. It follows that a series with a trend, or with seasonality, is not stationary, because its typical value depends on the date. A non-stationary series breaks the assumption behind many time series methods, and behind any regression that treats the months as interchangeable draws from one population.
Why does that break a regression? Ordinary least squares (OLS) standard errors assume errors that are independent with constant variance. Regress one unrelated trending series on another and the residuals inherit the persistence of the trends: each residual looks like the one before it. The standard errors come out far too small, the t statistics far too large, and R-squared high. This is a spurious regression: a strong fit with no relationship behind it.
You can catch non-stationarity in three ways.
- Run sequence plot. Plot the series against time. A drifting level, swings that widen as the level rises, or a shape that repeats on the calendar all signal non-stationarity.
- Autocorrelation function (ACF). The ACF lists the series' correlation with itself at lag 1, lag 2 and so on. For a stationary series the ACF drops to zero fairly quickly, while for non-stationary data it decreases slowly.[3] The lag-1 autocorrelation, r1, is usually large and positive in such data.
- Unit-root tests. The augmented Dickey-Fuller (ADF) test takes non-stationarity (a unit root) as its null hypothesis, so a small p-value is evidence for stationarity. The KPSS test (Kwiatkowski-Phillips-Schmidt-Shin) reverses the roles: its null hypothesis is stationarity. When the two tests agree, the verdict is more convincing than either one alone.
The textbook non-stationary process is the random walk: yt = yt-1 + εt, where εt is white noise, meaning independent random shocks with mean zero. Each value is the last value plus a shock. Random walks are a standard model for stock prices and many other financial and economic series. Two independent random walks often show a large correlation in levels by pure chance, which is exactly the trap in the packet.
Bottom line: a high correlation between two trending series is evidence that both trend, not that one drives the other. Check stationarity before you interpret any regression of one time series on another.
Difference observations: what differencing fixes and what it costs
The standard repair is to stop modeling levels and model changes instead, which means computing the differences between consecutive observations.[3] The first difference of a series y is:
y'(t) = y(t) - y(t-1)These are the difference observations (also called differenced observations) that the objective names. Each row now records how far the quantity moved since the last period instead of where it stood. The Δ columns in the packet are exactly this. Differencing is powerful, but it has costs, and exam scenarios often test those costs rather than the formula.
- You lose rows. The differenced series has only T - 1 values, where T is the original length, because the first observation has no predecessor.[3] The packet loses January. A second difference, y''(t) = y'(t) - y'(t-1) = y(t) - 2y(t-1) + y(t-2), loses two rows. In practice one difference is usually enough.
- The question changes. A model in differences explains changes, not levels. To forecast a level you add each predicted change onto the last known level, and the errors accumulate the further ahead you forecast.
- Over-differencing creates fake structure. If you difference white noise, which was already stationary, the result has a lag-1 autocorrelation of about -0.5. A strongly negative r1 after differencing hints that you differenced once too often.
- Spacing must be regular. A difference across a gap, such as a missing month, is a two-month change pretending to be a one-month change. Fill or flag the gaps before differencing.
- Variance is a separate problem. Differencing stabilizes the mean. A series whose swings grow with its level needs a transformation as well, and logarithms can help stabilize the variance of a time series.[3] A useful side effect is that a difference of logs, log y(t) - log y(t-1), approximately equals the percentage change when changes are small.
- Treat the variables alike. In a regression on time series, it is common to difference all of the variables if any of them need differencing, so that the relationship keeps the same form.[4]
Now rerun the packet on differences. Use March to August, the six months where every derived column exists. The correlation between Δ sales and same-month Δ ad is about -0.72. The sign has flipped. A careless reader would now conclude that advertising hurts sales. That is the second wrong answer, and it comes from a different bug.
Bug two: the effect arrives a month late (lagged observations)
Sometimes the effect of a predictor in a regression is not simple and immediate. Hyndman and Athanasopoulos use advertising as their example: sales in one month can depend on the advertising spend in each of the past few months.[4] A lagged observation is a past value placed on the current row: x(t-1) is the lag-1 value and x(t-12) the lag-12 value.
Check the packet's last column against Δ sales, row by row.
| Month | Δ ad, previous month | 2 + that value | Actual Δ sales |
|---|---|---|---|
| Mar | 3 | 5 | 5 |
| Apr | 0 | 2 | 2 |
| May | 4 | 6 | 6 |
| Jun | -1 | 1 | 1 |
| Jul | 2 | 4 | 4 |
| Aug | 5 | 7 | 7 |
With the lag, the relationship in this made-up data is exact, so r = 1.00. Why, then, was the same-month correlation negative? In this data, ad changes tend to reverse. A big increase is usually followed by a small rise or a cut: 3 then 0, 4 then -1, 5 then -2. So this month's Δ ad tends to move opposite to last month's Δ ad, and last month's change is the one that drives sales. The negative same-month correlation is a side effect of the lag, not a real effect. Six points can only suggest a hypothesis, which you would then test with an experiment of the kind Lesson 10 covers. Still, this is the reading the data support, and it reverses the analyst's recommendation: spend now if you want sales next month.
Applied to one series and its own past, the same idea is autocorrelation. NIST defines the lag-k autocorrelation for measurements Y(1) to Y(N) with mean Ybar as:
sum for i = 1 to N-k of (Y(i) - Ybar) * (Y(i+k) - Ybar)\nr(k) = ---------------------------------------------------------\n sum for i = 1 to N of (Y(i) - Ybar)^2It is an ordinary correlation, except that it compares two values of the same variable at different times.[5] The formula never looks at the time stamps, so it assumes the observations are equally spaced.[5] Many lag bugs start with that assumption. Here are the failures you will meet most often:
- Shifting the wrong way. A lag must bring the past forward to the current row. A shift in the other direction puts the next period's value on the current row. That is a lead: future information the model will not have when it is used.
- Leakage through availability. A value belongs in a feature only if it would be known at prediction time. If a month's ad total is not booked until the 5th of the following month, a model that forecasts on the 1st cannot use even the lag-1 value.
- Lags that cross entities. In a table where several stores are stacked one after another, a plain shift hands store A's last row to store B's first row as its lag.
- Lost rows. A lag of k leaves the first k rows of each entity empty. Drop them or model them explicitly. Do not fill them with zero, because zero means no spend, not unknown.
- Too many lags. Lags 1 to 24 of ten variables add 240 strongly correlated columns, which leads straight to multicollinearity, covered below.
The fictional pandas example below shows the cross-store bug and its fix, with the result of each version side by side. NaN ("not a number") is how pandas marks a missing value.
store month ad ad_lag1 (plain shift) ad_lag1 (shift within store)\nA Jan 10 NaN NaN\nA Feb 13 10 10\nA Mar 13 13 13\nB Jan 40 13 <- store A's March NaN\nB Feb 42 40 40\n\n# buggy: df[\"ad_lag1\"] = df[\"ad\"].shift(1)\n# fixed: df[\"ad_lag1\"] = df.groupby(\"store\")[\"ad\"].shift(1)Lagged observations and difference observations are easy to confuse because both look back one step. A lag copies a past value onto the current row as a separate feature. A difference subtracts the past value from the current one and replaces the series. You can combine them, as the packet does: a lagged difference.
Bottom line: before you read a relationship between time series, line up each cause with the time at which it could act. Use lags that stay inside each entity's rows and use only values known at the moment of prediction.
Bug three: eight months cannot show a year (seasonality)
The packet has a third, quieter bug. For a coffee chain, January to August could be the rising half of an annual cycle, as iced drinks and tourist traffic pick up. NIST describes seasonality as periodic fluctuations, with retail sales that peak for the Christmas season and fall after the holidays as its example.[6] It is common in economic and retail series. With only eight months you cannot tell a trend from the first half of a season. Separating the two needs at least two full cycles, which here means at least 24 months. Worse, managers often raise ad budgets in the months when they already expect demand. Then the season drives both columns, and the slide's recommendation, to spend in the months when you want sales, confuses the calendar with a cause.
How do you detect seasonality once you have enough data?
- Run sequence plot. The plot of the series against time is the usual first step for any time series. It often shows the repetition but not its exact shape.
- Seasonal subseries plot and box plots by season. These group the values by month (or quarter, or weekday) and show the between-group pattern. Both assume you know the period, which for monthly data is usually 12.
- ACF. When the period is unknown, the autocorrelation plot helps: significant seasonality shows up as spikes at lags equal to the period, so for monthly data you expect peaks at lag 12, 24, 36 and so on, although they may weaken further out.[6]
Seasonality, like a trend, violates stationarity, but NIST notes that it is usually built explicitly into the time series model rather than simply removed.[2] The usual options:
| Method | How it works | Suits | Cost |
|---|---|---|---|
| Seasonal dummy variables | One indicator per season, minus one, added as predictors | A fixed pattern with a short period | m - 1 parameters for period m |
| Seasonal differencing | y(t) - y(t-m): this January minus last January | A pattern that drifts slowly, short periods | Loses m observations |
| Seasonal autoregressive integrated moving average (SARIMA) | Seasonal autoregressive and moving-average terms plus seasonal differencing (Lesson 5) | Periods such as 12 or 4 | Estimation becomes hard as m grows |
| Fourier terms | Pairs of sine and cosine waves at the seasonal frequency | Long periods such as 52 weeks or 365 days | You must choose the number of pairs |
Seasonal versions of ARIMA (autoregressive integrated moving average) and exponential smoothing models are designed for short periods, such as 12 for monthly data or 4 for quarterly data.[4] When the seasonal period is long, Hyndman and Athanasopoulos find a dynamic regression with Fourier terms is often the better choice.[4] Sometimes a series needs both a seasonal difference and a first difference before it becomes stationary.[7]
A short worked example shows the row cost. Suppose January sales were 210 in 2025 and 231 in 2026, and February sales 198 and 214. The seasonal differences are 231 - 210 = 21 and 214 - 198 = 16: each month compared with the same month a year earlier. With 60 months of data, a seasonal difference at lag 12 leaves 48 values, and a first difference on top of that leaves 47. Change one input, a weekly series with period 52, and the same two steps on four years (208 weeks) leave only 155 values. That is a quarter of the data gone, which is one reason long periods push you toward Fourier terms.
Granularity misalignment: daily rows meet monthly facts
Granularity, or grain, is the level of detail that one row represents: one transaction, one store-day, one customer-month. Granularity misalignment happens when you combine tables recorded at different grains without reconciling them. The classic case is a join of daily sales to a monthly budget on a month key. Here is a fictional result for one store in March.
| date | store | daily_sales | monthly_ad_budget |
|---|---|---|---|
| 2026-03-01 | S14 | 2,310 | 45,000 |
| 2026-03-02 | S14 | 2,145 | 45,000 |
| 2026-03-03 | S14 | 2,488 | 45,000 |
| ... 27 more rows ... | S14 | ... | 45,000 |
| 2026-03-31 | S14 | 2,402 | 45,000 |
Nothing errors out. The join succeeded, and three problems are now in the data.
- Fake sample size. There is one budget decision for March, but it now appears on 31 rows. A regression treats those as 31 independent observations, so the standard error of the budget coefficient comes out far too small.
- Inflated totals. Anyone who later sums the budget column gets 31 x 45,000 = 1,395,000 for March instead of 45,000.
- Misattributed variation. Daily sales swing between weekdays and weekends, but the budget cannot vary within the month, so the model can only ever explain month-to-month differences with it. Daily noise then looks like weak evidence about the budget.
The fix starts with a decision: which grain matches the question being asked? A monthly budget decision is usually analyzed at the monthly grain. Rolling fine data up to a coarser grain is safe if you pick the right aggregation for each variable. Pushing coarse data down to a finer grain means allocating it, for example spreading the budget across days in proportion to days or to ad impressions, and that allocation is an assumption you must state.
| Kind of variable | Example | Roll up with |
|---|---|---|
| Flow (amount per period) | Sales, ad spend, visits | Sum |
| Stock (level at a moment) | Inventory, account balance | Last value, or the period average |
| Rate or ratio | Conversion rate, average basket | Recompute from summed numerators and denominators; do not average the rates |
| Extreme | Peak temperature, maximum queue length | Maximum or minimum |
Misalignment comes in other forms too. Entity grain: a customer table joined to a household table. Calendar grain: fiscal weeks against calendar weeks, or time stamps stored in Coordinated Universal Time (UTC) against local dates, which can move late-evening sales into the next day. Unit grain: one table in thousands, another in units. A cheap check catches most of them: count the rows and the distinct keys before and after every join, and explain any change. If joins and aggregation are new to you, the Atlas Data+ course covers them from the beginning.
Multicollinearity: predictors that tell the same story
A fictional marketing-mix regression returns the output below. The model's R-squared is 0.88 and its overall F test is highly significant. Yet no spend coefficient is individually significant, and digital spend has a negative sign that nobody believes.
| Predictor | Coefficient | Standard error | VIF |
|---|---|---|---|
| tv_spend | 0.42 | 0.39 | 18.6 |
| digital_spend | -0.15 | 0.36 | 16.2 |
| price | -3.10 | 0.40 | 1.3 |
The plausible wrong reading is that advertising does not work. The real issue is multicollinearity: one predictor can be predicted well from the others. Here the chain raised TV and digital spend together, so the data never show what happens when one moves without the other. The model knows the combined effect well and cannot split it between the two.
The variance inflation factor (VIF) in the last column measures how much of this there is. Regress predictor j on all the other predictors, record that regression's R-squared as Rj2, and compute:
VIF(j) = 1 / (1 - R_j^2)The name describes the mechanism. The sampling variance of the OLS coefficient bj is σ2 / [(1 - Rj2) Σ(xij - x̄j)2], where σ2 is the error variance. That equals the variance bj would have if xj were uncorrelated with the other predictors, multiplied by VIFj. The standard error therefore grows by the square root of the VIF.
Work it both ways. If tv_spend regressed on the other predictors gives Rj2 = 0.95, then VIF = 1 / 0.05 = 20, and the standard error is about 4.47 times larger than it would be with an uncorrelated predictor. Change one input: if Rj2 = 0.50, VIF = 1 / 0.50 = 2, and the standard error grows only by about 1.41. Common rules of thumb flag VIF above 5 or above 10. They are conventions, not laws: a VIF of 6 on a coefficient you never interpret may not matter.
The extreme case is perfect collinearity. Add a total_spend column equal to tv_spend + digital_spend and the design matrix X has an exact linear dependency. The matrix XTX (X transposed times X) becomes singular, which means it cannot be inverted, and OLS has no unique solution: the VIF is infinite. The dummy-variable trap is the same problem: one indicator for every category plus an intercept.
Symptoms in a stem: coefficients that flip sign or change a lot when a few rows are dropped, large standard errors despite a high R-squared, a significant overall F test with no significant individual t tests, and high VIF values. Remedies:
- Drop one of the redundant predictors, or combine them into one, such as total spend.
- Replace the correlated block with principal components (principal component analysis, PCA), accepting that components are harder to interpret.
- Use ridge regression, whose L2 penalty (a penalty on the sum of squared coefficients) shrinks correlated coefficients toward each other and stabilizes them (Lesson 12).
- Collect data where the predictors vary independently, for example a test in which TV and digital spend are changed separately.
Multicollinearity mainly damages interpretation. If the goal is prediction, and the predictors stay correlated in the same way in the future, the combined fit can still forecast well.
Bottom line: high VIF values mean the data cannot separate the predictors' effects. The coefficients become unreliable even when the model as a whole fits well.
Multivariate outliers: ordinary one column at a time, strange together
A fictional human resources (HR) file contains a row with age 22 and 17 years of full-time work experience. Age 22 is common in the file, and so are 17 years of experience. Neither value trips a per-column rule such as |z| > 3, where a z-score measures a value's distance from its column mean in standard deviations. Together the two values are nearly impossible, because the person would have started full-time work at age 5. A multivariate outlier is a point whose combination of values is unusual, given how the variables normally move together, even when each value is unremarkable on its own. It usually signals a data-entry error, a join that merged two people's records, or a genuinely different subpopulation.
The standard detector is the Mahalanobis distance. For a point x, the mean vector μ and the covariance matrix S of the data:
D^2 = (x - μ)^T S^-1 (x - μ)Multiplying by the inverse covariance does two things. It rescales each variable by its spread, and it treats movement along the direction where the variables normally move together as cheap and movement against that direction as expensive. For two standardized variables (mean 0, standard deviation 1) with correlation ρ, the formula reduces to:
D^2 = (z1^2 - 2*ρ*z1*z2 + z2^2) / (1 - ρ^2)Worked example. Two standardized variables have ρ = 0.8. Point A is (2, 2) and point B is (2, -2). Both are the same Euclidean distance from the center, the square root of 8, about 2.83.
- A: (4 - 2(0.8)(2)(2) + 4) / (1 - 0.64) = (8 - 6.4) / 0.36 = 1.6 / 0.36, about 4.44.
- B: (4 - 2(0.8)(2)(-2) + 4) / 0.36 = (8 + 6.4) / 0.36 = 14.4 / 0.36 = 40.0.
To judge these numbers, use the fact that when the data are roughly multivariate normal, D2 follows a chi-squared distribution with p degrees of freedom, where p is the number of variables. For p = 2, the 95th, 99th and 99.9th percentiles are 5.99, 9.21 and 13.82. A, at 4.44, is an ordinary point that lies along the direction in which the variables move together. B, at 40, is far beyond even 13.82, because it is high on one variable and low on the other when the two normally move together. The same Euclidean distance gives opposite verdicts, and the correlation is the reason.
Three cautions. First, masking: the outliers themselves pull the mean and inflate the covariance, which can hide them. Robust estimates such as the minimum covariance determinant reduce this. Second, S must be invertible, so severe multicollinearity makes Mahalanobis distances unstable, which links two issues on the objective list. Third, the chi-squared cut-offs assume approximate normality; heavy-tailed data will flag more points. In every case, flag and investigate a multivariate outlier. Do not delete it automatically: the 22-year-old with 17 years of experience is a data error to correct, but an unusual combination of genuine values may be the most informative record in the file.
Non-linearity: when a straight line is the wrong shape
Take five fictional points: x = -2, -1, 0, 1, 2 and y = 4, 1, 0, 1, 4, so y = x2 exactly. The mean of x is 0, and the sum of x times y is -8 - 1 + 0 + 1 + 8 = 0, so the covariance and Pearson's r are both exactly 0. A linear model reports no relationship, yet y is a perfect function of x. Change one input: add x2 as a feature and the same linear regression fits perfectly.
Non-linearity means the true relationship between a predictor and the target is not a straight line. Correlation and linear regression measure only linear association, so they can understate or completely miss a curved relationship. The main symptom is structure in the residuals: plot the residuals against the fitted values or against each predictor, and look for a U shape, an arch, or a curve that flattens out. A healthy residual plot looks like a featureless band. Do not confuse a curve with a funnel: residuals that fan out as the fitted values grow show heteroscedasticity (error variance that changes with the level), which calls for a transformation or weighted fitting rather than a new shape.
Remedies, roughly in order of how much they change the model:
- Transform a variable. A logarithm turns many diminishing-returns or multiplicative relationships into straight lines.
- Add basis terms. Polynomial terms, splines or interaction terms. A polynomial regression is still linear in its parameters, so OLS, its standard errors and VIF all still apply. Polynomial terms are strongly correlated with each other, though, so centering x before squaring it helps.
- Switch model family. Tree ensembles, kernel methods and neural networks learn curved shapes without being told the form (Lessons 14 to 16).
Keep non-linearity distinct from insufficient features. With non-linearity, the residuals show a pattern against a variable you already have. With insufficient features, the residuals look random against everything you have and are simply large.
Sparse data: sparse matrices and sparse vectors
A fictional retailer builds a customer-by-product purchase matrix: 50,000 customers and 20,000 products, with each customer buying on average 12 distinct products. That gives 600,000 nonzero cells out of 1,000,000,000, a density of 0.06 percent. Stored densely as 8-byte floating-point numbers, the matrix takes 8 GB. The plausible wrong conclusion is that you need a bigger machine.
SciPy's documentation describes sparse arrays as arrays where only a few locations have any data.[8] Because so few cells hold data, a compressed representation can record only the locations where data exist. The documentation's introductory example builds a coordinate-format array from a small dense one:
>>> dense = np.array([[1, 0, 0, 2], [0, 4, 1, 0], [0, 0, 5, 0]])\n>>> sparse = sp.sparse.coo_array(dense)\n>>> sparse\n<COOrdinate sparse array of dtype 'int64'\n with 5 stored elements and shape (3, 4)>The sparse version stores the five nonzero values explicitly and represents all the remaining zeros as implicit values.[8] A sparse matrix is the whole table stored this way. A sparse vector is one row or column of it: a single customer's purchases, a one-hot encoding of one categorical value, or one document's word counts in a bag-of-words or TF-IDF (term frequency inverse document frequency) representation, where a document uses a few hundred words out of a vocabulary of tens of thousands.
Now size the retailer's matrix in compressed sparse row (CSR) form, assuming 8-byte values and 4-byte indexes. CSR keeps three arrays: the nonzero values, the column index of each value, and a row-pointer array with one entry per row plus one. Values take 600,000 x 8 = 4.8 MB, column indexes 600,000 x 4 = 2.4 MB, and row pointers 50,001 x 4, about 0.2 MB. That is roughly 7.4 MB against 8 GB, about a thousand times smaller. The format you choose depends on the job:
| Format | Good for | Weak at |
|---|---|---|
| COO (coordinate) | Building a matrix from (row, column, value) triples; converting to other formats | Arithmetic and slicing |
| CSR (compressed sparse row) | Fast arithmetic, matrix-vector products, slicing rows | Changing the sparsity pattern |
| CSC (compressed sparse column) | Fast arithmetic, matrix-vector products, slicing columns | Changing the sparsity pattern |
| DOK (dictionary of keys) and LIL (list of lists) | Incremental construction and single-element changes | Heavy computation |
SciPy notes that CSR is most useful for fast arithmetic, vector products and slicing by row.[8] CSC is its column-oriented twin, built for the same operations when you slice by column. Sparse arrays in general are less flexible than dense ones for slicing, reshaping or assignment.[8] So build the matrix in COO or LIL, then convert it to CSR or CSC before training.
Sparse data cause problems beyond memory:
- Scaling can destroy sparsity. Standardization subtracts each column's mean, which turns almost every implicit zero into a stored nonzero value, and the matrix silently becomes dense. Scale sparse data without centering, for example by dividing each column by its maximum absolute value.
- Euclidean distance measures the wrong thing. Two customers' sparse vectors rarely share a nonzero. When they share none, the Euclidean distance between them is the square root of the sum of their two squared lengths, so it is dominated by how much each customer bought and by the purchases that do not overlap, not by whether they bought alike. Cosine similarity divides by both vectors' lengths, which normalizes for size, and its numerator, the dot product, involves only the shared nonzeros. That makes it the usual choice for text and baskets.
- Many columns, little evidence per column. A product bought by three customers adds a column the model can only memorize. Remedies include minimum-frequency thresholds, L1 regularization (LASSO, least absolute shrinkage and selection operator, which penalizes the sum of absolute coefficients and can set some to zero), feature hashing and truncated singular value decomposition (SVD), which compresses the columns without first centering them.
- Zero is not missing. In a purchase matrix an implicit zero means did not buy. In a ratings matrix an empty cell means not rated, which is unknown. Treating unknown as zero tells a recommender that every customer hates every product they have not rated.
Bottom line: sparse data are mostly zeros that mean none. Store them in a sparse format, keep them sparse through preprocessing, and never let a zero stand in for an unknown.
Insufficient features: when no model can find the signal
A fictional telecom churn model reaches an area under the ROC curve (receiver operating characteristic, Lesson 2) of 0.62 on training data and 0.61 on validation data. The team replaces logistic regression with gradient boosting, then with a deeper boosted model. Neither score moves. The plausible wrong answers are that they need a cleverer algorithm or more rows.
Read the two numbers together. Training and validation scores are close, so the model is not overfitting, which would show as a training score well above the validation score. Both are low, so the model has high bias. When more flexible models also fail to improve, the limit is not the algorithm but the information in the inputs. That is insufficient features: the available variables do not carry enough signal about the target.
This fictional case is the clean version. Real projects rarely look so tidy: a more flexible model usually does lift the training score, by fitting noise, while the validation score stays flat. So do not wait for both numbers to freeze. The reliable sign of insufficient features is a validation score that will not improve however you change model complexity or add rows. A learning curve confirms it. Adding rows narrows a gap between the training and validation curves, but when the validation curve has already flattened at a low score, more rows of the same columns will not lift it.
The diagnosis usually comes from error analysis and from talking to people who know the domain. Suppose customer-care staff point out that most cancellations happen within 30 days of a contract ending, and the table has no contract end date. That single engineered feature, days until contract end, may do more than any change of model. Remedies include engineering features from data you already hold (recency, counts, ratios, lags), acquiring new sources (Lesson 8), and reframing the target. Two limits apply. Every new feature must be available at prediction time, or you have built leakage. And some targets are partly unpredictable, so there may be a ceiling that no feature set reaches.
Exam cues: what the stem says and what it points to
Scenario questions describe a symptom and expect you to name the issue or the first fix. Read the table across, and pay most attention to the last column, where the traps are.
| The stem says | Points to | First move | Often confused with |
|---|---|---|---|
| ACF decays slowly, r1 near 1, upward drift, unit root | Non-stationarity | First difference; log if swings grow with the level | Seasonality, which shows spikes at fixed lags |
| Spikes at lags 12, 24, 36; peaks every December | Seasonality | Seasonal dummies, seasonal difference, SARIMA or Fourier terms | A trend, which is one-directional |
| y(t) - y(t-1), model of changes, one fewer row | Difference observations | Track lost rows; add changes back onto the last level to forecast | Lagged observations, which copy rather than subtract |
| Effect appears weeks later; previous period's value | Lagged observations | Lag features shifted within each entity | Leads, which leak future values |
| Daily rows joined to monthly values; repeated values; inflated totals | Granularity misalignment | Aggregate to one grain with the right function | Duplicate records |
| VIF above 10; signs flip; large standard errors despite a high R-squared | Multicollinearity | Drop or combine predictors, PCA, ridge | Multivariate outliers |
| Normal on each variable, odd combination; Mahalanobis | Multivariate outliers | Investigate; use a robust covariance | Univariate outliers found by z-scores |
| U-shaped residuals; r near 0 with an obvious pattern | Non-linearity | Transform, polynomial or spline terms, or a non-linear model | Heteroscedasticity (a funnel) or insufficient features |
| Mostly zeros; one-hot; bag of words; memory error | Sparse data | CSR or CSC storage; scale without centering; truncated SVD | Missing data |
| Validation score stays low whatever the model or row count | Insufficient features | Engineer or acquire informative features | Overfitting, where a model change could still help |
Common misconceptions
- A high R-squared between two time series proves they are related. Two trending series correlate strongly whether or not they are connected. Difference them, or test for stationarity, before reading the fit.
- Differencing is a free cleanup step. It removes one row per first difference and m rows per seasonal difference, changes the model from levels to changes, and differencing too often creates a lag-1 autocorrelation near -0.5.
- Multicollinearity makes a model's predictions bad. It mainly makes individual coefficients unstable and hard to interpret. Predictions can stay good as long as the predictors remain correlated in the same way.
- An outlier must be extreme on at least one variable. A multivariate outlier can be ordinary on every variable and still be extreme in combination, which only a covariance-aware measure such as Mahalanobis distance shows.
- Sparse means missing. In a sparse matrix the implicit zeros usually mean none. Missing means unknown, and filling unknowns with zeros adds false information.
- More rows will fix any weak model. When the validation score has flattened at a low level, the inputs lack signal. More rows of the same columns will not help, but better features might.
Pulling it together
- A stationary series has a mean, variance and autocorrelation structure that do not change over time. Trends and seasonality break stationarity. A slowly decaying ACF with a large positive r1 is the classic symptom.
- A first difference, y(t) - y(t-1), stabilizes the mean and loses one observation. A seasonal difference at lag m loses m observations, so 60 months with both steps leave 47. Logarithms, not differences, stabilize growing variance.
- Lag features must bring past values forward within each entity and use only values known at prediction time. A shift in the other direction creates leakage.
- Seasonality appears as ACF spikes at multiples of the period: 12, 24 and 36 for monthly data. Seasonal ARIMA suits short periods such as 12 or 4. Fourier terms suit long periods such as 52 or 365.
- Granularity misalignment copies a coarse value onto many fine rows, faking sample size and inflating totals. Fix it by choosing one grain: sum flows, take the last value of stocks, and recompute rates from their parts.
- VIF(j) = 1 / (1 - R_j^2). An R_j^2 of 0.90 gives a VIF of 10, and the coefficient's standard error grows by the square root of the VIF. Perfect collinearity makes X^T X singular.
- Mahalanobis distance flags unusual combinations of values. For two variables, compare D^2 with the chi-squared cut-offs of 5.99 (95 percent) and 13.82 (99.9 percent), and investigate a flagged point rather than deleting it automatically.
- Sparse data store only the nonzeros: CSR is efficient for row operations and CSC for column operations. Centering destroys sparsity, and an implicit zero means none, not unknown.
- Non-linearity leaves curved residuals against a variable you have; a funnel means heteroscedasticity instead. Insufficient features show as a validation score that stays low whatever model or row count you try.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Stationarity (Process Modeling/Box-Jenkins). itl.nist.gov
- Rob J. Hyndman and George Athanasopoulos. (2021). 9 ARIMA models (9.1 Stationarity and differencing). OTexts, Forecasting: Principles and Practice (3rd ed.). otexts.com
- Rob J. Hyndman and George Athanasopoulos. (2021). 10.2 Regression with ARIMA errors using fable. OTexts, Forecasting: Principles and Practice (3rd ed.). otexts.com
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Autocorrelation plot / related EDA page. itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Seasonality. itl.nist.gov
- Rob J. Hyndman and George Athanasopoulos. (2021). 9.9 Seasonal ARIMA models. OTexts, Forecasting: Principles and Practice (3rd ed.). otexts.com
- SciPy. (n.d.). Sparse Arrays (scipy.sparse). docs.scipy.org
- Key terms
- Stationarity
- The property of a time series whose mean, variance and autocorrelation structure do not change over time, so its statistical behavior does not depend on when it is observed.
- Difference observations
- Values created by subtracting an earlier observation from a later one, such as y(t) - y(t-1) for a first difference or y(t) - y(t-12) for a monthly seasonal difference. Used to remove trend or seasonality, at the cost of the first rows of the series.
- Lagged observation
- A past value of a variable placed on the current row as a feature, such as last month's ad spend. It is valid only if the value would be known at the time a prediction is made.
- Seasonality
- Periodic fluctuation in a time series tied to the calendar or another fixed cycle, visible in the autocorrelation function (ACF) as spikes at lags equal to the period and its multiples.
- Granularity misalignment
- An error from combining data recorded at different levels of detail, such as daily sales joined to monthly budgets. Coarse values are copied onto many fine rows, which inflates totals and the apparent sample size.
- Variance inflation factor (VIF)
- A multicollinearity measure for one predictor, equal to 1 / (1 - R-squared) from regressing that predictor on all the others. The coefficient's standard error grows by the square root of the VIF.
- Multivariate outlier
- An observation whose combination of values is unusual given how the variables normally move together, even though each value is ordinary on its own. It is usually detected with Mahalanobis distance.
- Sparse matrix
- A matrix in which most entries are zero, stored in a compressed format such as compressed sparse row (CSR) or compressed sparse column (CSC) that records only the nonzero values and their positions.
- Sparse vector
- A single row or column in which nearly all entries are zero, such as a one-hot encoding or one document's word counts over a large vocabulary.
- Insufficient features
- A situation in which the available input variables do not carry enough information about the target, so validation performance stays poor however the model's complexity or the number of rows is changed.
Enriching and Augmenting Data
- Choose an encoding, ratio, cross-term, linearizing transform, Box-Cox transformation or binning step for a given feature and model, and explain why it fits that model's assumptions.
- Calculate standardization, min-max scaling, robust scaling and Box-Cox values by hand, learning every parameter from training data only.
- Use pivoting and geocoding to reshape and enrich raw records, and recognize the leakage, coverage and privacy risks that come with each.
- Decide when external data sets, data augmentation or synthetic data are the right addition, and which data splits each may touch.
41,800 appointments and a 9 percent no-show rate
A fictional veterinary group with four clinics, called Northfield Vets in this lesson, exports 41,800 appointment rows from its booking system for 2025. In 3,762 of them, exactly 9 percent, the client never arrived and a vet waited beside an empty exam table. The practice manager wants a model that flags risky bookings so front-desk staff can phone those clients and offer the slot to someone on the waiting list. The model scores each booking seven days before the appointment, or at the moment of booking when the appointment is less than a week away. You are the data scientist, and the export looks like this:
| appt_id | client_id | booked_at | appt_at | appt_type | species | client_tier | address | no_show |
|---|---|---|---|---|---|---|---|---|
| A-50211 | C-1042 | 2025-03-01 | 2025-03-04 | Vaccination | Dog | Gold | 12 Orchard Ln, Northfield, MN | 0 |
| A-50212 | C-2210 | 2025-01-20 | 2025-03-04 | Dental | Cat | Bronze | 9 Mill St, Dundas, MN | 1 |
| A-50213 | C-0388 | 2025-03-04 | 2025-03-04 | Checkup | Rabbit | Silver | 405 Pine Ave, Faribault, MN | 0 |
| A-50214 | C-1042 | 2025-02-10 | 2025-03-05 | Surgery | Dog | Gold | 12 Orchard Ln, Northfield, MN | 0 |
Almost nothing here can go straight into a model. The dates are text. Appointment type is a word. The address is a sentence, not a number. And the client's own history, probably the strongest predictor of a missed appointment, sits in a different table. This lesson follows the Northfield data from that export to a model-ready feature matrix. Each technique on the exam's list appears at the point where the data needs it.
Exam objectives: CompTIA DataX DY0-001 objective 2.3, "Given a scenario, apply data enrichment and augmentation techniques."[1] The objective lists feature engineering and data transformation (one-hot encoding, label encoding, cross-terms, linearization in logarithmic and exponential forms, the Box-Cox transformation, normalization, binning, ratios and pivoting), then geocoding, scaling, standardization and additional data sources (data augmentation, data sets and synthetic data).
You should be comfortable with logistic regression, means and standard deviations, and train/test splits. Lesson 3 covered synthetic data in depth and Lesson 7 covered missing data and multicollinearity; this lesson builds on both. If descriptive statistics feel rusty, the Atlas Data+ course reviews them.
Feature engineering and data transformation
Feature engineering is the work of building the inputs a model learns from. You decide which raw fields to keep, which new columns to derive, and what form to give them. A data transformation is a single operation that changes how a column is represented, such as taking its logarithm or splitting a category into indicator columns. Feature engineering is the goal and transformations are most of its tools, which is why the exam lists them together.
Two questions settle most transformation choices. The first is what the model assumes. A linear or logistic regression adds up feature effects along straight lines, so curves must be straightened and interactions written out as columns. Distance-based methods, such as k-nearest neighbors (KNN) and support vector machines (SVM) with a radial basis function (RBF) kernel, compare raw numeric distances. A feature measured in thousands drowns one measured in fractions. Decision trees and their ensembles split on thresholds, so rescaling barely affects them, and neither does any transformation that keeps the values in the same order.
The second question is what will be known when the prediction is made. Northfield's model scores a booking seven days before the appointment, or immediately for bookings made inside that window. A feature built from information that arrives later, such as the day's actual weather or the appointment's own outcome, leaks the answer into training. The model then scores well in testing and fails at the front desk.
| Technique | What it changes | Models that depend on it most |
|---|---|---|
| Pivoting | Reshapes rows into columns, or columns into rows | Any model that needs one row per entity |
| Ratios | Divides one quantity by another | Linear models, which cannot divide on their own |
| One-hot encoding | One category column becomes several 0/1 columns | Linear, distance-based and neural models |
| Label (ordinal) encoding | Categories become integers | Ordered categories, tree models, target labels |
| Cross-terms | Adds the product of two features | Linear and logistic models |
| Linearization (log, exponential) | Straightens a curved relationship | Linear models |
| Box-Cox transformation | Reshapes a skewed positive variable toward normal | Linear models, normal-theory tests |
| Binning | Continuous values become intervals | Linear models that need a stepwise effect; reporting |
| Geocoding | Address text becomes coordinates | Any model that needs location |
| Scaling, standardization, normalization | Puts features on comparable numeric ranges | Distance-based, gradient-trained and penalized models |
| Additional data sources | Adds columns or rows from outside the table | Any model short of signal or examples |
Key idea: pick a transformation by asking what the model assumes and what is known at prediction time. Then learn every fitted parameter of that transformation from training rows only.
Pivoting the visit history from long to wide
Northfield's visit log stores one row per past appointment. That is long format, with many rows per client. The model needs wide format: one row per client and one column per thing worth counting. Turning the first into the second is pivoting, and the reverse is unpivoting.
| client_id | appt_at | status |
|---|---|---|
| C-1042 | 2024-06-11 | attended |
| C-1042 | 2024-09-30 | attended |
| C-1042 | 2024-12-02 | attended |
| C-2210 | 2024-05-14 | no_show |
| C-2210 | 2024-08-21 | attended |
| C-2210 | 2024-11-19 | no_show |
| C-2210 | 2024-12-28 | cancelled |
| C-0388 | 2024-10-07 | attended |
In pandas, pivot() and pivot_table() group the unique values of one or more categories into a new grid of rows and columns.[2] The difference between the two matters here. The pandas documentation says pivot() can handle only unique combinations of index and column values, and it sends you to pivot_table() when there are duplicates.[2] Client C-2210 has two no_show rows, so the pair (C-2210, no_show) occurs twice and pivot() would raise an error. pivot_table() is built for pivoting with aggregation, so you tell it how to combine duplicates, here by counting them.[2]
cutoff = pd.Timestamp('2025-01-01')
history = visits[visits['appt_at'] < cutoff]
counts = history.pivot_table(index='client_id', columns='status',
values='appt_at', aggfunc='count', fill_value=0)
| client_id | attended | cancelled | no_show |
|---|---|---|---|
| C-0388 | 1 | 0 | 0 |
| C-1042 | 3 | 0 | 0 |
| C-2210 | 1 | 1 | 2 |
Two details in that code carry real weight. The cutoff keeps only visits before the period being predicted. If you pivot the full log, appointment A-50212's own no-show lands in C-2210's count, and the model learns from the answer. In production you compute the counts as of each scoring date rather than using one fixed cutoff, but the rule is the same: history means strictly earlier. A same-day booking simply uses whatever history exists at the moment it is made. The fill_value=0 setting records "no cancelled visits" as a zero rather than a missing value. That is correct here, because the absence of a row really does mean zero events.
Going the other way is just as common. A sales export with one column per month (jan_sales, feb_sales and so on) is wide, but a time-series model wants one row per store per month. pandas' melt() unpivots a wide DataFrame into long format.[2] In an exam stem, "one row per event, need one row per customer" points to pivoting, and "one column per period, need a date column" points to melting.
Ratios: turning two counts into one rate
Counts mislead when clients differ in volume. C-2210 has two no-shows, but a loyal client with forty visits might have two as well. A ratio divides one quantity by another so the result compares fairly across rows: no-shows per visit, spend per visit, cats per household, staff per hundred appointments. Ratios also give a linear model something it cannot build alone. A logistic regression can add and weight features, but it cannot divide one by another. If the meaningful quantity is a rate, you have to compute it.
Define the prior no-show ratio as no_show / (attended + no_show), counting only appointments that reached their date. Cancellations stay out of the denominator because a cancelled visit was never a chance to miss. From the pivot, C-1042 scores 0 / 3 = 0, C-2210 scores 2 / 3 = 0.67 and C-0388 scores 0 / 1 = 0. A brand-new client scores 0 / 0, which is undefined.
Two problems are already visible. The new client needs a value, and C-0388's zero rests on a single visit, which is weak evidence of reliability. A standard fix is a smoothed ratio that pulls small-sample ratios toward the overall rate:
smoothed ratio = (no_shows + m × p) / (visits + m)
Here p is the overall no-show rate, and m is how many visits' worth of weight that prior receives. Because p is a fitted parameter, compute it from the training period only, never from the full year that includes the test months. This example uses p = 0.09 for illustration and m = 5, so m × p = 0.45.
| Client | No-shows | Visits | Raw ratio | Smoothed ratio |
|---|---|---|---|---|
| C-1042 | 0 | 3 | 0.00 | (0 + 0.45) / (3 + 5) = 0.056 |
| C-2210 | 2 | 3 | 0.67 | (2 + 0.45) / (3 + 5) = 0.306 |
| C-0388 | 0 | 1 | 0.00 | (0 + 0.45) / (1 + 5) = 0.075 |
| New client | 0 | 0 | undefined | (0 + 0.45) / (0 + 5) = 0.090 |
The smoothed column keeps the ordering the evidence supports, with C-2210 riskiest, but it no longer claims one visit proves a client perfect. Notice that C-0388, with one clean visit, now sits above C-1042, with three. That is the point: more clean visits are more evidence. A client with 40 visits and 10 no-shows would move only from 0.250 to (10 + 0.45) / 45 = 0.232, because forty visits outweigh the prior. Keep the denominator (visit count) as its own feature too, since a ratio hides how much evidence stands behind it.
One-hot encoding and label encoding
Appointment type takes four values: Checkup, Dental, Surgery and Vaccination. None is "more" than another. Suppose you store them as the integers 0 to 3 in alphabetical order. A logistic regression gives that column a single coefficient, which forces Surgery's effect to sit exactly halfway between Dental's and Vaccination's, with Vaccination three equal steps from Checkup. Those constraints come from the alphabet, not from clients.
One-hot encoding removes the false order by giving each category its own 0/1 indicator column. scikit-learn's OneHotEncoder encodes categorical features as a one-hot numeric array.[3] In pandas, get_dummies() performs the same conversion to indicator variables.[2]
| appt_id | Checkup | Dental | Surgery | Vaccination |
|---|---|---|---|---|
| A-50211 | 0 | 0 | 0 | 1 |
| A-50212 | 0 | 1 | 0 | 0 |
| A-50213 | 1 | 0 | 0 | 0 |
| A-50214 | 0 | 0 | 1 | 0 |
Each row has exactly one 1, which creates a trap for linear models with an intercept. The four indicator columns always sum to 1, the same as the intercept column, so any one of them is an exact linear combination of the rest. That is perfect multicollinearity, the case where Lesson 7's variance inflation factor (VIF) becomes infinite and ordinary least squares (OLS) has no unique solution. For an unpenalized linear model, drop one column, the reference category. Each remaining coefficient then measures the difference from that reference. Penalized models such as ridge regression and the least absolute shrinkage and selection operator (LASSO) usually keep every column, because the penalty picks one solution. Tree models keep them too.
Label encoding maps each category to an integer. The term is used in two ways, and the exam can mean either. In scikit-learn, LabelEncoder is meant for the target: it encodes target labels as integers from 0 to n_classes - 1.[3] Northfield's no_show target is already 0/1, but a three-class target (attended, cancelled, no_show) would become 0, 1, 2. For input features, the scikit-learn tool is OrdinalEncoder, which encodes categorical features as an integer array.[3] pandas offers factorize() for the same single-column job.[2]
Integer codes are the right choice when the categories really are ordered. Northfield's client_tier runs Bronze, Silver, Gold, and one ordered column of 0, 1, 2 lets the model learn a single tier effect. Watch the default, though. Both LabelEncoder and OrdinalEncoder sort categories alphabetically unless told otherwise. That gives Bronze = 0, Gold = 1, Silver = 2 and puts Gold in the middle. Pass the order explicitly, as the pipeline at the end of this lesson does.
| Column | Values | Ordered? | Encoding | Reason |
|---|---|---|---|---|
| appt_type | Checkup, Dental, Surgery, Vaccination | No | One-hot | No order to preserve |
| species | Dog, Cat, Rabbit, Bird | No | One-hot | No order to preserve |
| client_tier | Bronze, Silver, Gold | Yes | Ordinal 0, 1, 2 with the order set explicitly | One coefficient for one ordered scale |
| no_show (target) | 0, 1 | Not applicable | Label encoding | Target labels are mapped to integers 0 to n_classes - 1 (LabelEncoder); already done here |
| breed | About 300 values | No | Target encoding, or group rare breeds first | One-hot would add 300 sparse columns |
The last row is the high-cardinality case. One-hot encoding 300 breeds adds 300 mostly empty columns, and rare breeds get coefficients estimated from a handful of rows. scikit-learn's TargetEncoder, available for regression and classification targets, replaces each category with a value learned from the target.[3] Because that value comes from the target, it must be learned out-of-fold, or each row's own label leaks into its feature. Grouping rare breeds into one Other category before one-hot encoding is the simpler alternative.
Key idea: one-hot encode categories that have no order. Use ordinal or label encoding only when the order is real, and set that order yourself. Reserve LabelEncoder for target labels.
Cross-terms: when rain matters more for distant clients
The front desk has a theory: rain keeps people home, but mostly people who live far away. With separate distance and rain features, a logistic regression cannot express that. It shifts the log-odds by the same rain amount for everyone, whether they live one kilometer away or ten. A cross-term, also called an interaction term, is a new feature made by multiplying two existing ones. It lets one feature's effect depend on the other's level. scikit-learn's PolynomialFeatures generates polynomial and interaction features automatically.[3]
Write distance in kilometers as d and a forecast-rain indicator as r (1 if rain is forecast, 0 if not). With the cross-term, the model's log-odds of a no-show are:
log-odds = b0 + b1d + b2r + b3(d × r)
When r = 0, the last two terms vanish and each kilometer adds b1. When r = 1, each kilometer adds b1 + b3. So b3 is exactly "how much more each kilometer matters in the rain." Suppose the fitted model (fictional values) gives b0 = -3.0, b1 = 0.04, b2 = 0.2 and b3 = 0.06. Convert log-odds to a probability with p = 1 / (1 + e-log-odds).
| Client | d (km) | r | Log-odds | Probability of no-show |
|---|---|---|---|---|
| Near, dry | 1 | 0 | -3.0 + 0.04 = -2.96 | 1 / (1 + e2.96) = 0.049 |
| Near, rain | 1 | 1 | -3.0 + 0.04 + 0.2 + 0.06 = -2.70 | 1 / (1 + e2.70) = 0.063 |
| Far, dry | 10 | 0 | -3.0 + 0.40 = -2.60 | 1 / (1 + e2.60) = 0.069 |
| Far, rain | 10 | 1 | -3.0 + 0.40 + 0.2 + 0.60 = -1.80 | 1 / (1 + e1.80) = 0.142 |
Read the rows in pairs. For the client one kilometer away, forecast rain raises the risk by about 1.4 percentage points. For the client ten kilometers away, the same forecast roughly doubles it, a rise of 7.3 points. Without the cross-term the model must choose one rain effect for both clients, and that single effect is wrong for both. Notice also that r is the forecast available at scoring time, not the rainfall measured on the day. Training on measured rainfall would teach the model a signal it never has when it predicts.
Cross-terms have a cost. With k features there are k(k - 1) / 2 pairwise products, so 50 features give 1,225 candidate interactions, most of them noise. Add the products a real mechanism suggests, or generate them all and let regularization prune them. Tree ensembles build many interactions on their own, because a split on distance beneath a split on rain already is one.
Linearization: logarithmic and exponential relationships
Linearization means transforming a feature, the target, or both, so that a curved relationship becomes a straight line a linear model can fit. The skill is recognizing the shape of the curve, because each shape has its own fix. The exam names two: exponential and logarithmic.
An exponential relationship grows by a constant percentage for each unit step: y = a ebx. Take the natural log of both sides and you get ln y = ln a + bx, a straight line in x with slope b. So you linearize an exponential relationship by logging the target. Northfield's online bookings (fictional) grew 20 percent a month after it launched a booking app:
| Month | Bookings | Change in bookings | ln(bookings) | Change in ln |
|---|---|---|---|---|
| 1 | 200 | 5.298 | ||
| 2 | 240 | 40 | 5.481 | 0.182 |
| 3 | 288 | 48 | 5.663 | 0.182 |
| 4 | 345.6 | 57.6 | 5.845 | 0.182 |
The raw changes keep growing (40, 48, 57.6), so a straight line in month fails. The log changes are constant at 0.182, which is ln 1.2, so the fitted slope recovers the 20 percent growth rate. On a log scale, constant percentage growth becomes constant additive growth.
A logarithmic relationship shows diminishing returns: y = a + b ln x. Each doubling of x adds the same amount to y, however large x already is. Northfield's no-show rate by distance (fictional averages) looks like this:
| Distance (km) | No-show rate (%) | ln(distance) |
|---|---|---|
| 1 | 4 | 0.000 |
| 2 | 6 | 0.693 |
| 4 | 8 | 1.386 |
| 8 | 10 | 2.079 |
Distance doubles on each row and the rate rises by 2 points each time. The relationship is curved in kilometers but straight in ln(distance): rate = 4 + 2.885 × ln(distance), because 2 / 0.693 = 2.885. Check the last row: 4 + 2.885 × 2.079 = 10.0. Here you linearize by logging the feature, not the target. Mixing up the two is the classic trap. Log the target for exponential growth, log the feature for diminishing returns, and log both for a power law, y = a xb, which becomes ln y = ln a + b ln x.
The exponential transformation is the inverse operation, and you meet it in two places. The first is back-transformation: if the model predicts ln y, you exponentiate the prediction to report y. If the errors are roughly symmetric on the log scale, e raised to the predicted log lands near the median of y, not the mean, so totals come out too low unless you apply a correction. The second is on left-skewed variables, where a long tail of small values needs stretching rather than compressing. Exponentiating, or squaring, spreads out the upper end. Two practical points about the log itself. It is undefined at zero and for negative numbers, so counts that include zeros are usually transformed as ln(1 + x). And the base (e, 10 or 2) changes only the slope, never whether the line is straight.
The Box-Cox transformation: letting the data choose the power
Northfield's lead time, the number of days between booking and appointment, runs from 0 (same-day bookings) to 120, with a median near 6 and a long right tail. A log would compress the tail, but is a log the right amount of compression? A square root compresses less and a reciprocal compresses more. In 1964, George Box and David Cox suggested a useful family of power transformations to settle exactly this kind of choice.[4] A single power, λ (lambda), indexes the whole family, and as the table below shows, the family runs from no change through the square root and the log to reciprocal-like transforms.
x(λ) = (xλ - 1) / λ when λ ≠ 0, and x(λ) = ln x when λ = 0.
The family is defined only for positive values. The NIST/SEMATECH e-Handbook of Statistical Methods points out that a constant can always be added when some observations are zero or negative.[4] Lead time includes zeros, so Northfield uses lead_days + 1. When λ = 0, the natural log is used instead of the formula.[5] That is not an arbitrary patch. As λ shrinks toward 0, (xλ - 1) / λ approaches ln x. Subtracting 1 and dividing by λ is what makes the family change smoothly from one power to the next instead of jumping at zero.
The table applies four λ values to lead times that each quadruple the one before:
| x (lead_days + 1) | λ = 1 | λ = 0.5 | λ = 0 (log) | λ = -0.5 |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 |
| 4 | 3 | 2 | 1.386 | 1.0 |
| 16 | 15 | 6 | 2.773 | 1.5 |
| 64 | 63 | 14 | 4.159 | 1.75 |
| Gaps between rows | 3, 12, 48 | 2, 4, 8 | 1.386 each | 1.0, 0.5, 0.25 |
Read the bottom row. At λ = 1 the transform is just x - 1, a shift that leaves the shape alone, and the gaps still grow fourfold. At λ = 0.5, a scaled square root, they grow twofold. At λ = 0, the log, every quadrupling gets the same gap. At λ = -0.5 the gaps shrink, so the right tail is pulled in harder than a log would pull it. The lower the λ, the stronger the compression of large values.
The fitting procedure picks λ for you. The NIST handbook describes choosing the λ that maximizes the logarithm of the likelihood function, which asks how plausible the transformed values would be if they came from a normal distribution.[4] Its worked example uses microwave radiation measurements. Across a grid of λ values the log-likelihood peaks at 0.3, which becomes 0.28 when a second digit is calculated.[4] A graphical alternative is the Box-Cox normality plot. It charts, for each λ, the correlation coefficient of a normal probability plot of the transformed data, and the λ with the highest correlation wins.[5] In NIST's sample, a strongly right-skewed data set peaks at λ = -0.3, and after that transformation the histogram is close enough to normal for normal-based methods.[6]
Why bother? Many statistical tests and intervals are built on an assumption of normality, and they are simplest and most powerful when it holds.[6] For a linear model, a heavy right tail on a feature lets a few extreme rows dominate the fitted slope, and reshaping the feature spreads that influence more evenly.
In scikit-learn, PowerTransformer applies a power transform feature by feature to make data more Gaussian-like.[3] It offers Box-Cox and Yeo-Johnson, a related family that also accepts zero and negative values, and by default it standardizes the result to zero mean and unit variance.[7] The documentation warns that power transforms give very Gaussian-like output for some distributions and are ineffective for others, so plot the data before and after.[7] A feature with two well-separated clusters stays two clusters under any power, because the transform keeps the values in order.
Three cautions apply. First, fit λ on the training rows only and reuse it on test rows. Second, if you transform the target rather than a feature, invert the predictions before reporting them, with the same median-versus-mean caution as the log. Third, tree models gain almost nothing, because Box-Cox keeps the order of values and trees use only order. If a power will not fix the shape, a quantile transformation maps values through their ranks to a uniform or normal shape. It resists outliers but distorts correlations and distances within and across features.[7]
Key idea: the Box-Cox transformation is a dial. It runs from no change in shape (λ = 1) through a square root (0.5) and a log (0) to stronger, reciprocal-like compression (below 0). It needs positive data, and the dial setting is learned from training data.
Binning lead time into tiers
The scheduling team does not think in Box-Cox units. They think "same day", "this week", "this month" and "later". Binning (data binning) turns a continuous feature into a small number of intervals. The scikit-learn guide calls it discretization, also known as quantization or binning.[7] Its KBinsDiscretizer bins continuous data into intervals.[3] pandas cut() does the same job, turning continuous values into discrete categories.[2]
| Bin | Lead time | Appointments | No-shows | No-show rate |
|---|---|---|---|---|
| Same day | 0 days | 3,100 | 93 | 3.0% |
| This week | 1-7 days | 15,900 | 954 | 6.0% |
| This month | 8-30 days | 13,400 | 1,340 | 10.0% |
| Later | 31+ days | 9,400 | 1,375 | 14.6% |
| Total | 41,800 | 3,762 | 9.0% |
Binning buys three things. A linear model given the bins as one-hot columns learns a separate effect per bin, so it captures a curve without any formula. Extreme values stop mattering, because a 120-day booking is simply Later. And the feature speaks the business's language. It also costs something. Every booking from 8 to 30 days gets the same value, so the model cannot tell day 8 from day 30, and a booking that moves from day 7 to day 8 jumps a whole tier.
Bin edges come from one of three strategies: equal width (the same span per bin), equal frequency (quantile bins with the same count per bin) or domain knowledge, as here. Equal-width and equal-frequency edges are learned from data, so, like every other fitted parameter, they come from the training rows. Binning and Box-Cox both answer a skewed feature. Prefer the transform when the model needs fine-grained ordering, and binning when the effect jumps at known thresholds or when people must read the feature.
Geocoding client addresses
The address column holds the travel story the front desk keeps telling, but as text it is useless to a model. Geocoding turns it into numbers. The U.S. Census Bureau defines geocoding as inputting an address and receiving back latitude and longitude coordinates calculated along an address range.[8] That last phrase matters. The service places a house by its position within the known range of house numbers on a street segment, so the point is near the house, not necessarily on its roof. For the Census service, the building number and street name are required, while city, state and ZIP code are optional.[8]
Northfield's clinics are in Minnesota, so the free Census Geocoder works. It geocodes only addresses within the United States, Puerto Rico and the U.S. Island Areas.[9] Its batch service has an upper limit of 10,000 records per file, so Northfield's 18,000 distinct client addresses need two files.[9] The locations return type gives coordinates only, while geographies adds a geographic lookup.[9] In batch mode that lookup returns state, county, census tract and block codes for each point.[9] The address data behind the service are benchmarked twice a year, which suggests that a brand-new street may not match until a later release.[9]
This is the shape of a single-address result, taken from the Census Bureau's documentation example (an excerpt of the JavaScript Object Notation, JSON, response):
"x": -76.92748724230096,
"y": 38.84601622386617
...
"matchedAddress": "4600 SILVER HILL RD, WASHINGTON, DC, 20233"
Notice which is which: x is longitude and y is latitude, the reverse of the "lat, lon" order people usually say aloud. Swapping them is a classic bug, and here it would move a Washington, DC, address to Antarctica. After geocoding and computing distances, Northfield's client table gains these columns (fictional values; the clinic sits at 44.4583, -93.1616):
| client_id | latitude | longitude | match status | distance_km |
|---|---|---|---|---|
| C-1042 | 44.4561 | -93.1702 | Exact | 0.7 |
| C-2210 | 44.4280 | -93.2010 | Exact | 4.6 |
| C-0388 | 44.2950 | -93.2690 | Non-exact | 20.0 |
| C-5120 | No match | missing |
Distance comes from the haversine formula for two points on a sphere. Use latitudes lat1 and lat2, latitude difference Δlat and longitude difference Δlon, all in radians, and Earth's radius r ≈ 6,371 km:
d = 2r × arcsin( √( sin2(Δlat / 2) + cos(lat1) × cos(lat2) × sin2(Δlon / 2) ) )
A quick sanity check helps catch errors. One degree of latitude is about 111 km (2π × 6,371 / 360 = 111.2), and a degree of longitude shrinks with the cosine of latitude, to about 79 km at Northfield's 44.5 degrees north. C-0388 lies 0.163 degrees south (about 18.1 km) and 0.107 degrees west (about 8.5 km), so a straight-line distance near 20 km is right.
Commercial services offer more. Google's Geocoding API converts addresses to coordinates and also performs reverse geocoding, turning coordinates into a human-readable street address.[10] Its version 4 methods have a default quota of 25 queries per second (QPS).[10] At that rate 18,000 addresses take 720 seconds, or 12 minutes, so caching results and geocoding only new or changed addresses pays off.
Geocoding unlocks distance and travel time to each clinic, the nearest clinic, clusters of clients and, through the tract code, joins to anything published by geography. It also brings risks. Unmatched addresses (post office boxes, typos, new streets) become missing values that are rarely missing at random, since rural and new addresses fail more often. Interpolated points carry position error that matters at short distances. And an address is personally identifiable information (PII), so sending it to a third-party service needs the same approval as any other PII transfer. Keep match status as a feature of its own, because "could not be geocoded" may itself predict behavior.
Scaling, standardization and normalization
Northfield's numeric features now live on very different ranges. Distance runs from 0 to 60 km, the smoothed ratio from 0 to 1, and visit counts up to 80. For penalized logistic regression, KNN and neural networks that matters. The scikit-learn guide notes that many learning algorithms, linear models among them, benefit from standardizing the data set.[7] Three families of fix exist, and their names are often swapped in conversation.
Standardization subtracts the mean and divides by the standard deviation, giving each feature mean 0 and standard deviation (SD) 1: z = (x - μ) / σ, where μ is the training mean and σ the training standard deviation. scikit-learn's StandardScaler does exactly this.[3] The result is often called a z-score. Standardization does not make data normal. A skewed feature stays exactly as skewed, only recentered and rescaled.
Min-max scaling, which is what "scaling" usually means in this context, maps a feature into a fixed range, most often 0 to 1: x' = (x - min) / (max - min).[7] A variant, MaxAbsScaler, divides each feature by its maximum absolute value.[3] The guide lists preserving zero entries in sparse data among the reasons to use these scalers: a sparse matrix full of zeros stays sparse.[7] When outliers are present, the guide suggests robust scalers or other transformers instead.[7] RobustScaler uses statistics that resist outliers, by default centering on the median and dividing by the interquartile range (IQR).[3]
Normalization is the overloaded word. In scikit-learn, Normalizer works on rows, not columns: it rescales each sample to unit norm.[3] A row [3, 4] becomes [0.6, 0.8], because its Euclidean length is √(9 + 16) = 5. That suits cases where only a vector's direction matters, such as word-count vectors compared by cosine similarity. In everyday data-science speech, though, "normalize" often means min-max scaling, and statisticians use it for transforming data toward a normal distribution, which is the sense of NIST's Box-Cox pages. pandas even uses it for turning a frequency table's counts into proportions.[2] When a question says normalization, read the scenario to see which is meant: unit-length rows, a 0-1 range or a normal shape.
Now work an example. Take five training lead times, in days (fictional): 2, 4, 6, 8 and 30. The mean is 50 / 5 = 10. The deviations from the mean are -8, -6, -4, -2 and 20, and their squares sum to 64 + 36 + 16 + 4 + 400 = 520. The population variance is 520 / 5 = 104, so σ = √104 = 10.20. The minimum is 2 and the maximum 30, a range of 28. The median is 6, the first quartile 4 and the third quartile 8, so the IQR is 4.
| Lead days | Standardized (x - 10) / 10.20 | Min-max (x - 2) / 28 | Robust (x - 6) / 4 |
|---|---|---|---|
| 2 | -0.78 | 0.00 | -1.0 |
| 4 | -0.59 | 0.07 | -0.5 |
| 6 | -0.39 | 0.14 | 0.0 |
| 8 | -0.20 | 0.21 | 0.5 |
| 30 | 1.96 | 1.00 | 6.0 |
| Test row: 45 | 3.43 | 1.54 | 9.75 |
Read the columns. Under min-max scaling the single 30-day booking takes the top of the range and squeezes the other four into 0 to 0.21, so their differences nearly vanish. Under standardization the outlier also inflates σ, though less dramatically. The robust column keeps the four typical values evenly spread in half-unit steps and simply marks 30 as far out.
Now change one input. A test booking arrives at 45 days, longer than anything in training. Min-max scaling gives 1.54, outside the 0-1 range the method seemed to promise. Nothing is broken: the scaler correctly reused the training minimum and maximum. A model that assumes inputs never exceed 1 needs clipping or a different scaler. What would be broken is refitting the scaler on test data, or fitting it on all rows before splitting, because then the test rows' mean and spread shape the training features. scikit-learn's documented pattern places the scaler inside a Pipeline, which learns the scaling from training rows and applies those same parameters to the test rows without leaking.[7]
Which models care? Distance-based models (KNN, k-means, SVM with an RBF kernel), models trained by gradient descent (neural networks) and penalized regressions all care. In LASSO and ridge the penalty treats every coefficient alike, so the units must be comparable. Unpenalized OLS gives the same predictions either way, with rescaled coefficients. Tree models do not care.
| Method | Formula | Range after | Effect of outliers | Typical use |
|---|---|---|---|---|
| Standardization | (x - μ) / σ | Unbounded; mean 0, standard deviation 1 | Outliers inflate σ | Linear and penalized models, SVM, principal component analysis (PCA) |
| Min-max scaling | (x - min) / (max - min) | 0 to 1 on training data | One outlier compresses the rest | Neural network inputs, pixel intensities |
| MaxAbs scaling | x / max |x| | -1 to 1 | Set by the largest value | Sparse data; keeps zeros as zeros |
| Robust scaling | (x - median) / IQR | Unbounded | Barely affected | Features with outliers |
| Row normalization | Each row divided by its length | Each row has length 1 | Works per row, not per column | Text vectors, cosine similarity |
Key idea: standardization gives mean 0 and standard deviation 1, min-max scaling gives a 0-1 range on training data, robust scaling resists outliers, and scikit-learn's Normalizer rescales rows. Every one of them learns its parameters from training data only.
Additional data sources: data sets, data augmentation and synthetic data
Even well-engineered features only reshape the information already in the table. When the signal or the number of examples is too thin, you go outside the table. The exam names three routes, and they solve different problems.
External data sets add columns. Northfield can join a weather forecast by date and clinic, a school-holiday calendar by date, and published statistics by the census tract that geocoding supplied. Every join raises four questions. Is the key reliable, with dates in the same time zone and tract codes from the same vintage? Is the granularity right, given that a county average says little about one street? Does the license allow this use? And would the value have existed at prediction time? Weather shows the trap. Forecasts exist at scoring time and observed rainfall does not, so the model must train on archived forecasts issued at each booking's scoring time.
Data augmentation adds rows by making modified copies of real training examples. In computer vision, a photo that is flipped, cropped, slightly rotated or recolored still shows the same thing, so one labeled image becomes several. Text can be augmented by synonym replacement or back-translation, and audio by adding noise. For tabular data with a rare class, the synthetic minority oversampling technique (SMOTE) builds new minority rows by interpolating between a minority example and one of its nearest minority neighbors. Its rows are technically synthetic, as the name says, but because each comes from specific real neighbors it is usually grouped with augmentation and resampling. The rule that matters: augment only the training data, after the split. Augmented copies in the test set let the model be graded on near-duplicates of what it trained on, and the test set must keep the real class balance for its metrics to mean anything.
Synthetic data are records generated from a model of the data rather than derived from individual real examples; Lesson 3 covered how they are generated. Northfield might use them to give a scheduling vendor a realistic but privacy-safe copy of its bookings, to test a pipeline before real data arrive, or to simulate rare situations such as a clinic closure. The limits are real. A generator reproduces only the patterns it learned, an overfit generator can memorize and leak real records, and a model trained on synthetic rows must still be validated on real ones.
| Route | What it adds | Problem it solves | Main risk | Where it may be used |
|---|---|---|---|---|
| External data set | New columns from another source | Missing context or signal | Timing leakage, bad join keys, license limits | Training and prediction, if available at prediction time |
| Data augmentation | Modified copies of real examples | Too few examples, rare class, need for invariance | Copies reaching evaluation; changes that alter the label (rotating a handwritten 6 by 180 degrees makes a 9) | Training split only |
| Synthetic data | Records generated from a fitted model | Privacy, pipeline testing, rare scenarios | Unrealistic patterns, memorized records | Training, testing and sharing; always validate on real data |
Assembling Northfield's pipeline without leaking
Order matters, because some steps produce the inputs of others. Northfield's final sequence is:
- Split appointments by time: train on January to September 2025 and test on October to December. A random split would let the model learn from a client's later visits to predict earlier ones.
- Build point-in-time history: pivot each client's visits before the scoring date into counts, then compute the smoothed no-show ratio, with p taken from the training months only.
- Geocode addresses once and cache them, compute distance to the clinic, record match status and join tract data.
- Join the archived rain forecast available at scoring time and form the distance × rain cross-term.
- Inside a pipeline, one-hot encode type and species, ordinal-encode tier in the stated order, Box-Cox transform lead time plus 1, and standardize the numeric columns.
- Fit on training rows, then evaluate on test rows using the parameters learned in training.
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import (OneHotEncoder, OrdinalEncoder,
PowerTransformer, StandardScaler)
prep = ColumnTransformer([
('cats', OneHotEncoder(handle_unknown='ignore'), ['appt_type', 'species']),
('tier', OrdinalEncoder(categories=[['Bronze', 'Silver', 'Gold']]), ['client_tier']),
('lead', PowerTransformer(method='box-cox'), ['lead_days_plus1']),
('nums', StandardScaler(), ['distance_km', 'rain_forecast', 'rain_x_distance',
'smoothed_ratio', 'prior_visits']),
])
model = make_pipeline(prep, LogisticRegression(max_iter=1000))
model.fit(X_train, y_train) # every transformer learns from training rows only
model.score(X_test, y_test) # test rows reuse the training parameters
A few notes on the code. All one-hot columns are kept because scikit-learn's LogisticRegression applies an L2 (ridge) penalty by default, which resolves the dummy-variable ambiguity. handle_unknown='ignore' gives an appointment type that first appears after training, such as a new behavior consult, all zeros instead of crashing the pipeline. The Box-Cox step needs no separate scaler because PowerTransformer standardizes its output by default. Finally, score() on a classifier reports accuracy, which flatters a model when only 9 percent of cases are positive. Lesson 2's precision, recall and Matthews correlation coefficient (MCC) give a truer picture.
Objective 2.3 begins "given a scenario", so the exam skill is matching a description to a technique. These cues cover most question stems:
| The stem says | Points to | Commonly confused with |
|---|---|---|
| Categories with no natural order (color, region, appointment type) | One-hot encoding | Label encoding, which invents an order |
| Ordered levels (low, medium, high; bronze, silver, gold) | Ordinal (label) encoding with the order set explicitly | One-hot encoding, which discards the order |
| Convert class labels to integers for a classifier | Label encoding (LabelEncoder) | Ordinal encoding of input features |
| The effect of one variable depends on another | Cross-term (interaction) | Adding both features separately |
| Grows by a constant percentage; exponential growth | Log of the target | Log of the feature |
| Diminishing returns; each doubling adds the same amount | Log of the feature | Log of the target |
| Right-skewed positive variable; find the best power | Box-Cox transformation | Standardization, which does not change shape |
| Skewed with zeros or negative values | Shift then Box-Cox, or Yeo-Johnson | Box-Cox applied directly, which fails |
| Mean 0 and standard deviation 1; z-score | Standardization | Min-max scaling |
| Range 0 to 1; bounded inputs | Min-max scaling | Standardization |
| Scaling distorted by a few outliers | Robust scaling (median and IQR) | Min-max scaling |
| Each row to unit length; cosine similarity | Row normalization (Normalizer) | Column-wise scaling |
| Continuous values into groups, bands or tiers | Binning | One-hot encoding, which needs categories first |
| Rate, per capita, relative to size | Ratio feature | Raw counts |
| One row per event, need one row per customer | Pivot (pivot_table with aggregation) | Melt, which goes the other way |
| Address to latitude and longitude | Geocoding | Reverse geocoding (coordinates to address) |
| Few labeled images; flips, crops, rotations | Data augmentation | Synthetic data from a generator |
| Cannot share real records for privacy reasons | Synthetic data | Data augmentation, which starts from real rows |
| Model lacks context such as weather or demographics | Additional external data set | More transformations of existing columns |
Common misconceptions
- "Standardization and normalization are the same thing." Standardization always means mean 0 and standard deviation 1. Normalization can mean min-max scaling, scaling each row to unit length (scikit-learn's Normalizer) or reshaping toward a normal distribution, so the scenario decides.
- "Standardizing makes a skewed feature normal." It only shifts and rescales, so the shape, including the skew, is unchanged. Changing shape takes a log, Box-Cox, Yeo-Johnson or quantile transformation.
- "Label encoding is fine for any category." Integer codes tell linear and distance-based models that categories are ordered and evenly spaced. Use them for real orders, set explicitly, or for target labels.
- "Fit the scaler, encoder or λ on the whole data set; it is only preprocessing." Every fitted parameter carries information from the rows it saw. Fit on training rows and reuse the parameters on test rows, ideally inside a pipeline.
- "Augmented rows help everywhere, including the test set." Augmentation belongs in the training split only. Test data must stay real and keep the true class balance.
- "A log fixes any curve." Logging the target straightens exponential growth, and logging the feature straightens diminishing returns. Log the wrong side and the curve stays bent.
What you now know
- One-hot encoding gives each unordered category its own 0/1 column. With an intercept in an unpenalized linear model, drop one column to avoid perfect multicollinearity.
- Label encoding maps categories to integers. scikit-learn's LabelEncoder is for target labels (0 to n_classes - 1), and ordered features need their order set explicitly, because the default order is alphabetical.
- A cross-term d × r lets d's effect change with r: the slope of d is b1 when r = 0 and b1 + b3 when r = 1.
- Exponential growth is linearized by logging the target (ln y = ln a + bx) and diminishing returns by logging the feature. Exponentiating a log-scale prediction gives roughly the median, not the mean.
- Box-Cox is (xλ - 1) / λ, with ln x at λ = 0, and is defined only for positive data. λ is chosen by maximum likelihood or with a normality plot, and λ = 1 leaves the shape unchanged.
- Standardization is (x - μ) / σ. Min-max scaling is (x - min) / (max - min) and can exceed 1 on new data. Robust scaling uses the median and IQR, and Normalizer scales rows to unit length.
- pivot() needs unique index-column pairs, pivot_table() aggregates duplicates, and melt() unpivots wide data to long.
- Geocoding turns addresses into latitude and longitude, and reverse geocoding goes back. The Census Geocoder covers only U.S. addresses, caps batches at 10,000 records and reports longitude as x.
- External data sets add columns, augmentation adds modified copies of real rows to the training split only, and synthetic data are generated from a model and must be validated against real data.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- pandas. (n.d.). Reshaping and pivot tables. pandas.pydata.org
- scikit-learn. (n.d.). sklearn.preprocessing, scikit-learn 1.9.1 documentation. scikit-learn.org
- NIST. (n.d.). Box-Cox Transformations (NIST/SEMATECH e-Handbook of Statistical Methods, 6.5.2). itl.nist.gov
- NIST. (n.d.). Box-Cox Normality Plot (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- NIST. (n.d.). Box-Cox Linearity Plot (NIST/SEMATECH e-Handbook of Statistical Methods). itl.nist.gov
- scikit-learn. (n.d.). 8.3. Preprocessing data, scikit-learn 1.9.1 documentation. scikit-learn.org
- U.S. Census Bureau. (n.d.). Census Geocoding Services. census.gov
- U.S. Census Bureau. (n.d.). Geocoding Services API. geocoding.geo.census.gov
- Google Maps Platform. (n.d.). Geocoding API v4 overview. developers.google.com
- Key terms
- Feature engineering
- Building and choosing the input columns a model learns from by selecting, deriving and transforming raw fields.
- One-hot encoding
- Representing a category column as one 0/1 indicator column per category, so the model sees no false order between categories.
- Label encoding
- Mapping each category to an integer; suited to target class labels and to ordered categories when the order is set explicitly.
- Cross-term
- A feature made by multiplying two features, which lets a linear model represent an effect of one that changes with the level of the other.
- Box-Cox transformation
- A family of power transformations for positive data, (x^lambda - 1)/lambda, with the natural log at lambda = 0; lambda is usually chosen by maximum likelihood.
- Standardization
- Rescaling a feature to mean 0 and standard deviation 1 by subtracting the training mean and dividing by the training standard deviation.
- Min-max scaling
- Rescaling a feature to a fixed range, usually 0 to 1, with (x - min)/(max - min) using the training minimum and maximum.
- Pivoting
- Reshaping a long table with many rows per entity into a wide table with one row per entity and one column per category, aggregating duplicates when needed.
- Geocoding
- Converting a street address into latitude and longitude coordinates; reverse geocoding converts coordinates back into an address.
- Data augmentation
- Adding modified copies of existing training examples, such as flipped images or interpolated minority-class rows, to the training split only.
Iterating on Model Design
- Turn a business brief into a model specification with measurable hard and soft constraints on time, physical hardware and cost.
- Evaluate candidate models with statistical metrics, training time and cost, inference performance over time and residual vs. fitted plots, and judge whether a gap between candidates is real.
- Choose the next iteration (literature review, hyperparameter tuning or architecture change) from diagnostic evidence, and track experiments so every result can be reproduced.
- Validate a selected model against every requirement, and recognize when a changed constraint changes which candidate wins.
A model that topped the leaderboard and failed the brief
Lakeside Parcel is a fictional carrier, and every number in its story is invented for teaching. It wants to show customers how many minutes remain until the driver reaches their door. Its data science team trained four candidate models on 1.2 million past delivery stops. The best was a deep neural network trained on a rented graphics processing unit (GPU). It missed the true arrival time by a root mean square error (RMSE) of 5.2 minutes on validation data, the lowest error of the four. Operations rejected it within ten minutes of the demo.
The reason was a one-page document the team had not reread since kickoff: the specification. Here it is.
| Requirement | Target | Kind |
|---|---|---|
| Accuracy on the most recent 4 weeks of held-out stops | RMSE at most 6.0 minutes (the current rule of thumb scores 9.1) | Hard |
| Response time in the customer app | 95th-percentile (p95) latency at most 150 ms per request at 300 requests a second | Hard |
| Production hardware | Existing servers with central processing units (CPUs) only: 4 virtual CPUs and 8 GB of memory per instance, no GPUs | Hard |
| Weekly retraining | Finishes inside a 2-hour Sunday window | Hard |
| Compute budget | Training at most $400 a month | Hard |
| Explanation for dispatchers | Top three factors behind any estimate | Soft |
| Privacy | No driver personally identifiable information (PII) used as features | Hard |
A p95 latency of 150 ms means 95 percent of requests must be answered within 150 milliseconds. Here is what the four candidates delivered. Each was measured on the same validation weeks and, for latency, on a copy of the production server.
| Candidate | Validation RMSE (min) | p95 latency on production CPU | Weekly training time | Monthly training cost |
|---|---|---|---|---|
| v1: ordinary least squares (OLS) linear regression | 7.8 | 4 ms | 3 min | $5 |
| v2: OLS on log stop time, with a distance spline and hour-by-depot interactions | 6.6 | 5 ms | 6 min | $8 |
| v3: gradient-boosted trees, 600 trees, depth 8 | 5.4 | 38 ms | 50 min | About $118 (with monthly tuning) |
| v4: deep neural network, trained on a GPU | 5.2 | 210 ms | 3.5 h on a GPU | $1,100 |
Read the deep network's row against the specification. Its 210 ms latency breaks the 150 ms limit. Its 3.5-hour training run does not fit the 2-hour window, and it needs a GPU that production does not have. Its $1,100 a month is almost three times the budget. The two linear models are fast and cheap, but they miss the 6.0-minute accuracy target. Only the gradient-boosted trees, v3, pass every requirement measured so far. The most accurate model was never a contender.
Exam objectives: DataX DY0-001 objective 2.4, "Given a scenario, conduct a model design iteration process."[1] It sits in domain 2.0, Modeling, Analysis, and Outcomes, which carries 24 percent of the exam. Its bullets fall under four headings. Design and specifications covers constraints of time and resource, where resource means physical hardware and cost. Performance evaluation covers statistical metrics, training time and cost, inference performance over time, and model diagnostic plots such as residual vs. fitted values. Model selection covers literature review, hyperparameter tuning, experiment tracking and model architecture iteration. The last heading is requirements validation.
The case raises three questions, and the rest of the lesson answers them. How did the team get from v1 to v3, and how does it decide what to try next? How does it know v3 is not hiding a flaw that one error number cannot show? And what happens when the specification changes after launch?
The point: a model design iteration is judged against a written specification of accuracy and constraints. The candidate with the best metric still loses if it breaks a hard limit on time, hardware or cost.
The model design iteration loop
To iterate is to repeat a cycle in which each round's evidence decides what changes in the next round. Without that rule, iterating turns into trying things at random. A practical cycle, which this lesson uses to organize objective 2.4, has eight steps.
- Write or confirm the specification. State the business goal, the metric and threshold that define success, and every constraint.
- Review the literature and set a baseline. Find what has worked on similar problems, and measure the simplest reasonable predictor.
- Choose an architecture. Pick the model family and structure for this round.
- Tune hyperparameters. Search the settings of that architecture with cross-validation.
- Evaluate performance. Compute the statistical metrics, measure training time, cost and inference speed, and read the diagnostic plots.
- Track the experiment. Log parameters, metrics, data version, code version and artifacts so the run can be compared and repeated.
- Validate against requirements. Check every row of the specification on held-out data and on the target hardware. A failed row tells you where to go back. A tuning problem sends you to step 4, a design problem to step 3, and an unrealistic requirement to step 1.
- Monitor after deployment. Watch inference performance over time. Drift or a broken constraint sends the model back into the loop.
The steps are not a strict sequence. Lakeside's team went round the loop four times before v3, and some passes skipped steps. Step 7 is what makes it a loop: the comparison with the specification decides the next move.
Design and specifications: constraints of time and resource
A specification is the written agreement about what the model must achieve, how success will be measured, and the limits the model must live within. It has two kinds of content. Functional requirements say what the model predicts and how well, such as an RMSE of at most 6.0 minutes on the latest four weeks. Constraints say what the model may consume while doing it. Mark each requirement as hard, meaning failure disqualifies the candidate, or soft, meaning a preference you can trade. Without that label, every review meeting reopens the argument.
Google Cloud's architecture guidance for machine learning (ML) makes the same point about design: when you design a model, weigh its complexity and computational needs.[2] The exam objectives split constraints into time and resource, and split resource into physical hardware and cost. The table shows what each covers in practice.
| Constraint | What it covers | Typical measure | How it changes the design |
|---|---|---|---|
| Time: project | Deadline for a usable model | Calendar weeks | Limits how many loop passes you get and how unusual an architecture you can risk |
| Time: training | Retraining must finish inside a window | Wall-clock minutes per fit | Rules out models that train slower than the window; moves tuning to a less frequent schedule |
| Time: inference | Response time per prediction or per batch | p95 latency in ms; batch duration | Favors smaller models, precomputed features and simpler architectures |
| Time: freshness | How recent the data behind a prediction must be | Feature age in minutes | Decides between batch scoring and real-time scoring |
| Resource: physical hardware | Processors, memory and the place the model runs | CPU, GPU or TPU type; memory in GB; model file size; edge device limits | The model must fit in memory and run fast enough on the hardware it will actually use |
| Resource: cost | Money for compute, storage, labeling, licenses and staff | Dollars a month; cost per 1,000 predictions | Bounds tuning budgets and designs that are expensive per prediction |
Physical hardware deserves a careful reading. CPUs are general-purpose processors. GPUs and Google's tensor processing units (TPUs) are accelerators built for the large matrix operations in deep learning, and cloud providers rent them for both training and inference. The trap in Lakeside's v4 was training on one kind of hardware and serving on another. A network that answers in a few milliseconds on a GPU can take hundreds of milliseconds on a CPU. Measure inference on the hardware named in the specification, or the number is not evidence.
Cost splits the same way. Training cost is paid each time you fit or tune. Inference cost is paid on every prediction for the model's whole life. Lakeside's app sends about 300 requests a second. That is 300 × 86,400 seconds = 25,920,000 predictions a day. A design that doubles the compute per prediction doubles the serving bill every day, whereas a slower training run is paid once a week.
The point: write every constraint as a measurable number marked hard or soft. Then measure each one on the hardware, and at the volume, the model will actually face.
Performance evaluation: statistical metrics against a baseline
Statistical metrics summarize how far predictions are from the truth. Choose them from the specification, not from habit. Lakeside's estimates are in minutes, so the team uses two regression error metrics. Take n held-out stops, where yi is the true duration of stop i and ŷi (read "y-hat") is the prediction.
- Mean absolute error (MAE) = (1/n) Σ |yi - ŷi|. It is the average size of a miss.
- Root mean square error (RMSE) = √[(1/n) Σ (yi - ŷi)2]. It squares each miss before averaging, so large misses count far more.
Work a small case. Five stops have errors y - ŷ of 3, -4, 1, 0 and -2 minutes. For MAE, add the absolute values (3 + 4 + 1 + 0 + 2 = 10) and divide by 5: 2.0 minutes. For RMSE, square the errors (9 + 16 + 1 + 0 + 4 = 30), divide by 5 to get 6, and take the square root: about 2.45 minutes.
Now change one input. Replace the 0 with a 10-minute miss. MAE becomes 20 / 5 = 4.0. RMSE becomes √(130 / 5) = √26, about 5.10. One bad stop doubled MAE but more than doubled RMSE. Lakeside chose RMSE because a customer who waits 25 minutes longer than promised calls support, and RMSE punishes exactly those cases. If the business cared about the typical miss instead, MAE would be the better target.
A metric means little without a reference point. scikit-learn provides dummy estimators for this. They predict by a simple rule, such as always returning the training mean, so you can see what a metric looks like with no learning at all.[3] Lakeside's existing rule of thumb, the route's average stop time, scored 9.1 minutes RMSE. Every candidate must beat that bar by enough to justify the engineering.
You will also meet the coefficient of determination, written R2 and read "R-squared". It measures the fraction of the total variability in the response that the model accounts for.[4] In symbols, R2 = 1 - RSS / TSS. RSS, the residual sum of squares, is Σ(yi - ŷi)2. TSS, the total sum of squares, is Σ(yi - ȳ)2, where ȳ is the mean of y. An R2 of 0.80 means the model's squared errors are 20 percent of the squared spread around the mean. On training data, R2 never falls when you add a predictor, so it rewards complexity whether or not the predictor helps.
Adjusted R2 charges for each term: adjusted R2 = 1 - (1 - R2)(n - 1)/(n - p - 1), where p is the number of predictors. Work it with n = 1,000. A model with p = 10 and R2 = 0.80 gives 1 - 0.20 × 999/989 = 1 - 0.202 = 0.798. Now add 190 weak predictors that nudge R2 up to 0.81, so p = 200. Adjusted R2 becomes 1 - 0.19 × 999/799 = 1 - 0.238 = 0.762. Plain R2 went up; adjusted R2 went down, because the gain did not pay for 190 extra terms. The Akaike and Bayesian information criteria (AIC and BIC) from Lesson 2 make the same trade for likelihood-based models. None of these replaces held-out error for a model like gradient boosting, where "number of predictors" does not measure how flexible the model is.
Two library conventions trip people up in tuning code. First, every scikit-learn scorer treats a higher value as better.[3] Error metrics are therefore exposed in negated form, such as neg_mean_squared_error.[3] A best score of -29.2 means a mean squared error of 29.2. Forget the sign and you can end up picking the worst model in a grid. Second, you can track several metrics in one search, but the search must name one of them, through the refit setting, to choose the winner.
The same selection rule applies to classifiers. Revisit Lesson 2's confusion matrices and receiver operating characteristic (ROC) curves. The metrics built from them, such as precision, recall, the Matthews correlation coefficient (MCC) and the area under the ROC curve (ROC-AUC), each weight errors differently. Pick the one whose errors the business pays for, and write its threshold into the specification.
Where you compute the metric matters as much as which metric you compute. Tune and compare candidates on validation data. Keep a test set untouched until the final requirements check. Lakeside's data are ordered in time, so its validation and test sets are the most recent weeks, never a random sample of the past.
Performance evaluation: training time and cost
Training time and cost are performance measures too, because the specification limits them. They are also easy to underestimate, because tuning multiplies the cost of a single fit.
scikit-learn records the evidence for you. After a search, the cv_results_ dictionary holds mean_fit_time and mean_score_time for every candidate, in seconds, and the refit_time_ attribute reports the seconds spent refitting the best model on the whole dataset. Read these numbers before you schedule anything.
Lakeside rents its compute as nodes. A node is one machine in a compute cluster, billed by the hour, and a node-hour is one node used for one hour. Work the monthly tuning run for v3. The grid tries 2 learning rates, 3 tree depths and 3 tree counts.
- Candidates: 2 × 3 × 3 = 18 combinations.
- Fits: 18 candidates × 5 cross-validation folds = 90 fits, plus 1 refit of the winner, for 91 in total.
- Compute: each fit occupies a whole node. The team assumes an average of 30 minutes per fit across the grid. Deep 600-tree settings take about 45 minutes, and shallow 200-tree settings about 11. So 91 × 0.5 = 45.5 node-hours.
- Cost: at an invented price of $2.40 per node-hour, 45.5 × 2.40 = $109.20.
- Weekly retraining with the chosen settings: 50 minutes, about 0.83 node-hours, or $2.00 a run. At about 4.3 runs a month, that adds about $8.60.
- Total: $109.20 + $8.60, about $118 a month, well under the $400 budget.
Now check the time constraint. The 45.5 node-hours could never fit into the 2-hour Sunday window, so the design separates the two jobs: tune monthly, and retrain weekly with the last winning settings. Running fits in parallel shortens the wall-clock time; in scikit-learn the n_jobs parameter sets how many jobs run at once. Spread across ten nodes, the grid finishes in under five hours. Parallelism does not shrink the bill, though, when each fit already fills its node. Ten nodes for 4.55 hours cost the same 45.5 node-hours as one node for 45.5 hours.
Now flip one input. Suppose the team widens the grid to four values of each hyperparameter: 4 learning rates, 4 depths and 4 tree counts. The grid grows from 18 to 4 × 4 × 4 = 64 candidates. That is 64 × 5 + 1 = 321 fits. At the same 30-minute average, that is 160.5 node-hours, which costs about $385 for tuning alone. With retraining, the month comes to about $394. That is a few dollars under budget, and a single slow run would break it. Going from 18 to 64 candidates multiplied the tuning bill by about 3.5. Grids grow multiplicatively, which is why training time and cost appear in the objective next to the metrics.
Inference performance over time
Inference means using a trained model to make predictions. The objective's phrase "inference performance over time" covers two things you must watch after launch, and exam questions use both meanings.
- Speed and resource use. This covers latency, throughput, error rate and the memory or CPU use of the serving system. Google Cloud's guidance names latency, error rate and resource utilization as the metrics to monitor when hunting for bottlenecks.[2]
- Predictive quality. This asks whether the model is still as accurate as it was at validation. The world that produced the training data keeps changing, and accuracy decays with it.
Quality decays for named reasons. Data drift means the distribution of the inputs shifts: a new depot opens in a district with different traffic. Concept drift means the relationship between inputs and outcome changes: a new building-access policy adds two minutes to every apartment stop. Training-serving skew means the features computed in production differ from the ones computed for training, often because two code paths calculate what is supposed to be the same feature in different ways. Model monitoring services exist to track model performance, identify training-serving skew and prediction drift, and alert someone to retrain.[2]
Here is Lakeside's monitoring sheet for v3 after launch (fictional). True delivery times arrive the same day, so live RMSE can be computed every week.
| Week after launch | Live RMSE (min) | p95 latency (ms) | Note |
|---|---|---|---|
| 1 | 5.6 | 41 | Matches the test-set result |
| 4 | 5.7 | 43 | Stable |
| 7 | 5.9 | 52 | Feature lookups slowing; still well within 150 ms |
| 9 | 6.4 | 55 | Breaks the 6.0 requirement; a new depot opened in week 8 |
| 10 | 5.8 | 44 | Retrained on data that includes the new depot |
The table teaches two things. First, the requirement keeps applying after launch. The specification's thresholds become the alert thresholds for production monitoring. Week 9 broke one, so the model went back into the loop. Second, latency drifted even though the model never changed, because a dependency slowed down. A model can break the specification without any change to its own code.
Plan the response before you need it. Google Cloud's guidance says reliable deployment needs a robust rollback plan.[2] For Lakeside, the plan is to keep the previous model version registered and switch back with one configuration change. Sometimes true outcomes arrive late. A loan default, for example, may appear months after the decision. Then you cannot compute live RMSE or recall, so you monitor input drift and the distribution of predictions as early warnings.
The point: inference performance over time means both speed and accuracy in production. Turn the specification's thresholds into monitoring alerts, and expect drift to send a deployed model back into the iteration loop.
Model diagnostic plots: residual vs. fitted values
A single metric hides the shape of the errors. Lakeside's v1 scored 7.8 minutes RMSE. That number cannot tell you whether v1 is a little wrong everywhere or badly wrong in one region. Diagnostic plots can.
Start with the residual. The NIST/SEMATECH e-Handbook of Statistical Methods defines residuals as the differences between the observed responses and the responses the fitted model predicts.[4] In symbols, ei = yi - ŷi. A positive residual means the model under-predicted. A negative one means it over-predicted.
The handbook is blunt about R2: the statistic cannot justify a particular model on its own.[5] For most process modeling, it names graphical residual analysis as the primary validation tool.[4] The logic is short. If the model captured the systematic part of the relationship, the residuals contain only random noise. Any visible structure left in them is signal the model missed.
A residual vs. fitted values plot puts the fitted (predicted) value ŷ on the horizontal axis and the residual on the vertical axis, with a reference line at zero. It is one of the six plots in NIST's 6-plot, a standard set of graphical checks on a fit.[6] The other five are: the response and predictions against the predictor; residuals against the predictor; a lag plot of residuals (each residual against the one before it); a histogram of residuals; and a normal probability plot of residuals, which is a quantile-quantile (Q-Q) plot against the normal distribution.
Here is what Lakeside's v1 plot showed. The 1.2 million points are summarized by grouping stops into bands of fitted value (fictional data).
| Fitted estimate band (min) | Mean residual (min) | Spread of residuals, standard deviation (min) |
|---|---|---|
| 5-15 | +2.1 | 2.0 |
| 15-25 | +0.4 | 3.1 |
| 25-35 | -1.5 | 4.2 |
| 35-45 | -1.9 | 5.6 |
| 45-55 | -0.6 | 7.4 |
| 55-65 | +2.8 | 9.9 |
Read the table as if it were the plot. The center of the cloud starts above zero, dips below zero in the middle bands, and rises above zero again on the right. That U-shape is curvature. v1 under-predicts short and long stops and over-predicts medium ones, so the straight-line form is wrong.
Separately, the spread grows steadily from 2.0 to 9.9 minutes as the fitted value rises, so the cloud fans out like a funnel. That funnel is heteroscedasticity: error variance that changes with the level of the prediction. It means one overall RMSE overstates accuracy on long stops and understates it on short ones. Any prediction interval that assumes constant variance is also wrong.
Each pattern pointed to a different repair, and together they produced v2. The team modeled the logarithm of stop time. Errors that scale with the size of the stop become errors of roughly constant size on the log scale, which attacks the funnel. The team also added a spline on distance, a flexible curve built from joined polynomial pieces, to absorb the curvature. v2's residuals had a flat center line and a narrower funnel, and RMSE fell to 6.6. That still missed 6.0, but the remaining structure had moved somewhere else.
That is why one plot is never enough. NIST warns that no single residual plot can completely justify adopting a model.[5] It advises plotting the residuals against every available variable, including candidates not yet in the model.[5] Plotting residuals against time or day can also reveal shifts in conditions that a fitted-value plot hides. When Lakeside's team plotted v3's residuals by depot, depot 7 sat three minutes above zero on average. Its stops were in high-rise buildings, and the model had no feature for building type. A clean residual vs. fitted plot had hidden a depot-level miss.
Check the scale, too. In one NIST example, a quadratic fit to thermocouple calibration data left strong cyclic structure in its residuals. Those residuals spanned about fifty times the range of the residuals from a LOESS fit (locally estimated scatterplot smoothing, a flexible local regression).[5] Always read the vertical axis before you call a pattern small.
| Pattern | What it means | Typical next iteration |
|---|---|---|
| Even horizontal band around zero, no shape | This plot finds no structure | Check the other plots and variables before accepting the model |
| Curve (U-shape or arch) | Wrong functional form: a missing nonlinearity or interaction | Add terms, transform predictors, or move to a more flexible model |
| Funnel (spread grows or shrinks with the fitted value) | Heteroscedasticity: error variance is not constant | Transform the target (for example with a log), weight the observations, or model the variance |
| Separate horizontal bands or clusters | A categorical factor the model ignores | Add the missing variable, or fit separate models by group |
| A few points far from the rest | Outliers or influential points, often data errors | Inspect those records before deciding to fix, drop or keep them |
| Parallel diagonal stripes | The target is discrete or capped, such as whole minutes or a ceiling value | Usually harmless; consider a model built for count or censored data |
| Residuals that wander when plotted in time order | Autocorrelation: the errors are not independent | Use a lag plot; add time features or a time-series model (Lesson 5) |
Know the limits. Residual plots are hard to read when the number of estimated parameters approaches the number of observations, because fitting so many parameters constrains the residuals. NIST names logistic regression with binary data as another case where graphical residual analysis is difficult.[4] For a classifier, use classifier diagnostics instead: the confusion matrix and ROC curve from Lesson 2, plus precision-recall curves and calibration plots, which compare predicted probabilities with observed frequencies.
Two more plots help with any model. A learning curve plots training and validation error against the size of the training set. A validation curve plots both errors against one hyperparameter. A wide gap between the two curves means high variance, or overfitting. Two high curves close together mean high bias, or underfitting. Treat no fit as finished until you have looked at its residuals and these curves.
The point: a residual vs. fitted plot shows the shape of the errors that one metric hides. Curves, funnels and clusters each suggest a specific next iteration, and even a clean plot must be checked against every other variable.
Model selection begins with a literature review
Model selection means choosing which candidate goes forward. The objective lists four activities under it, and the first happens before you train anything: a literature review, a structured search of what others have already learned about problems like yours.
Sources include peer-reviewed papers and preprints, published benchmarks, library documentation and examples, cloud providers' catalogs of pretrained models, and your own organization's past projects. Past projects are often the most relevant source and the least searched. For language and image problems, the review may show that fine-tuning an existing pretrained model beats training one from scratch.
Read with a checklist, so the review produces decisions rather than a reading list.
| Question | Why it matters | What Lakeside's review found (fictional) |
|---|---|---|
| Which model families worked on similar data? | Narrows the choice of architecture | Reports favored gradient-boosted trees and sequence neural networks |
| What metric and baseline did others report? | Tells you whether your target is realistic | Reported errors were close to Lakeside's 6.0-minute goal, so the target was plausible |
| How much data and compute did they use? | Tests feasibility against your constraints | The best sequence networks were trained on GPU clusters |
| What went wrong for them? | Saves a pass round the loop | Several warned of leakage from features recorded after a stop was completed |
| Is there reusable code or a pretrained model? | May replace training from scratch with fine-tuning | No usable pretrained model; spline feature code was reusable |
The review also explains v4. The team tried the deep network because the reports it found showed the lowest errors. That was a fair reason to try it. Yet the review's own compute row had already shown that those results came from hardware Lakeside did not have. Reading for constraints as well as accuracy would have saved a pass round the loop. Time-box the review, for example two days for a familiar problem, and record what you rejected and why.
Hyperparameter tuning: searching the settings of one design
A model's parameters are learned from data during fitting: regression coefficients, or the split points of a tree. Its hyperparameters are set before fitting and control how learning happens: tree depth, learning rate, regularization strength. Hyperparameter optimization, usually called tuning, searches for the settings that give the best validation score within one architecture.
Three search strategies dominate.
- Grid search tries every combination of the listed values. scikit-learn's ParameterGrid generates the combinations, and GridSearchCV fits and cross-validates each one. It is exhaustive and easy to reproduce, but its cost multiplies with every added value, as the training-cost example showed.
- Random search samples a fixed number of combinations from ranges or distributions. For the same budget it tries more distinct values of each hyperparameter, which helps when only a few hyperparameters matter much.
- Adaptive search uses early results to decide what to try next. Bayesian optimization builds a model of the score as a function of the settings and picks promising points. Successive halving gives many candidates a small budget, then spends more on the best ones.
Here is the code behind Lakeside's monthly v3 search. It uses scikit-learn's histogram-based gradient boosting, where max_iter is the number of boosting iterations, one tree each for regression.
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit, train_test_split
from sklearn.ensemble import HistGradientBoostingRegressor
# Data sorted by time: hold out the most recent 20% of stops for the final check
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
grid = {
'learning_rate': [0.05, 0.1],
'max_depth': [4, 6, 8],
'max_iter': [200, 400, 600],
}
search = GridSearchCV(
HistGradientBoostingRegressor(),
grid,
cv=TimeSeriesSplit(n_splits=5),
scoring='neg_root_mean_squared_error',
n_jobs=-1,
)
search.fit(X_dev, y_dev)
print(search.best_params_)
print(-search.best_score_) # flip the sign back to RMSE
And here is an excerpt of the results, sorted by rank (fictional values).
| Rank | learning_rate | max_depth | max_iter | mean_test_score | std_test_score | mean_fit_time (s) |
|---|---|---|---|---|---|---|
| 1 | 0.1 | 8 | 600 | -5.41 | 0.21 | 2,640 |
| 2 | 0.05 | 8 | 600 | -5.44 | 0.19 | 2,710 |
| 3 | 0.1 | 6 | 600 | -5.52 | 0.24 | 1,980 |
| 18 | 0.05 | 4 | 200 | -6.71 | 0.30 | 640 |
The winner is the setting with the highest mean score, -5.41, which is an RMSE of 5.41 minutes. GridSearchCV reports it through best_params_ and best_score_.
Before you crown rank 1, ask whether its lead is real. The std_test_score column is the standard deviation of a candidate's score across the five folds. Rank 1 beats rank 2 by 0.03 minutes, while each candidate's score moves by about 0.2 minutes from fold to fold. A gap that small is inside the noise. A sounder check compares two candidates fold by fold on the same splits: compute the five differences, then look at their mean and spread. If rank 1 wins in some folds and loses in others, treat the two as tied. Be careful with a formal paired t-test (Lesson 1) on fold scores. The folds share training data, so the scores are not independent, and a plain test overstates confidence.
When candidates tie within noise, pick the simpler, faster or cheaper one. Rank 3 trails rank 1 by 0.11 minutes, about half a fold standard deviation, and trains about a quarter faster with shallower trees. If latency or model size were tight, rank 3 would be the rational choice. scikit-learn lets you pass a function to refit that encodes this kind of trade between score and complexity.
Tuning has one rule that is broken constantly: the data used to choose hyperparameters must not also judge the chosen model. scikit-learn's documentation describes the pattern: split the data into a development set for fitting the search and an evaluation set for the final evaluation.[7] If you tune on the test set, the best score is biased upward, because you picked the candidate that happened to fit that sample's noise. On a small dataset, nested cross-validation gives an honest estimate of the whole tuning procedure by running the search inside each outer fold. For time-ordered data like Lakeside's, the folds must respect time. TimeSeriesSplit trains on the past and validates on the future. Random folds would leak future information and make the score look better than it is.
The point: tuning searches settings within a fixed design. Its cost multiplies with every value you add, a lead smaller than the fold-to-fold spread is not a real lead, and the score that selects the settings must come from data the final test never touches.
Experiment tracking: making every pass reproducible
By the time v3 shipped, Lakeside's team had run more than 200 fits across four architectures. Without records, nobody can answer simple questions. Which data snapshot produced the 5.4? Was the 6.6 measured before or after the leakage fix? Experiment tracking is the practice of logging each training run's inputs, settings, results and outputs in one searchable place, so that runs can be compared and repeated.
| Item | Example | Why |
|---|---|---|
| Parameters and hyperparameters | max_depth=8, learning_rate=0.1 | Reproduce and compare settings |
| Metrics | val_rmse=5.41, val_rmse_std=0.21, p95_latency_ms=38, fit_seconds=2640 | Compare candidates against the specification |
| Data version | Snapshot ID or hash of the training table | Results change when the data change |
| Code version | Git commit ID | Find the exact code that produced the run |
| Environment | Library versions, container image, hardware type | Results and speed depend on them |
| Artifacts | Model file, residual plots, feature list | Reuse the model and review its diagnostics |
| Tags and notes | architecture=gbm, leakage_fix=true | Filter and group runs later |
MLflow is an open-source tracking tool. Its tracking component offers Python, R, Java and Representational State Transfer (REST) application programming interfaces (APIs) for logging experiment data and models.[8] For supported libraries, a single mlflow.autolog() call at the top of the training code logs metrics, parameters and models without explicit log statements.[8] Runs are grouped into named experiments so that runs aimed at the same task can be compared side by side. A tuning search fits naturally as one parent run with a child run for each candidate, and tags label runs so you can filter them later. Here is a manual version of v3's run.
import mlflow
mlflow.set_experiment('lakeside-eta')
with mlflow.start_run(run_name='v3-gbm'):
mlflow.set_tag('architecture', 'gradient_boosting')
mlflow.set_tag('data_version', 'stops_2026w40')
mlflow.log_param('max_depth', 8)
mlflow.log_param('learning_rate', 0.1)
mlflow.log_metric('val_rmse', 5.41)
mlflow.log_metric('p95_latency_ms', 38)
Tracking complements version control; it does not replace it. Code belongs in a version control system such as Git, usually hosted on a service like GitHub or GitLab; some older teams still use Subversion (SVN). The tracker stores the commit ID, so each run points back to its exact code. Data need the same treatment, because a run can be reproduced only if its input data can be recovered.
Model architecture iteration: changing the design itself
Model architecture iteration changes the structure of the model rather than its settings. It might mean a different model family, new transformations built into the model, or a different network shape. The boundary with tuning is blurry, because the number of layers in a neural network can be searched like any other hyperparameter. A practical test helps. If the change needs new code or a new pipeline rather than a new value in a grid, treat it as an architecture iteration and log it as a new candidate.
Lakeside's history shows the pattern. Each change answered a specific piece of evidence.
| Pass | Change | Evidence that prompted it | Result |
|---|---|---|---|
| v1 to v2 | Log target, spline on distance, hour-by-depot interactions | Curved, funnel-shaped residuals | RMSE 7.8 to 6.6 |
| v2 to v3 | Gradient-boosted trees | Remaining structure came from more interactions than could be coded by hand; the literature favored trees | RMSE 5.4, all constraints met |
| v3 to v4 | Deep neural network | Reports of lower errors | RMSE 5.2, but failed latency, hardware, training window and cost |
| v3 to v3.1 | Add a building-type feature | Depot 7 residuals averaged +3 minutes | Planned next pass |
When you do not know what to change next, match the symptom to the move.
| Symptom | Likely cause | Next move |
|---|---|---|
| Training and validation error both high and close together | Underfitting (high bias) | Richer architecture or better features |
| Training error low, validation error much higher | Overfitting (high variance) | Regularize, simplify or add data; then retune |
| Residual structure tied to one variable | Missing or badly specified feature | Add or transform that feature before changing model family |
| Two candidates differ by less than their fold-to-fold spread | No real difference | Treat as a tie; prefer the simpler, cheaper or faster one |
| Metric met, but latency or memory fails | Model too large for the hardware | Smaller ensemble or network, pruning, quantization or distillation |
| Metric met, but training window or cost fails | Training too expensive | Tune less often, warm-start from the last model, subsample, or choose a cheaper family |
| All requirements met with margin | Done for now | Stop iterating; validate and release |
Two of those terms need a definition. Quantization stores a model's weights at lower numeric precision, for example 8-bit integers instead of 32-bit floats, so the model is smaller and faster. Distillation trains a small "student" model to imitate a large "teacher" model's predictions. The table's logic is simple. Change the architecture when the evidence says the current family cannot represent the pattern. Tune when the family is right but its settings are not. Fix features when the residuals point at one variable. Stop when the specification is met with margin, because every extra pass costs time and compute.
Requirements validation: the final gate, and what flips it
Requirements validation checks that the selected candidate meets every requirement in the specification, measured the way the specification says, before release. It differs from evaluation in two ways. It uses the untouched test set rather than the validation data used for selection. And it tests constraints under realistic conditions: latency on production hardware at production load, cost at the real billing rate, and explanations reviewed by the people who will use them.
| Requirement | Target | v3 result on test weeks and production hardware | Pass? |
|---|---|---|---|
| RMSE | At most 6.0 min | 5.6 min | Yes |
| p95 latency at 300 requests a second | At most 150 ms | 41 ms | Yes |
| Hardware | CPU only, 8 GB per instance | Runs in 1.9 GB on 4 virtual CPUs | Yes |
| Weekly training | At most 2 h | 50 min | Yes |
| Training cost | At most $400 a month | About $118 | Yes |
| Dispatcher explanation | Top three factors | Per-prediction factor lists reviewed by five dispatchers | Yes (soft) |
| No driver PII | None used | Feature list reviewed | Yes |
Notice that the test RMSE, 5.6, is worse than the validation score of 5.4. That is normal. The validation score was the best of 18 candidates, so it carries a little selection luck. A test score much worse than validation would point to leakage or to overfitting the validation weeks.
Six months later the specification changes. Product wants estimates to work offline on drivers' handheld scanners. The new hard constraints are one ARM processor core, a model file of at most 5 MB, and p95 latency of at most 20 ms on the device. The accuracy target stays at 6.0 minutes. The team re-runs requirements validation.
| Candidate | Test RMSE (min) | p95 on the scanner | Model file | Verdict |
|---|---|---|---|---|
| v2: linear model | 6.7 | 2 ms | 0.1 MB | Fails accuracy |
| v3: 600 trees, depth 8 | 5.6 | 95 ms | 48 MB | Fails latency and size |
| v5: 120 trees, depth 6, with v2's features plus building type | 5.9 | 14 ms | 3.8 MB | Passes, with 0.1 min of accuracy margin |
One changed input, the hardware, flipped the decision. v3 went from the only passing candidate to a failing one, and no existing candidate passed. The team ran one more architecture iteration to build v5. Its accuracy margin is thin, so the team recorded the risk and asked product whether 6.0 minutes was a firm limit. Renegotiating a requirement is a legitimate outcome of validation, as long as the requirement's owner makes and documents the decision. Quietly moving the target is not.
The point: requirements validation is a row-by-row check on untouched data and real conditions. When a constraint changes, re-run it, because yesterday's winner may now fail.
Exam cues for objective 2.4
| The question says | Think | Do not confuse with |
|---|---|---|
| "must run on existing CPU servers", "edge device", "no GPU in production" | Physical hardware constraint; measure on the target hardware | Cost constraint: an affordable GPU is still useless if production has none |
| "retraining must finish overnight" | Time constraint on training | Inference latency |
| "respond within 100 ms" | Time constraint on inference | Training time |
| "monthly budget", "cloud bill" | Cost constraint | Hardware type |
| "accuracy fell months after launch" | Inference performance over time: drift; monitor and retrain | Overfitting during development |
| "features computed differently in production" | Training-serving skew | Concept drift |
| "residuals fan out as predictions grow" | Heteroscedasticity; transform or weight the target | Nonlinearity, which shows as a curve |
| "residuals form a curve" | Wrong functional form; add terms or change architecture | Outliers |
| "high R-squared but a patterned residual plot" | The model is inadequate; trust the plot | Accepting the model because R-squared is high |
| "R-squared rose after adding many predictors" | Check adjusted R-squared or held-out error | Proof that the new predictors help |
| "top two candidates differ by less than the fold standard deviation" | A tie; choose on simplicity, speed or cost | A clear win for the top-ranked candidate |
| "compare runs", "reproduce last month's model" | Experiment tracking | Version control of code alone |
| "find what has worked on similar problems" | Literature review | Hyperparameter tuning |
| "search learning rate and depth with cross-validation" | Hyperparameter tuning | Architecture iteration |
| "replace the linear model with gradient boosting" | Model architecture iteration | Tuning |
| "confirm the chosen model meets all requirements before release" | Requirements validation on the untouched test set and real hardware | The validation score used for selection |
| "best score is negative" | A negated error scorer; flip the sign | A broken model |
Common misconceptions
- "Select the model with the best validation metric." Selection is made against the whole specification. Lakeside's most accurate model broke four hard constraints, and a candidate that breaks any hard limit is out, however good its metric.
- "A high R-squared means the model fits." R-squared measures how much variance the model explains, not whether its form is right, and it rises with every added predictor on training data. A curved or funnel-shaped residual plot exposes an inadequate model that R-squared hides.
- "The top-ranked candidate in a search is the best model." A lead smaller than the fold-to-fold spread is noise. Compare candidates fold by fold, and break ties on simplicity, speed and cost.
- "Running a grid search in parallel makes it cheaper." Parallel jobs shorten wall-clock time. When each fit already fills a node, the total node-hours, and therefore the bill, stay the same.
- "Once a model passes validation, the iteration is finished." Data drift, concept drift, training-serving skew and slower dependencies can all break the specification after launch. Monitoring and a rollback plan keep the loop open.
- "A GPU benchmark shows the model is fast enough." Latency must be measured on the hardware where the model will serve, at the load it will face. GPU training numbers say nothing about CPU or edge-device inference.
The takeaway
- A model design iteration is judged against a written specification. A candidate that breaks any hard constraint loses, whatever its metric.
- Constraints divide into time (project deadline, training window, inference latency, data freshness) and resource (physical hardware and cost). Measure latency on the hardware the model will actually use.
- RMSE squares errors before averaging, so one large miss raises it far more than it raises MAE. Always compare a metric with a baseline such as a dummy estimator.
- R-squared = 1 - RSS/TSS never falls on training data when predictors are added; adjusted R-squared, AIC and BIC charge for extra terms, and a gap between candidates smaller than the fold-to-fold standard deviation is not a real difference.
- scikit-learn scorers follow a higher-is-better rule, so error metrics appear negated (neg_mean_squared_error), and best_score_ must be sign-flipped to read as an error.
- Grid search fits = (product of the value counts) × folds + 1 refit. Parallel jobs cut wall-clock time, not the node-hours billed when each fit fills a node.
- A residual is observed minus predicted. On a residual vs. fitted plot, a random band is good, a curve means the wrong functional form, a funnel means heteroscedasticity, and bands mean a missing categorical variable.
- Inference performance over time covers both latency and accuracy. Data drift, concept drift and training-serving skew degrade deployed models, and a rollback plan is part of deployment.
- Hyperparameter tuning changes settings within one architecture; architecture iteration changes the family or structure; experiment tracking logs parameters, metrics, data version and code commit; requirements validation uses the untouched test set and production conditions, and a changed constraint can flip which candidate wins.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Google Cloud. (n.d.). AI and ML perspective: Operational excellence. docs.cloud.google.com
- scikit-learn. (n.d.). 3.4. Metrics and scoring: quantifying the quality of predictions. scikit-learn.org
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Model Validation (4.4). itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Process Modeling section 4.4.1. itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: 6-Plot. itl.nist.gov
- scikit-learn. (n.d.). sklearn.model_selection.GridSearchCV. scikit-learn.org
- MLflow. (n.d.). MLflow Tracking APIs. mlflow.org
- Key terms
- Model specification
- The written agreement on what a model must achieve, how success is measured, and the limits on time, hardware and cost it must meet. Each requirement is marked hard (failure disqualifies) or soft (tradeable).
- Requirements validation
- The final check, before release, that a selected model meets every requirement in its specification. It uses untouched test data and realistic conditions such as production hardware and load.
- Residual
- The observed value minus the model's prediction for one observation, e = y - y-hat. A positive residual means the model under-predicted.
- Residual vs. fitted plot
- A diagnostic plot with predicted values on the horizontal axis and residuals on the vertical axis. A random band around zero suggests adequate fit; curves, funnels or clusters reveal structure the model missed.
- Heteroscedasticity
- Error variance that changes with the level of the prediction. It shows as a funnel in a residual vs. fitted plot and makes a single error metric and constant-width prediction intervals misleading.
- Hyperparameter tuning
- Searching the settings chosen before training, such as tree depth or learning rate, to find the combination with the best validation score within one model architecture.
- Model architecture iteration
- Changing a model's structure rather than its settings, such as moving from linear regression to gradient-boosted trees or changing a network's design, in response to evaluation evidence.
- Experiment tracking
- Logging each training run's parameters, metrics, data version, code version, environment and artifacts in one searchable place so runs can be compared and reproduced.
- Data drift
- A shift in the distribution of a deployed model's inputs compared with its training data, which can degrade accuracy even though the model itself has not changed.
- Training-serving skew
- A mismatch between the features computed for training and those computed in production, often caused by two code paths calculating the same feature differently.
Using Experiments and Tests to Justify a Model
- Benchmark a candidate model against a dummy baseline and against the conventional process, using the same cases, outcome, capacity and costs for each.
- Read specification testing results, both residual and calibration diagnostics and pass-or-fail requirement tests, as gates on a model recommendation.
- Report final performance measures from an untouched test set with an interval, and decide when a measured improvement justifies extra complexity.
- Sort stakeholder statements into business needs, business wants and reality, and check a recommendation against each.
Two memos about the same 10,000 claims
Harbor Mutual is a fictional regional auto insurer, and this lesson follows it from start to finish. It has set aside 10,000 claims from its most recent quarter as a test set. Investigators later confirmed 400 of them, 4 percent, as fraudulent. The fraud unit has five investigators, and together they can open 500 cases a quarter. Two memos about those 10,000 claims are now on the claims director's desk.
The first memo comes from the data science lead. Her gradient-boosted model has a ROC-AUC (Receiver Operating Characteristic - Area Under the Curve) of 0.88 on the test set. A logistic regression scores 0.84. The paper checklist that adjusters use today gives a yes or a no rather than a score, so it has no ROC curve to measure at all. Her recommendation: ship the boosted model, and the unit will catch more fraud with the same five people.
The second memo comes from the head of claims operations, who has run the checklist for eleven years. He makes three points. First, the model's accuracy is 95.6 percent, which is lower than the 96 percent you would get by calling every claim honest. Second, a claim has a confirmed label only if someone investigated it. Every claim the checklist flagged was investigated and graded, but many of the claims the model would flag were never looked at, and they sit in the test set labeled honest. Third, the compliance team requires a plain-language reason for every referral. The checklist supplies one. A boosted ensemble does not supply one by itself.
Every number in both memos is correct. Objective 2.5 is about getting from numbers like these to a recommendation that survives scrutiny. You compare the model with a baseline and with the process it would replace. You check that the model is correctly specified and that it meets its written specification. You report final performance honestly. Then you test the result against what the business actually needs, rather than what it would like.
Exam objectives: CompTIA DataX DY0-001 objective 2.5: Given a scenario, analyze results of experiments and testing to justify final model recommendations and selection.[1] The objective lists five things to weigh: the baseline, the conventional process, specification testing results, final performance measures, and business requirements. Within business requirements, you must separate needs from wants and from reality.
The sections below take the memos' claims one at a time. For each one they ask what the number shows, what it cannot show, and what would settle the question.
Benchmark one: a baseline that ignores the claim
Start with the operations head's sharpest point, because it is plain arithmetic. A model that labels every claim honest is right on 9,600 of 10,000 claims, which is 96.0 percent accuracy. Harbor Mutual's boosted model flags its top 500 claims and is right on 9,560 of the 10,000 claims, which is 95.6 percent. Judged by accuracy, the model loses to doing nothing.
That do-nothing model has a name. A baseline model is the simplest predictor anyone could plausibly use. It either ignores the inputs or applies one obvious rule. In Python, the scikit-learn library supplies one as DummyClassifier. Its documentation says it makes predictions that ignore the input features and presents it as a simple baseline to compare more complex classifiers against.[2] The predictions are not arbitrary, though. They usually depend on the labels the dummy saw during fitting.[2] Its main strategies are these:
most_frequent: always predict the most common training class. At Harbor Mutual that means "not fraud" for every claim.prior, the default: predict the same class, but return the training class proportions as probabilities (0.96 and 0.04 here).stratified: draw random labels in the training proportions, so about 4 percent of claims get flagged at random.uniform: draw each class with equal probability.constant: always predict a label you choose. This is useful when the class you care about is the rare one.
scikit-learn's user guide describes comparing your estimator with simple rules of thumb as a basic sanity check in supervised learning.[3] The same guide says dummy estimators are useful for getting a baseline value of its metrics.[3] For regression, the matching tool is DummyRegressor, which predicts a constant such as the training mean or median. The mean baseline is the yardstick built into R2: a model with an R2 of zero does no better than predicting the mean of the data.
Other kinds of task have their own standard baselines, and an exam scenario may name any of them:
- Classification: the majority class, or random labels in the class proportions.
- Regression: the training mean or median.
- Forecasting: the naive forecast, which repeats the last observed value, or the seasonal naive forecast, which repeats the value from the same period last season (see Lesson 5).
- Ranking and recommendation: recommend the most popular items to everyone.
Now for the trap in the operations memo, and why the number is still useful. In scikit-learn, a classifier's default score method returns mean accuracy on the data you pass it.[2] On a problem where only 4 percent of cases are positive, accuracy rewards a model for staying silent. Balanced accuracy fixes this by averaging the rate of correct answers within each class:
- Balanced accuracy = (TPR + TNR) / 2.
- TPR, the true positive rate (also called recall or sensitivity), is TP / (TP + FN): the share of real fraud that the model flags.
- TNR, the true negative rate (also called specificity), is TN / (TN + FP): the share of honest claims that the model leaves alone.
Here TP is a true positive, FP a false positive, TN a true negative and FN a false negative, the four cells of the confusion matrix from Lesson 2. The scikit-learn guide notes what happens when accuracy is above chance only because the classifier exploits an imbalanced test set: balanced accuracy drops to 1 divided by the number of classes, which is 0.5 for a two-class problem.[3]
| Candidate | Claims flagged | Fraud caught (TP) | False alarms (FP) | Accuracy | Recall | Balanced accuracy |
|---|---|---|---|---|---|---|
| Dummy, most_frequent | 0 | 0 | 0 | 96.0% | 0.0% | 0.500 |
| Checklist (today's process) | 600 | 150 | 450 | 93.0% | 37.5% | 0.664 |
| Logistic regression, top 500 | 500 | 190 | 310 | 94.8% | 47.5% | 0.721 |
| Gradient boosting, top 500 | 500 | 230 | 270 | 95.6% | 57.5% | 0.773 |
Work through the boosting row so you can rebuild any row yourself:
- TP = 230 and FP = 270, because the model flagged 500 claims and 230 of them were fraud.
- FN = 400 - 230 = 170, the fraud it missed.
- TN = 9,600 - 270 = 9,330, the honest claims it left alone.
- Accuracy = (230 + 9,330) / 10,000 = 0.956.
- TPR = 230 / 400 = 0.575. TNR = 9,330 / 9,600 = 0.972.
- Balanced accuracy = (0.575 + 0.972) / 2 = 0.773.
The operations head's number is correct, but his conclusion is not. A baseline's job is to set the floor: you read any metric against what the dummy scores on that same metric, on that same data. On accuracy the floor is 96 percent, and no candidate clears it. On balanced accuracy the floor is 0.500, and every real candidate clears it. On recall the floor is zero. A model is not "good" because it scores 95.6 percent. It is justified, or not, by how far it rises above the floor on the metric the decision actually depends on.
What matters here: the baseline tells you what a metric is worth on this particular data. Report the dummy's score next to the model's on every metric, and argue from the gap, never from the raw value.
Benchmark two: the conventional process the model would replace
Nobody would deploy a dummy model, so it is an easy floor to clear. The objective's second benchmark is harder to beat: the conventional process.[1] In practice that means whatever the organization does today without the model. At Harbor Mutual this is a four-item checklist (fictional, like all figures in this case). An adjuster ticks a box if the policy is under 30 days old, if the claim was filed more than 14 days after the incident, if there was a prior claim within 12 months, or if the repair shop is on a watch list. Two or more ticks send the claim to the fraud unit.
A comparison with the conventional process is only fair if both sides are measured the same way. Five things must match:
- Same cases. Score the checklist on the same 10,000 test claims, not on last year's claims or a vendor's demo set.
- Same outcome definition. "Fraud" means confirmed by investigation for every candidate.
- Same operating constraint. The fraud unit opens 500 cases, whoever does the flagging.
- Same costs. Count review time, model hosting and maintenance, and the cost of missed fraud for every candidate.
- Same period. A process tuned to 2024 fraud patterns and a model tested on 2026 claims are not being compared fairly.
The third rule changes the numbers. The checklist flags 600 claims, but only 500 can be opened. The checklist does not rank its flags, so investigators choose 500 of the 600 with no further information. On average they catch 150 x 500 / 600 = 125 fraudulent claims. The models rank every claim, so they simply hand over their top 500.
Two measures express performance under a fixed review budget. Precision at k is the share of the k reviewed cases that turn out positive. Recall at k is the share of all positives caught within those k reviews. Lift is precision at k divided by the base rate, so it tells you how many times better than random review a method is.
| Candidate | Fraud caught in 500 reviews | Precision at 500 | Recall at 500 | Lift over random |
|---|---|---|---|---|
| Random review (stratified baseline) | 20 | 4.0% | 5.0% | 1.0 |
| Checklist, 500 of its 600 flags | 125 | 25.0% | 31.3% | 6.3 |
| Logistic regression | 190 | 38.0% | 47.5% | 9.5 |
| Gradient boosting | 230 | 46.0% | 57.5% | 11.5 |
Now put money on it. Assume, as part of the example, that each caught fraud avoids an average payout of $6,000 and that each review costs $200. All candidates use the full 500 reviews, so review cost is $100,000 for each. The net quarterly value is 6,000 x (fraud caught) - 100,000:
- Checklist: 750,000 - 100,000 = $650,000.
- Logistic regression: 1,140,000 - 100,000 = $1,040,000.
- Gradient boosting: 1,380,000 - 100,000 = $1,280,000.
On these offline figures, both models beat the conventional process by a wide margin, and boosting beats logistic regression by $240,000 a quarter. That is the data science memo's case at full strength.
The operations head's second point still stands, and it is the more serious one. A claim gets a confirmed label only if someone investigates it. In the test quarter, the 400 confirmed frauds reached the unit through three channels (fictional figures): 150 from checklist referrals, 140 from tips by adjusters, repair shops and the public, and 110 found later through payment audits. The checklist is the largest single channel, but it found well under half the confirmed fraud, which is exactly why its recall is 37.5 percent. Fraud that no channel surfaced is still in the test set, labeled honest.
That creates two biases you can name. First, every recall figure is measured against fraud that someone found, not against all fraud, so true recall is lower for every candidate. Second, the bias is uneven. All 600 checklist flags were investigated, so every checklist false alarm is a real false alarm. Many of the model's top 500 were never investigated. If the model has spotted a kind of fraud that none of the three channels catches, those catches are scored as false alarms, and its true advantage could be larger than it looks. But if the model mostly learned the patterns that referrals, tips and audits already catch, its offline score flatters it on exactly the cases that were easy to label, and its advantage on new kinds of fraud could be smaller. Offline data cannot tell you which. You will meet the way out, a randomized experiment, later in the lesson.
What matters here: benchmark against the conventional process on the same cases, outcome, capacity and costs. Then ask how the labels were produced, because a process whose every flag was investigated is graded on different terms from a model whose flags mostly were not.
Specification testing, first meaning: is the model's form right?
"Specification testing results" can mean two related things in practice, and an exam scenario may use either. In statistics, a model specification is the model's chosen form: which variables it uses, how they enter (straight-line, squared, interacted) and what it assumes about the errors. A specification test asks whether that form fits the data. In engineering, the specification is the written list of requirements the model must meet, and specification tests check each requirement. This section covers the statistical meaning. The next covers the requirements meaning.
The NIST/SEMATECH e-Handbook of Statistical Methods, published by the US National Institute of Standards and Technology (NIST), calls model validation possibly the most important step in building a model, and one of the most often skipped.[4] It warns that quoting a high R2 is not validation, because a high R2 does not guarantee that the model fits well. The handbook's main tool is residual analysis, done graphically.[4] A residual is the observed response minus the model's prediction for that observation.[4] In symbols, ei = yi - f(xi), where yi is the i-th observed value and f(xi) is the fitted value. The logic is simple. If the model were correct, the residuals would behave like the random errors in the data.[4] If they show non-random structure, the model fits poorly.[4]
Harbor Mutual also runs a severity model, an ordinary least squares (OLS) regression that predicts repair cost from vehicle age, damage area and other inputs. The binned residuals below are a fictional example of a specification failure:
| Predicted cost band | Claims | Mean residual, straight-line model | Mean residual, model with squared damage-area term |
|---|---|---|---|
| $1,000 to $2,000 | 3,100 | +310 | +20 |
| $2,000 to $4,000 | 3,800 | -210 | -15 |
| $4,000 to $8,000 | 2,200 | -240 | +10 |
| $8,000 to $16,000 | 900 | +410 | -30 |
First check something that should hold: an OLS fit with an intercept has residuals that sum to zero. Weight each band's mean by its claim count. For the straight-line column, 3,100 x 310 - 3,800 x 210 - 2,200 x 240 + 900 x 410 = 961,000 - 798,000 - 528,000 + 369,000 = 4,000, an average of $0.40 per claim, which is effectively zero. The squared-term column also sums to zero. So the problem is not the average error. It is the pattern.
Read the third column from top to bottom: positive, negative, negative, positive. Plotted against predicted cost, the residuals would form a U. The model underpredicts cheap and expensive repairs and overpredicts the middle. In other words, the real relationship curves while the model draws a straight line. Its R2 might still be high, because a straight line captures most of a gently curving trend. Any RMSE (Root Mean Square Error) you report for this model describes a misspecified model, and its errors are systematic: they will hit the most expensive claims hardest.
The fix is often suggested by the diagnosis. NIST makes this point too: residual analysis usually points to a remedy, so finding a problem does not mean starting over.[5] Its load cell calibration case study is the classic example. A straight-line fit left patterned residuals, and changing the functional form to a quadratic made every residual plot satisfactory.[6] Harbor Mutual's fourth column shows the same thing: adding a squared damage-area term leaves residual means scattered close to zero in every band.
A full residual review covers four checks, each with its own plot:
- Functional form: residuals against fitted values or each predictor. A curve or U means a missing term or transform.
- Constant variance: the spread of the residuals across fitted values. A funnel shape means the variance grows with the level, which calls for a transform or weighting.
- Independence: residuals in time order, and a lag plot of each residual against the previous one. Runs or a diagonal lag pattern mean autocorrelation, which pushes you toward the temporal models of Lesson 5.
- Error distribution: a histogram and a normal probability (Q-Q, Quantile-Quantile) plot. Heavy tails make normal-theory intervals misleading.
Formal tests confirm what the plots suggest. Examples include a lack-of-fit test when replicate observations exist, Ramsey's RESET (Regression Equation Specification Error Test), which adds powers of the fitted values and tests whether they matter, and the Breusch-Pagan test for non-constant variance. A small p-value from any of these is a specification test result that the exam may ask you to act on.
Classifiers have no residual plot, but calibration plays the same role. You sort the test cases into score bands and compare the average predicted probability with the observed rate in each band. A well-specified model's predictions match reality band by band.
| Score band | Claims | Mean predicted probability | Confirmed fraud | Observed fraud rate |
|---|---|---|---|---|
| 0.00 to 0.02 | 6,000 | 0.003 | 15 | 0.0025 |
| 0.02 to 0.05 | 2,200 | 0.024 | 50 | 0.023 |
| 0.05 to 0.20 | 1,300 | 0.080 | 105 | 0.081 |
| 0.20 to 0.50 | 350 | 0.36 | 130 | 0.371 |
| 0.50 to 1.00 | 150 | 0.66 | 100 | 0.667 |
Check the table against the rest of the case. The claims add to 10,000 and the confirmed fraud adds to 400, the whole test set. The two top bands hold exactly 500 claims, the 500 highest scores, and 130 + 100 = 230 confirmed frauds, which matches the 230 the model catches in its top 500. Multiplying each band's claims by its mean predicted probability gives 18 + 52.8 + 104 + 126 + 99, about 400 expected frauds. In every band, predicted and observed rates are close.
Calibration matters to Harbor Mutual because the expected-value arithmetic in the previous section multiplies probabilities by dollars. A model that ranks well but says 0.60 when the truth is 0.30 would make every dollar estimate wrong by a factor of two.
Specification testing, second meaning: does the model meet its spec?
Before training began, Harbor Mutual's project charter listed requirements for any fraud scorer. Each requirement becomes a test, and the results form a table like this one. This is the second thing "specification testing results" can mean in a scenario: a set of pass or fail outcomes against written requirements.
| Test | What it checks | Gradient boosting | Logistic regression |
|---|---|---|---|
| Input schema | A claim missing its policy start date is rejected with a clear error, not scored | Pass | Pass |
| Leakage audit | No feature is recorded after the referral decision | Failed in version 6 (used an investigation_opened field); fixed in version 7 | Pass |
| Latency | 95th-percentile scoring time under 300 ms on the intake server's CPU (Central Processing Unit) | 140 ms, pass | 9 ms, pass |
| Invariance | Changing only the claimant's name moves the score by less than 0.01 | Pass | Pass |
| Directional expectation | A policy under 30 days old raises the score, all else equal | Pass | Pass |
| Reason codes | Each referral comes with its top three contributing factors in plain language | Pass only with an added attribution layer | Pass, read directly from coefficients |
| Calibration | Predicted and observed rates agree within each score band | Pass | Pass |
Three rows deserve comment. The leakage row tells a story that happens often. Version 6 of the boosted model scored 0.97 ROC-AUC because it had learned from a field that is only filled in after an investigator opens a case. The model was reading the answer. The 0.88 for version 7 is the honest figure, and any memo quoting 0.97 would have been quoting a test failure as a success.
The invariance and directional rows are behavioral tests. They check the model's responses to controlled changes in its input, the way unit tests check code. They catch models that latch onto meaningless fields or that contradict what experts know.
The reason-codes row is where the compliance requirement from the operations memo becomes testable. The boosted model can pass, but only with an extra explanation component. That component has to be built, validated and maintained, and so it adds to the model's cost.
What matters here: specification test results are gates, not tiebreakers. A model that fails a need-level test is out, whatever its AUC. A patterned residual plot or poor calibration means that every metric reported for the model describes a misspecified model.
Final performance measures: one test set, one look, an interval
A final performance measure is the figure you put in the recommendation and stand behind. Four conditions make it trustworthy:
- Untouched data. It is computed on a test set that played no part in training, feature selection or tuning (Lesson 12 covers train, validation and test splits). Each look at a set that you then act on leaks a little information into your choices. After six weeks of tuning against validation folds, the validation score is optimistic. That is why test scores usually come in slightly lower, and the test score is the one to report.
- Chosen in advance. The team picks the metric before seeing the results, and picks it because the decision depends on it. Here that metric is fraud caught within 500 reviews, not accuracy and not even ROC-AUC. AUC summarizes ranking over all thresholds, while Harbor Mutual operates at a single point: the top 500.
- Reported with uncertainty. A point estimate without an interval cannot tell a real gain from noise.
- Shown beside the benchmarks. The baseline and the conventional process appear in the same table, on the same metric.
Here is what Harbor Mutual's final evaluation report looks like (fictional example):
HARBOR MUTUAL FRAUD SCORER: FINAL EVALUATION (fictional example)
Test set: claims 2026-Q2, n = 10,000, confirmed fraud = 400 (4.0%)
Review capacity: 500 claims per quarter
Primary metric (fixed before testing): fraud caught in top 500
candidate reviewed caught prec@500 recall@500 bal_acc roc_auc
dummy_most_frequent 0 0 n/a 0.000 0.500 0.500
checklist (rules) 500 125 0.250 0.313 0.637 n/a
logistic_l2 500 190 0.380 0.475 0.721 0.840
gbm_v7 500 230 0.460 0.575 0.773 0.880
paired bootstrap, 2,000 resamples, gbm_v7 minus logistic_l2
extra fraud caught in top 500: +40 95% interval [+18, +63]
Read the column and row names this way. gbm_v7 is version 7 of the gradient boosting machine, and logistic_l2 is logistic regression with an L2 (ridge) penalty on its coefficients. prec@500 and recall@500 are precision and recall at 500 reviews, bal_acc is balanced accuracy, and roc_auc is ROC-AUC. An n/a entry means the metric cannot be computed: the dummy reviews nothing, so it has no precision, and the checklist gives no score, so it has no ROC curve.
The checklist's balanced accuracy here (0.637) differs from the first table (0.664) because this report scores it at capacity, on 500 of its 600 flags. That gives 125 caught and 375 false alarms, so TNR = 9,225 / 9,600 = 0.961 and balanced accuracy = (0.3125 + 0.961) / 2 = 0.637.
The last two lines of the report do the real work. A paired bootstrap estimates how much the difference between two models would vary with a different sample of claims. It runs in four steps:
- Draw 10,000 claims from the test set with replacement, so some claims appear twice and some not at all.
- On that resample, count how much fraud each model catches in its top 500, and record boosting's count minus logistic regression's count.
- Repeat 2,000 times.
- Take the 2.5th and 97.5th percentiles of the 2,000 differences as a 95 percent interval.
The method is "paired" because both models are scored on the same resampled claims each time, so claim-to-claim variation cancels out of the difference. For paired yes or no outcomes on the same cases, McNemar's test is the classical alternative. It looks only at the cases where the two models disagree.
The interval [+18, +63] excludes zero, so the gain is unlikely to be noise. The bootstrap measures sampling noise in this test set only, though. It says nothing about the label bias described earlier, and nothing about next quarter's fraud patterns. A narrow interval around a biased estimate is still biased.
Run two: the fraud unit shrinks to one investigator
Change one input and run the same analysis again. Suppose a reorganization leaves Harbor Mutual with one investigator and a capacity of 100 cases a quarter. The models, the test set and the requirements stay the same. Only k changes.
| Candidate | Fraud caught in 100 reviews | Precision at 100 | Net value per quarter |
|---|---|---|---|
| Random review | 4 | 4% | $4,000 |
| Checklist, 100 of its 600 flags | 25 | 25% | $130,000 |
| Logistic regression | 68 | 68% | $388,000 |
| Gradient boosting | 71 | 71% | $406,000 |
The arithmetic follows the same pattern as before. The checklist's expected catch is 150 x 100 / 600 = 25. Net value is 6,000 x (fraud caught) - 200 x 100. For boosting that is 426,000 - 20,000 = $406,000. At the very top of the ranking, both models find the same obvious cases, so their difference shrinks to 3 claims. The paired bootstrap interval for that difference is now [-6, +12] (fictional). It contains zero, so the test set cannot tell the two models apart at this capacity.
The recommendation flips to logistic regression, and the reasons are specific:
- The measured gain from boosting cannot be distinguished from zero.
- Logistic regression passes the reason-codes test natively. Boosting needs an attribution layer that must itself be built and maintained.
- Logistic regression scores in 9 ms instead of 140 ms, and it is simpler to retrain and monitor.
Google's problem-framing guide makes the general point: the costs of improving a model, such as engineering time and compute, have to be justified by the improvement you expect.[7] In run one, a gain of 40 caught frauds worth $240,000 a quarter justified the extra machinery. In run two, a gain somewhere between minus six and plus twelve frauds, quite possibly none, does not.
Both runs keep one thing constant: either model beats the conventional process by a wide margin. The dispute between the two memos now has a firm part (a model should replace the checklist for ranking) and a conditional part (which model depends on capacity and on what the compliance requirement costs).
What matters here: the same test results can justify different models under different operating conditions. Recompute the decision metric at the real operating point, and prefer the simpler model when the interval for the gain includes zero.
Needs, wants and reality
The objective asks you to differentiate business needs from business wants and from reality.[1] These three categories decide which test results carry the most weight.
- A business need is a requirement without which the project fails or cannot legally or operationally run. Needs become pass or fail gates.
- A business want is a desirable outcome that stakeholders would trade away for cost, time or another priority. Wants become targets to report progress against, not gates.
- Reality is the set of facts about the data, the budget, the staff and the systems that bounds what any candidate can achieve. It limits what any model can deliver.
Sorting stakeholder statements usually comes down to one question: what happens if this one is not met? If the answer is "we cannot use the model", the statement is a need. If the answer is "we would be disappointed", it is a want. If it describes a fact that holds no matter which model you choose, it is reality.
One boundary needs a rule, because system limits seem to belong to reality. A limit that the business imposes on the model as a pass or fail condition is a need, even when a system causes it. The intake system's 300 ms time-out is a need: each candidate either meets it or cannot be used, and you test for it. Reality is different in kind. It bounds every candidate's performance at once, such as 400 confirmed labels or 500 reviews a quarter, and you do not test a model against it. You use it to check whether a target is achievable at all.
| Statement from stakeholders | Category | Why it lands there |
|---|---|---|
| Catch more confirmed fraud than the checklist within the fraud unit's capacity | Need | It is the reason the project exists; failing it means keep the checklist |
| Give a plain-language reason with every referral | Need | Company compliance policy; a referral without one cannot be acted on |
| Score each claim within 300 ms at intake | Need | The intake system times out after that, so a slower model cannot be used at all; each candidate passes or fails it |
| Catch 90 percent of all fraud | Want | A goal from the director; nobody would cancel the project for reaching 60 percent |
| A live dashboard of scores by region | Want | Useful, but it does not change who gets investigated |
| Only 400 confirmed frauds in the test quarter, labels only for investigated claims, 500 reviews a quarter | Reality | Facts about data and staffing that limit every candidate equally |
Now test the 90 percent want against reality. Catching 90 percent of 400 frauds means 360 caught within 500 reviews, which requires a precision at 500 of 360 / 500 = 72 percent. The best candidate reaches 46 percent. The want is not impossible in principle: a perfect ranker would put all 400 frauds in the top 500. But it is far beyond any model this data has produced. The recommendation should say so directly: "Gradient boosting meets all three needs and raises recall at capacity from 31 to 58 percent. Reaching 90 percent would need either more investigators or a model with substantially better ranking than any we have built."
Google's problem-framing guide connects these categories to metrics. Before modeling, define the ideal outcome and the model's goal.[7] Then define success in business terms, separately from the model's evaluation metrics. The guide warns that a model can have great evaluation metrics but not move you closer to your success criteria.[7] That is the gap between an AUC of 0.88 and the fraud unit's real question: how many dollars of fraud did our 500 reviews stop?
What would settle the dispute: a randomized champion-challenger test
Offline testing has taken the argument as far as it can. The label bias in the second memo can only be removed by new labels that no existing channel chose. The standard design is a champion-challenger test, a form of A/B testing. The champion is the current process and the challenger is the proposed model.
- Randomize. For one quarter, randomly assign each incoming claim to one of two arms, about half the claims each. In the champion arm the checklist picks 250 cases to review. In the challenger arm the boosted model picks its top 250. Half the claims and half the reviews keep each arm at the same review rate as today.
- Audit at random. Investigate an extra 200 claims chosen completely at random, whatever their scores. This sample estimates how much fraud both methods miss, which is the quantity the biased labels could not provide.
- Fix the plan before starting. Write down the primary metric (confirmed fraud per review), the sample sizes, the test to be used and the stopping rule, so that nobody chooses them after seeing the results.
- Compare with the tests from Lesson 1. Fraud found per review is a proportion in each arm, so a two-proportion z-test or a chi-squared test applies.
Before running the experiment, check whether it can actually detect what you care about. Use the offline precisions as rough guesses. For checklist against boosting, 0.25 against 0.46 with 250 reviews per arm, the standard error of the difference is the square root of (0.25 x 0.75 / 250 + 0.46 x 0.54 / 250), which is about 0.042. A difference of 0.21 is about five standard errors, so one quarter is enough. For logistic regression against boosting, 0.38 against 0.46, the standard error is about 0.044 and the difference is under two standard errors. One quarter would probably not settle that question. The experiment can answer "model or checklist?" quickly. "Which model?" needs more cases or a longer run.
Deployment does not end the measurement. Google's guide advises deciding in advance when to measure success, for example six days, six weeks or six months after launch.[7] It also advises examining why a system fails, for instance a recommender that learns to promote clickbait titles until user engagement drops off.[7] Fraud has its own version of that failure: fraudsters adapt to whatever gets flagged, so a model that wins in quarter one can lose ground by quarter four. Schedule a re-test against the checklist arm before the experiment begins.
What matters here: when labels exist only for cases that someone chose to investigate, only a randomized experiment with a random audit sample can fairly compare model and process. Check the experiment's power before you run it, so you know which question it can answer.
Exam cues for objective 2.5
| The question stem says | It points to | Commonly confused with |
|---|---|---|
| "compared with always predicting the majority class", "a model that ignores the features" | Benchmark against the baseline (dummy model) | Conventional process, which is a real working method |
| "the current manual review", "existing rules", "what the team does today" | Benchmark against the conventional process | Baseline, which nobody actually uses |
| "high accuracy" on a rare-event problem | Check the baseline's accuracy; judge on recall, balanced accuracy, precision at k or MCC (Matthews Correlation Coefficient) | Concluding the model is strong |
| "residuals show a curve or funnel", "lag plot pattern", "RESET p-value is small" | Specification test failed: revise the functional form, variance model or error model | Overfitting, which shows as a train-test gap |
| "fails the latency, schema or leakage test" | Specification (requirement) test failed: the model is out or must be fixed | A tiebreaker to weigh against AUC |
| "held-out test set", "report to stakeholders", "confidence interval for the difference" | Final performance measures | Validation scores from tuning |
| "small gain, interval includes zero, higher cost" | Keep the simpler or incumbent model | Adopt the higher point estimate |
| "must", "required by policy", "hard limit", "times out" | Business need | Want, or reality when the limit comes from a system |
| "ideally", "would like", "stretch goal" | Business want | Need |
| "only N labeled cases", "budget", "staff can review K", "data available" | Reality | Need |
| "offline gain, but labels exist only for cases the old process or other channels investigated" | Randomized champion-challenger experiment with a random audit sample | More cross-validation folds on the same labels |
Common misconceptions
- "A model with 95 percent accuracy is good." On data with 4 percent positives, a model that never predicts a positive scores 96 percent. Every metric has to be read against the dummy baseline's score on that same metric.
- "Beating the baseline justifies deployment." The baseline is a floor that nobody would deploy. The decision depends on beating the conventional process under the same capacity and costs, and on passing the requirement tests.
- "A high R-squared means the model is correctly specified." NIST's handbook says plainly that a high R-squared does not guarantee a good fit. A U-shaped residual pattern can sit alongside an R-squared above 0.9.
- "The higher score wins." If the interval for the difference includes zero, the test data cannot rank the models, and cost, explainability and simplicity should decide.
- "A narrow bootstrap interval proves the result." The bootstrap measures sampling noise in the test set. It does not correct labels that exist only for investigated cases, or fraud patterns that shift next quarter.
- "Stakeholder targets are requirements." Many are wants. Sorting them into needs, wants and reality before testing stops a team from rejecting a sound model for missing a stretch goal.
Summing up
- A dummy baseline ignores the inputs and predicts from the training labels. Its score on each metric is the floor that the model's score must be read against.
- On a 4 percent fraud rate, always predicting "not fraud" gives 96 percent accuracy and a balanced accuracy of 0.500. Balanced accuracy is (TPR + TNR) / 2.
- A fair comparison with the conventional process uses the same cases, outcome definition, review capacity, costs and time period. When labels exist only for investigated cases, every recall is overstated and the comparison is uneven.
- Precision at k, recall at k and lift (precision at k divided by the base rate) measure performance under a fixed review budget.
- In the statistical sense, specification testing uses residual plots, calibration tables and tests such as RESET or lack-of-fit. Patterned residuals mean the functional form is wrong, and a changed form such as a quadratic term is often the remedy.
- In the requirements sense, specification tests (schema, leakage, latency, invariance, reason codes) are pass or fail gates, not tiebreakers.
- Final performance measures come from an untouched test set, using a metric fixed in advance, with an interval such as a paired bootstrap, shown beside the benchmarks.
- When the interval for a gain includes zero, as at 100 reviews in the Harbor Mutual example, prefer the simpler model that meets the needs.
- Needs are pass or fail gates, even when a system sets them; wants are targets; reality is the facts that bound every candidate. When labels are biased, a randomized champion-challenger test with a random audit sample settles whether a model beats the conventional process.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn. (n.d.). DummyClassifier. scikit-learn.org
- scikit-learn. (n.d.). 3.4. Metrics and scoring: quantifying the quality of predictions. scikit-learn.org
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods, 4.4.4 How can I tell if a model fits my data? itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods, 4.4.5 How can I assess the sufficiency of the functional part of the model? itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods, 4.6.1.8 (process modeling section). itl.nist.gov
- Google for Developers. (n.d.). Framing an ML problem. developers.google.com
- Key terms
- Baseline model
- The simplest predictor anyone could plausibly use, such as always predicting the majority class or the training mean. Its score on a metric sets the floor that a real model must clear on that same metric.
- Conventional process
- The method an organization uses today without the proposed model, such as a rules checklist or manual review. A candidate model is judged against it using the same cases, outcome, capacity and costs.
- Specification testing
- Checks that a model's form is right for the data, using residual plots, calibration or tests such as RESET, and that the built model meets its written requirements, such as latency, input schema and absence of leakage.
- Residual
- The observed response minus the model's prediction for that observation. Residuals that behave like random noise suggest a well-specified model; patterned residuals show a specification problem.
- Final performance measure
- The headline result in a model recommendation: computed once on a test set untouched by tuning, using a metric chosen in advance, reported with an interval and shown next to the baseline and the conventional process.
- Precision at k
- The share of the k highest-ranked cases that turn out positive. It measures a ranking model when only k cases can be acted on, such as k reviews per quarter.
- Balanced accuracy
- The average of the true positive rate and the true negative rate. It equals 0.5 for any binary classifier that wins on accuracy only by always predicting the majority class.
- Business need
- A requirement without which a model cannot be used, such as a legal, operational or system limit imposed as a pass or fail condition. It acts as a gate when selecting a model.
- Business want
- A desirable outcome that stakeholders would trade away for cost, time or other priorities, such as a stretch target for recall. It is reported against, but it does not disqualify a model.
- Champion-challenger test
- A randomized experiment that assigns live cases at random between the current process or model (the champion) and a proposed model (the challenger), so the two can be compared on real outcomes.
Communicating Results to the People Who Need Them
- Translate a model metric into a decision for executive, domain and peer stakeholders, choosing the report type and the data each one needs
- Choose a chart that suits the data types, dimensions and level of aggregation, and spot and fix charts that mislead without meaning to
- Make charts and reports accessible through color, shape, labels, fonts, text alternatives and content tagging, and recognize where government regulation applies
- Tell code documentation, data dictionaries, metadata and change descriptions apart, and write each for a real project
A churn model, a CSV file and three meetings on one Thursday
Dana Okafor's churn model produced a file with 1,200,000 rows and 41 columns. Dana is a senior data scientist at Northline Mobile, a fictional regional phone carrier invented for this lesson. The model estimates each subscriber's probability of cancelling within the next 30 days. Its output is a comma-separated values (CSV) file with one row per account: a probability, plus the 40 input features that produced it. The model has driven Northline's retention calls for a year. Before launch it passed a randomized retention experiment of the kind covered in Lesson 10. Since launch, its results have been measured against an untreated holdout group: a random slice of customers who are scored but never called.
On Thursday 19 March 2026, two weeks after a model update, Dana has three meetings about the same model. At 9:00 the chief financial officer (CFO) must decide whether to fund the retention program for a second year. At 11:00 the retention team manager wants to know which customers her agents should call next week. At 3:00 two data engineers and a machine learning (ML) engineer need to learn how to rerun and maintain the scoring pipeline while Dana is on parental leave.
The model is the same in all three rooms, and so are the numbers underneath it. What Dana brings to each room is different, and none of it is the CSV file. This lesson follows her through that Thursday and the documents that come after it. Each part of the exam objective comes up at the point where Dana needs it.
Exam objectives: CompTIA DataX DY0-001 objective 2.6: "Given a scenario, translate results and communicate via appropriate methods and mediums."[1] The objective covers types of visualizations and reports, data selection for reports, and effective communication with three kinds of stakeholder: business executive, business domain, and peers or professionals. It also covers matching data types, dimensions and levels of aggregation to visualizations, avoiding unintentionally deceptive charts, and chart accessibility, which includes font choice and size, color choice, content tagging, effectiveness for accessibility and government regulatory implications. The last part is data and model documentation: code documentation, the data dictionary, metadata and change descriptions.
Three kinds of stakeholder: executive, domain and peer
A stakeholder is anyone whose decisions or daily work depend on your result. Objective 2.6 sorts them into three groups. The groups differ less in seniority or technical skill than in the question each one brings to the meeting.
| Group | Typical people | Question they bring | Give them | Usually leave out |
|---|---|---|---|---|
| Business executive | Chief executive officer (CEO), CFO, chief operating officer (COO), chief information officer (CIO), chief technology officer (CTO), chief marketing officer (CMO), chief data officer (CDO) | Should we fund, stop, scale or change this? | The recommendation first; impact in money, customers or risk; cost; uncertainty as a range; the decision you need from them | Algorithms, hyperparameters, feature lists, raw metric tables |
| Business domain | Retention manager, marketing and sales leads, call-center supervisors, finance analysts, product owners, compliance officers | What do I do differently on Monday, and can I trust it? | Results at the grain of their work (accounts, stores, shifts); the reasons behind each flag; thresholds in their own units; a way to report errors | Training procedure, loss curves, tuning history |
| Peers and professionals | Data scientists, data engineers, ML engineers, analysts, software engineers, model validators, internal auditors | Is it correct, reproducible and maintainable? | Method, assumptions, data lineage, metrics with uncertainty, code, versions, known limitations | Very little: they need the detail the other two groups skip |
Business executive stakeholders own budgets and strategy. In one meeting they may weigh a dozen proposals, so attention is what they have least of. Lead with the recommendation, then give the evidence in their units. Each title tends to think in its own unit. The CFO asks about net value and payback. The COO asks whether the call center can absorb 5,000 extra calls a month. The CIO or CTO asks what the scoring job costs to run and what breaks if it fails. The CDO, who answers for data governance, asks which customer data the program uses and who can see it. If you know which of them makes the decision, you know which number goes in the first sentence.
Business domain stakeholders run the process your model touches. They are subject matter experts, and they know things the data does not. A retention supervisor knows that customers in an open billing dispute should not get a cheerful retention call, even if the model ranks them first. Domain stakeholders need to act, so give them results at the grain of their work: a ranked list of accounts, a short reason for each flag, and a threshold expressed as calls per week rather than as a probability. Also give them a way to push back. A team that does not trust the list will quietly ignore it, and the value you measured in the experiment will never show up in the business.
Peers and professional stakeholders are fellow practitioners, including the validators and auditors whose job is to find your mistakes. They want the method, the assumptions, where the data came from, the metrics with their confidence intervals, the code and the known limitations. Simplifying for this group is a risk as well as a discourtesy: round away a wide confidence interval and you have hidden exactly what a reviewer is there to check.
Why this matters: exam scenarios usually name the audience in the stem ("the board", "the operations manager", "another data scientist"). Identify the group first. The right format, vocabulary and level of detail follow from it.
9:00, the CFO: translating a model metric into a decision
Dana's technical summary reports a receiver operating characteristic area under the curve (ROC-AUC) of 0.81. Lesson 2 gave that number a precise meaning: pick one random churner and one random non-churner, and the model ranks the churner higher about 81 percent of the time. That answers none of the CFO's questions. The CFO wants to know whether the program brings in more money than it costs. To answer, Dana has to move from a ranking metric to a decision at one specific threshold, and then into money.
Two threshold metrics from Lesson 2 carry the calculation. Call a flagged customer who really churns a true positive (TP), a flagged customer who would have stayed a false positive (FP), and a churner the model did not flag a false negative (FN). Then:
- Precision = TP / (TP + FP): of the customers flagged, the share who really churn.
- Recall = TP / (TP + FN): of the customers who really churn, the share the model flags.
Here are the inputs. Every number is fictional, and each comes from a named piece of evidence.
| Input | Value | Where it comes from |
|---|---|---|
| Customers contacted per month | 5,000 (the top 5,000 scores) | Call-center capacity |
| Precision at that threshold | 0.30 | Untreated holdout group: 30 percent of top-scored customers did churn |
| Save rate among contacted churners | 20 percent (95 percent interval 14-26 percent) | Randomized retention experiment |
| Value of one saved customer | $900 ($50 monthly contribution margin x 18 months of expected remaining tenure) | Finance team |
| Cost per contact | $27 ($25 bill credit + $2 agent time) | Finance team |
Work it step by step.
- True churners reached: 5,000 x 0.30 = 1,500. Precision converts "flagged" into "flagged and really leaving".
- Customers saved: 1,500 x 0.20 = 300. Only churners can be saved. The other 3,500 contacts were not going to leave anyway.
- Value created: 300 x $900 = $270,000 a month.
- Cost: every contact gets the credit, churner or not, so 5,000 x $27 = $135,000 a month.
- Net: $270,000 - $135,000 = $135,000 a month.
Now the CMO asks the obvious follow-up: if 5,000 calls make money, why not make 20,000? Change that one input and rerun. A lower threshold lets in customers the model is less sure about, so precision in the holdout group falls to 0.12.
- True churners reached: 20,000 x 0.12 = 2,400.
- Saved: 2,400 x 0.20 = 480, worth 480 x $900 = $432,000.
- Cost: 20,000 x $27 = $540,000.
- Net: $432,000 - $540,000 = a loss of $108,000 a month.
The model is the same and its AUC is still 0.81, yet the decision has flipped from profitable to loss-making. The AUC describes ranking quality across every possible threshold. The business lives at one threshold. Translating a result means carrying the metric through to the place where the decision is made.
One more check belongs in the CFO's version: does the recommendation survive the uncertainty? Use the low end of the experiment's interval, a 14 percent save rate. At 5,000 contacts, 1,500 x 0.14 = 210 customers saved, worth $189,000, so net value is $189,000 - $135,000 = $54,000. At the high end, 26 percent, 390 customers are saved, worth $351,000, and net value is $216,000. The program pays at every plausible save rate, and that is a far stronger message than one point estimate. Here is the page Dana takes to the meeting:
RETENTION PROGRAM: RECOMMENDATION (fictional example)
Recommend: continue at 5,000 contacts per month. Do not expand to 20,000.
Why: 5,000 contacts return about $135,000 net per month
(range $54,000 to $216,000 across the experiment's uncertainty).
20,000 contacts lose about $108,000 per month, because most of
the extra calls reach customers who were not going to leave.
Risk: assumes the experiment's save rate keeps holding in production.
We re-measure each quarter against a 10% untreated holdout group.
Ask: approve a $1.62M annual contact budget (12 x $135,000).
Notice what is missing from the page: the algorithm, the features, the AUC. Notice what is there: a recommendation, a number in the CFO's unit, a range, the main risk, and the decision being requested. It is no less rigorous than the technical report. The rigor sits in the calculation, which Dana can produce if the CFO asks.
Why this matters: one model metric can support opposite business decisions depending on the threshold and the costs. Translation means carrying the metric all the way to the decision, in the decision-maker's unit, with the uncertainty stated as a range.
11:00, the retention team: choosing the type of report
The retention manager's first question is not about the new report at all. On 5 March her weekly call list shrank by almost half. Her own deputy had asked for a shorter list to match call capacity, but nobody sent her the note describing the change, so a deliberate decision looked like a fault. Dana explains, and the document that should have reached her appears at the end of this lesson.
Then they turn to the format. The retention manager does not need a decision memo. She makes the same decision every week: which accounts her twelve agents should call. A repeated, operational decision calls for a different format from a one-time strategic one. The table compares the report types the exam expects you to tell apart.
| Report type | Best for | Refresh | Interactivity | Main risk |
|---|---|---|---|---|
| Executive summary (one-pager) | A single funding or strategy decision | Once | None | Dropping the uncertainty and assumptions |
| Dashboard | Monitoring key performance indicators (KPIs) and repeated operational decisions | Scheduled or near real time | Filters, drill-down | Too many tiles; numbers without context; stale data that looks live |
| Scheduled static report: a Portable Document Format (PDF) file or document | A record of a period: monthly or quarterly results, regulatory filings | Periodic snapshot | None | Read once and filed; errors are hard to correct after distribution |
| Ad hoc analysis | A one-time question ("why did churn spike in May?") | Once | Low | Rushed method; reused later as if it were a standing metric |
| Technical report or white paper | Peers and validators reviewing method and evidence | Per model version | None | Unreadable to non-specialists if sent to them by mistake |
| Slide presentation | A live briefing that walks an audience through an argument | Once | Presenter-led | Slides travel without the speaker and lose their caveats |
| Notebook | Peers reproducing or extending the analysis | On rerun | Full (code) | Hidden state from cells run out of order |
For the retention team Dana builds a Business intelligence dashboard: an interactive page that refreshes every Monday. It shows the week's ranked call list, one plain-language reason for each flag ("contract ends in 21 days; 3 dropped-call complaints"), and a running tile of calls made against calls planned. It also shows saves among contacted customers against the untreated holdout group, because without the holdout the team cannot tell saves from customers who would have stayed anyway. Two rules keep it honest. Each tile states its own definition and data date. And each tile answers a question the team actually asks, or it is removed.
Dashboards and static reports are often confused, and the difference matters on the exam. A dashboard is for watching something that changes and acting on it repeatedly. A static report is a fixed record of a moment that someone may need to cite, audit or file later. Northline's quarterly results to its board are a static report even though they draw on the same data as the dashboard, because the board needs a version that will not change after the meeting.
Deciding what goes on the page: data selection for reports
Data selection means deciding which data a report shows, and which it leaves out. Every report is a selection, so the question is never whether to select but whether you selected for the decision or for the story you hoped to tell. Dana's choices for the retention dashboard show the main decisions.
- Metrics tied to the decision. The team decides whom to call, so the dashboard shows rank, probability band and reason. It does not show global feature importance, which helps an analyst but tells an agent nothing about one customer.
- A time window fixed in advance. Results are reported from the program's launch, not from whichever month makes the program look best. If the window changes, the report says so.
- A stated population and stated exclusions. Business accounts and customers in billing disputes are excluded, and the dashboard footer says so with the counts. A reader who does not know what was excluded will draw conclusions about the wrong population.
- Minimum necessary personally identifiable information (PII). Agents already have access-controlled customer records, so the dashboard shows account identifiers that link to those records, not names and phone numbers in an exportable table. The executive one-pager contains no customer-level data at all. The audience determines the PII, and most audiences need none.
- One definition per metric. "Churn" means a closed account within 30 days of the score date, in the dashboard, the one-pager and the technical report alike. Two documents that define a KPI differently will eventually disagree in front of an executive.
- Enough data to support the claim. A region with 40 customers gets a note or is pooled, because a rate computed on 40 people swings wildly from week to week.
Matching the chart to the data: types, dimensions and aggregation
The objective asks you to weigh three properties of the data when you choose a visualization: its types, its dimensions and its level of aggregation.[1] Each one narrows the choice.
Data type sets which visual encodings make sense. Nominal categories (plan type, region) have no order, so their bars can be sorted by value. Ordinal categories (satisfaction from 1 to 5) have an order the chart must keep. Continuous measures (bill amount) can sit on a position axis. Temporal data has a natural left-to-right direction. Geographic data can go on a map, but only when location itself matters to the reader.
Number of dimensions means how many variables the chart shows at once and which role each plays: x position, y position, color, size, shape or panel. One variable is univariate, two are bivariate, more are multivariate. Every encoding beyond x and y is harder to read precisely. When a chart needs a third or fourth variable, small multiples, meaning a grid of small identical charts with one panel per category, usually beat cramming color, size and shape onto one plot. For dozens of dimensions, a projection such as principal component analysis (PCA) reduces the data first, and the chart must then say that its axes are components, not original features.
Level of aggregation means the grain at which values are summarized: one row per customer, per day, per week, per region, per segment. The same data aggregated differently can tell different stories, as the worked example below shows.
| What you want to show | Data involved | Usual chart | Watch out for |
|---|---|---|---|
| Change over time | Temporal x, continuous y | Line chart | Uneven time intervals; more than about five lines |
| Comparison across categories | Categorical x, numeric y | Bar chart, sorted; horizontal when labels are long | Axis not starting at zero |
| Distribution of one measure | One continuous variable | Histogram or density plot | Bin width changes the apparent shape |
| Distributions compared across groups | Categorical plus continuous | Box plot or violin plot | A box plot hides two peaks in the data |
| Relationship between two measures | Two continuous variables | Scatter plot, with a trend line if helpful | Overplotting with millions of points: use transparency or hexagonal bins |
| Part of a whole | Categories that sum to 100 percent | Stacked bar; pie only for two to four slices | Many slices; 3D pies |
| Values across two categorical or binned dimensions | Two categories plus a value | Heat map | Color scale choice; a rainbow scale invents boundaries |
| Values by place | Geographic units plus a value | Choropleth map | Large empty areas dominate; map rates, not raw counts |
| Exact values for lookup | Any | Table | Too many digits; no units |
| Classifier performance | Scores and labels | ROC or precision-recall curve, confusion matrix, lift chart, calibration plot | An executive audience cannot read them without translation |
| Regression fit | Predictions and residuals | Residuals against fitted values; predicted against actual | Patterns hidden by aggregation |
Now the aggregation example. Later that Thursday morning the COO forwards a chart: overall monthly churn rose from 1.8 percent in February 2025, the month before the program launched, to 2.4 percent in February 2026. He asks whether the program has failed. Dana breaks the rate out by segment.
| Segment | Customers 2025 | Churn 2025 | Customers 2026 | Churn 2026 |
|---|---|---|---|---|
| Postpaid | 800,000 | 1.0% (8,000) | 700,000 | 0.9% (6,300) |
| Prepaid | 200,000 | 5.0% (10,000) | 500,000 | 4.5% (22,500) |
| All customers | 1,000,000 | 1.8% (18,000) | 1,200,000 | 2.4% (28,800) |
Churn fell in both segments, yet the overall rate rose. The reason is mix: a prepaid promotion moved the customer base toward a segment that always churns more. Prepaid was 20 percent of customers in 2025 and 42 percent in 2026. This is Simpson's paradox: a trend that holds within every group reverses when the groups are combined, because the group sizes changed. Neither number is false. The overall rate answers "how many customers are we losing?" and the segment rates answer "is retention getting better for comparable customers?" The honest report shows both and names the mix shift in one sentence.
Aggregation over time has a similar effect. Daily churn at Northline dips every weekend because stores are closed. Plotted daily, the series looks like noise around a trend. Aggregated monthly, the weekly pattern disappears and the trend becomes visible. Neither grain is right in general. Daily suits the operations team watching for a sudden outage. Monthly suits the executive watching strategy. Choose the grain the decision is made at, and label it.
Why this matters: the chart is chosen by the question, the data types and the grain together. When a scenario says an overall rate moved one way while every segment moved the other, the answer is about aggregation level and mix, not a broken model or a data error.
The chart that almost went to the board: deception without intent
The objective asks you to avoid charts and reports that deceive by accident.[1] The qualifier matters. Most misleading charts are made by people who accepted a software default or chose the version that looked cleanest.
A colleague's draft for the board showed customer retention of 92 percent before the program and 94 percent after, as two bars on a y-axis running from 90 to 95 percent. Work out what a reader sees. A bar's length is measured from the bottom of the axis, so the "before" bar is 92 - 90 = 2 units tall and the "after" bar is 94 - 90 = 4 units tall. The after bar is twice as tall. The true ratio is 94 / 92 = 1.022: retention rose by 2 percentage points, about 2.2 percent in relative terms. Readers judge bars by length, so the drawing claims a doubling that the data does not support.
Now change one thing: plot the same two values as points on a line chart. A line chart encodes value by position and change by slope, not by length from a baseline. A y-axis from 90 to 95 percent can be honest there, provided the axis is clearly labeled, because no reader is asked to compare lengths. That is why "every axis must start at zero" is too strong a rule. Bars must start at zero. Lines and points need a labeled axis and a range that does not exaggerate noise. If the 2-point difference is the message, the most honest chart may plot the difference itself, with its confidence interval, on an axis that includes zero.
| Problem | What the reader takes away | Fix |
|---|---|---|
| Truncated bar axis | Small differences look large, because bar length is read from the baseline | Start bars at zero, or chart the difference itself |
| Cherry-picked time window | A trend that exists only in the months chosen | Fix the window before looking; show longer history; mark when interventions started |
| Dual y-axes | Two series appear to move together or cross, depending on arbitrary scaling | Two aligned panels, or index both series to 100 at a common start |
| Cumulative totals | A line that can only rise is read as ongoing success | Show values per period; use cumulative only when the running total is the point |
| Area and 3D effects | Doubling an icon's height and width quadruples its area; tilted 3D pies enlarge the front slices | Encode values by 2D length or position |
| Unequal intervals or bins | Missing months or uneven histogram bins distort the shape | Even spacing; state the bin width; plot density when bins must differ |
| Rates without counts | "Complaints up 50%" when they went from 2 to 3 | Show the counts and the denominator beside the rate |
| Missing uncertainty | Point estimates read as exact | Intervals, error bars, or a range in the text |
| Rainbow scale on ordered data | Sharp boundaries between hues that do not exist in the data | A single-hue sequential scale, or a diverging scale around a meaningful midpoint |
Titles can mislead too. A chart titled "Program success" that shows cumulative saves claims something the chart cannot show. Write titles that state a checkable finding ("Saves per month held between 270 and 330 after launch") and let the data carry it.
Reading the exam's scenario cues
Objective 2.6 begins "Given a scenario", so questions describe a situation and ask for the best choice. These are the cues to look for, including the pairs people confuse.
| The stem says | Points to | Commonly confused with |
|---|---|---|
| Board, CFO, "approve the budget", "five minutes" | Executive summary: recommendation first, impact in money, a range | A dashboard or technical report |
| Operations team acts daily or weekly; "monitor" | Dashboard with scheduled refresh and drill-down | A static report, which is a fixed record |
| Another data scientist must reproduce or validate the result | Technical report, notebook, code documentation, data dictionary, versions | A simplified slide deck |
| Trend over many months | Line chart | Bar chart, which is better for discrete categories |
| Compare a handful of regions or products | Sorted bar chart | Pie chart with many slices |
| Shape or skew of one measure | Histogram (or box plot for several groups) | Bar chart of category counts |
| Relationship between two numeric measures | Scatter plot | Line chart, which implies an ordered sequence |
| Bars start above zero; "looks like it doubled" | Truncated axis: start at zero | Line charts, where a non-zero baseline can be acceptable |
| Overall rate rose but every segment fell | Aggregation and mix (Simpson's paradox): report by segment | Data-quality error or model failure |
| Color-blind readers; legend relies on color | Fill patterns, marker shapes, direct labels, contrast | A brighter or rainbow palette |
| Screen reader users; complex chart | Short alt text, plus a long description or data table, in a tagged document | Putting every value into the alt text |
| Deliverable for a government agency | Accessibility regulation such as Section 508 | Privacy law, which governs PII rather than accessibility |
| "What does this field mean? What values can it take?" | Data dictionary | Metadata about the whole file |
| "Who made this file, when, in what format, who may use it?" | Metadata | Data dictionary |
| "Why do this version's numbers differ from last month's?" | Change description (changelog, release notes) | Code comments |
Making every chart readable: color, shape, labels and font
A few days later the board pack goes out, and Dana gets an email from a regional director who is color-blind. He cannot tell which line on the regional churn chart is his region. The chart separated five regions by color alone, red and green among them.
UC Berkeley's digital accessibility guidance puts the principle plainly: "Color should be supplemental to your message, but not essential for understanding."[2] It asks designers to check that color choices meet contrast requirements and to watch how color carries information in charts.[2] It also lists red-green combinations among the palettes to avoid, along with rainbow color maps.[2] Red-green is the classic problem because red-green color vision deficiency is the most common form of Color blindness. A rainbow map fails twice over: hues of similar lightness are hard to tell apart, and the eye sees sharp boundaries between hues where the data changes smoothly.
The same guidance offers three repairs, each of which keeps color but removes the dependence on it:
- Fill patterns. Hatching or dots on bars separate the series even in grayscale; Berkeley notes that patterns make different data sets stand out and easier to understand.[2]
- Marker shapes. On line charts, give each series its own marker (circle, triangle, square), which adds a second distinction between data sets.[2]
- Direct labels. Label each line at its end, or print values on bars and slices. Berkeley points out that once labels are added, the chart no longer depends on color, and the legend often becomes unnecessary.[2]
Dana's fixed chart uses a palette chosen for color-blind readers, a distinct marker on each line, and the region name written at the right end of each line. It passes the simplest test there is: print it in grayscale and see whether you can still read it.
Font choice and size affect who can read a chart at all. Charts are usually made at one size and shown at another: an axis label that was readable in a notebook shrinks to a smudge on a slide or a phone. Practical rules:
- Use a plain sans-serif typeface for chart text on screens. Avoid condensed, decorative or script fonts.
- Size tick labels and annotations for the size the chart will be displayed at, not the size it was drawn at, and check it there.
- Do not rotate long category labels to fit them under vertical bars. Turn the chart into a horizontal bar chart so the labels read normally.
- Use size and weight to rank the text: the title states the finding, axis titles give units, annotations point to the one thing that matters. Avoid long runs of capital letters, which are slower to read.
- Keep text as real text rather than part of an image. Screen readers cannot read text that has been flattened into a picture, and it blurs when magnified.
Contrast applies to text as well as to chart marks. Pale gray labels on a white background are a common default and a common failure. Formal minimum contrast ratios are set out in the Web Content Accessibility Guidelines (WCAG), and checker tools will measure a color pair against them.
Text alternatives: alt text, long descriptions and data tables
A reader who uses a screen reader cannot see the chart at all. Software reads the document aloud, and an image without a text alternative is either skipped or announced as a file name. Text alternatives come in three sizes.
Alt text is a short description attached to the image itself; in Hypertext Markup Language (HTML) it is the alt attribute of the image element. Berkeley's guidance is to keep it brief, under 150 characters.[2] Good alt text gives the chart type, what it covers and the main finding, not a list of every value. Compare two versions for Dana's chart:
Weak: regional_churn_v3.png
Better: Line chart of monthly churn by region, 2025. All five fell;
West stayed highest, ending at 3.1%.
(fictional; 96 characters when written as one line)
For a complex chart, 150 characters is not enough. Berkeley acknowledges that alt text may not have room to explain everything, while insisting it is still needed.[2] It suggests a longer plain-text description placed next to the image.[2] It also suggests an accessible data table with the chart, giving the same values in a form a screen reader can move through cell by cell.[2] A data table helps sighted readers too: an executive who wants the exact West figure can read it instead of estimating it from a line.
The three layers work together. The alt text says what the chart is and why it is there. The long description walks through the pattern. The table holds the numbers.
Content tagging, testing for accessibility, and the law
Content tagging means labeling the parts of a document by what they are, so that software can interpret them. In an accessible PDF, tags mark headings, paragraphs, lists, figures with their alternative text, table header cells and the reading order. A screen reader uses those tags to announce "heading level 2", to jump between sections, and to read a table cell together with its column header. An untagged PDF exported straight from a slide tool may be read as one jumble of text in the wrong order, or as nothing at all. HTML does the same job with semantic elements: real headings, real lists, table headers marked as headers, and alt attributes on images.
The idea is older than accessibility. A 2025 report from the National Institute of Standards and Technology (NIST), summarizing the scheme of the National Information Standards Organization (NISO), describes markup languages as mixing metadata into content by inserting flags that mark notable features, such as paragraphs or place names.[3] Tags can also mark meaning rather than structure: a sensitivity label on a report ("Confidential: contains customer data"), or topic keywords that make a report findable in a company portal. On the exam, content tagging in a chart-accessibility scenario means structural tags that assistive technology can read. In a findability or governance scenario, it means descriptive labels.
Effectiveness for accessibility is checked by testing, not assumed. Before Dana publishes the board pack she:
- Prints every chart in grayscale and checks each series can still be identified.
- Views the charts through a color-blindness simulator; Berkeley's resource list includes browser extensions for this.
- Runs the PDF accessibility checker in her document tool, which reports untagged content, missing alt text and table headers.
- Listens to the first pages with a screen reader to confirm the reading order makes sense.
- Uses only the keyboard to move through the dashboard's filters, since some users cannot use a mouse.
- Zooms the dashboard well beyond normal size to check that labels reflow rather than overlap.
Government regulatory implications come in two kinds. The first is accessibility law. In the United States, Section 508 of the Rehabilitation Act requires federal agencies to make the information and communication technology they develop, buy, maintain or use accessible to people with disabilities. Reports, PDFs and dashboards delivered to an agency fall under it, which is why agency contracts often require accessible deliverables. Section 508's technical standards point to the Web Content Accessibility Guidelines published by the World Wide Web Consortium (W3C), and many other rules use WCAG as their technical yardstick too. The Americans with Disabilities Act covers a much broader range of organizations, and in the European Union the European Accessibility Act sets accessibility requirements for certain products and services. Which law applies depends on jurisdiction, sector and the specific product or service, so a data scientist's job is to recognize when a deliverable is in scope and bring in the organization's legal or accessibility specialists.
The second kind is regulation of the data and the reporting itself. Privacy laws restrict PII in reports: health data in the US falls under the Health Insurance Portability and Accountability Act (HIPAA), and personal data in the EU under the General Data Protection Regulation (GDPR). Small groups in an aggregated table can identify individuals. A row reading "West region, prepaid, age 80+: 2 customers, 1 churned" all but names a person, which is why published statistics often suppress small cells. Regulated industries such as banking and insurance also expect formal model documentation that supervisors can review. Whatever the regulation, the documentation described next is how you show you complied.
Why this matters: accessibility is a set of concrete, testable properties (not relying on color, labels, readable fonts, alt text, tagged structure), and for some audiences, including government agencies, it is a legal requirement rather than a courtesy.
3:00, the engineers: code documentation and the data dictionary
The 3:00 meeting is about a handover. In three weeks Dana will be on leave, and the scoring job must run every Sunday night without her. The engineers do not need persuading. They need to be able to answer their own questions at 2 a.m. when the job fails. That calls for four kinds of documentation, starting with the code.
Code documentation explains what code does, how to use it and why it was written that way. It has several layers. A README file, the plain text file meant to be read first, says what the project is, how to install and run it and where its outputs go. Docstrings on each function give its purpose, inputs, outputs and assumptions. Type hints and a pinned list of package versions follow. Comments explain why, not what. A comment saying "loop over rows" repeats the code. A comment saying "exclude accounts in billing dispute: retention team request, see change 2.1.0" records a decision no one could recover from the code alone. Here is one of Dana's scoring functions:
def score_customers(features: pd.DataFrame, model, threshold: float = 0.62) -> pd.DataFrame:
"""Return active accounts whose 30-day churn probability meets the threshold.
Parameters
----------
features : one row per account_id; columns as defined in data dictionary v3.2
model : fitted classifier exposing predict_proba
threshold : probability cutoff. 0.62 yields about 5,000 flags a month at
current volumes, matching call-center capacity (see CHANGELOG 2.1.0)
Returns
-------
DataFrame of account_id, churn_prob, top_reason, sorted by churn_prob descending.
Excludes business accounts and accounts flagged in_dispute before scoring.
"""
The function refers to a data dictionary, and that is the second artifact. A Data dictionary describes each data element: its name, meaning, type, units, allowed values, source and owner. The idea is old and formal. In a 1980 federal guideline, Federal Information Processing Standards (FIPS) Publication 76, the National Bureau of Standards (NIST's former name) set out how to plan and use a data dictionary system.[4] It defined such a system as software that assists "in organization-wide data management, without restriction to computer data".[4] The guideline draws the distinction that still matters: a dictionary entry, which it calls an entity description, holds important information about a named element.[4] It does not hold the element's actual values, such as every client name in the database.[4] The dictionary describes the column. It does not contain the column.
| Field | Type | Definition | Allowed values and units | Source | Notes |
|---|---|---|---|---|---|
| account_id | String, globally unique identifier (GUID) | Identifier of one billing account | 36-character GUID | billing.accounts | Treated as PII: links to a person |
| plan_type | Categorical | Contract type on the score date | postpaid, prepaid | crm.plans | Business plans excluded upstream |
| tenure_months | Integer | Whole months from activation_date to score date | 0-480 months | Derived | Changed in v3.2: previously counted from first_bill_date |
| avg_monthly_bill | Decimal | Mean billed amount over the previous 6 months | US dollars, 2 decimal places | billing.invoices | Excludes taxes and one-time fees |
| churned_30d | Boolean | Target label: account closed within 30 days of score date | 0 or 1 | Derived | Unknown for the most recent 30 days |
The tenure_months note shows why a dictionary pays off. If an engineer recomputes tenure from the billing date, the model silently gets different inputs from the ones it was trained on. The dictionary is where that definition is written down. The 1980 guideline made the same point at the scale of a government: a well-kept dictionary makes similar data elements visible and reliably identifies what data an organization holds.[4] In a company, that is how two teams discover that they each built their own "tenure" and that the two disagree.
Metadata and change descriptions: the record that outlives the meeting
Metadata is data that describes data. Two respected frameworks divide it differently, and the exam could use either, so learn both.
NIST's security glossary names two types: "structural metadata describing data structures (e.g., data format, syntax, and semantics) and descriptive metadata describing data contents".[5] Its example of descriptive metadata is a security label.[5] The glossary offers these two types as examples, not as a complete list.[5]
The NISO scheme, as summarized in the 2025 NIST report, has four categories: descriptive, administrative, structural and markup languages.[3] Administrative metadata is the broad one: information needed to manage a resource, or that relates to its creation.[3] Inside it sit technical metadata, the details needed to decode and render a file, such as its file type.[3] It also holds preservation metadata, such as a checksum or hash that proves a file is unchanged.[3] And it holds rights metadata, such as a license.[3] NISO's structural metadata is narrower than NIST's. It describes how the parts of a resource relate to one another, such as pages in a sequence.[3]
A practical test, which the NIST report credits to Cornell University's research data management service group: metadata should cover the who, what, when, where, why and how of a dataset in the context of its domain.[3] Here is the metadata record Dana attaches to each weekly score file:
{
"title": "Northline churn scores, week of 2026-03-16 (fictional)",
"description": "30-day churn probability for each active consumer account",
"creator": "Data Science team, owner D. Okafor",
"created": "2026-03-15T23:40:00Z",
"format": "CSV, UTF-8, comma-delimited, header row",
"row_count": 1200000,
"checksum_sha256": "9f2c...e71a",
"schema": "churn data dictionary v3.2",
"model_version": "2.1.0",
"part_of": "weekly churn scores 2026, file 12 of 52",
"classification": "Confidential: contains linkable account identifiers",
"retention": "Delete 90 days after creation",
"rights": "Internal use only"
}
| Field | NIST glossary (two named types) | NISO scheme (four categories) |
|---|---|---|
| title, description | Descriptive | Descriptive |
| classification | Descriptive (a security label) | Usually administrative (needed to manage access) |
| row_count | Descriptive (describes the contents) | Administrative: technical |
| format | Structural (data format) | Administrative: technical (needed to decode the file) |
| schema | Structural (syntax and meaning of the fields) | Administrative: technical (needed to read the columns) |
| creator, created, model_version | Not one of the two named types | Administrative (relates to creation, or provenance) |
| checksum_sha256 | Not one of the two named types | Administrative: preservation |
| retention, rights | Not one of the two named types | Administrative: management and rights |
| part_of | Not one of the two named types | Structural (how this file relates to the other files in the series) |
Read the format row. A file's format is structural metadata in the NIST glossary's sense and technical, administrative metadata in NISO's. Neither framework is wrong; they cut the same facts along different lines. If an exam stem describes structural metadata as format, syntax and semantics, it is using the NIST framing. If it pairs structural metadata with how parts fit together, or administrative metadata with creation and rights, it is using NISO's. Let the stem's wording decide.
Metadata pays off at scale, which is why organizations standardize it. The 2025 NIST report calls the management of metadata foundational to an enterprise's digital transformation.[3] Public data works the same way: NIST lists the Project Open Data schema as a shared schema used to describe data resources available from across the US Government.[6]
The last artifact is the change description: a dated record of what changed between versions, why, and what effect it had. It is the document the retention manager should have received on 5 March, when her weekly call list shrank by almost half. A commit message records a change to code. A changelog or release note records changes that users will notice. A change description for a model must record the effect on outputs and metrics, not just the edit:
## 2.1.0 (2026-03-05, fictional)
Changed: decision threshold 0.55 -> 0.62, at retention team request
(call capacity 5,000 contacts per month).
Effect: flags per month 8,900 -> 5,000; holdout precision 0.24 -> 0.30;
holdout recall 0.074 -> 0.052.
Data: tenure_months now counted from activation_date, not first_bill_date
(data dictionary v3.2). Retrained on Jan 2024-Dec 2025.
Unchanged: feature set, algorithm, exclusion rules.
Notify: retention manager, retention team leads, finance.
Author: D. Okafor. Reviewed by: J. Ramos (model validation).
Check the effect line with the formulas from 9:00. At 5,000 flags and 0.30 precision, TP = 1,500. With about 28,800 churners a month, TP + FN = 28,800, so recall is 1,500 / 28,800 = 0.052. At 8,900 flags and 0.24 precision, TP = 2,136, and 2,136 / 28,800 = 0.074. The entry tells a reader exactly what the threshold change traded away: fewer wasted calls, at the cost of reaching fewer of the customers who leave. The Notify line is the fix for March's surprise: a change description only works if it reaches the people whose numbers it moves. Many teams also publish a model card, a short standard document listing the model's intended use, training data, evaluation results by subgroup and known limitations, and update it with each change description.
| Artifact | Describes | Main reader | Answers |
|---|---|---|---|
| Code documentation | Programs: purpose, inputs, outputs, design decisions | Engineers maintaining the code | How do I run, use or change this safely? |
| Data dictionary | Each data element: meaning, type, units, allowed values, source | Anyone using the fields | What does this column mean? |
| Metadata | A dataset or file: origin, date, format, structure, sensitivity, rights | Catalogs, governance, downstream users | What is this file, and may I use it? |
| Change description | Differences between versions and their effects | Everyone who relied on the old version | What changed, why, and what does it do to my numbers? |
Why this matters: documentation is how a result outlives the meeting it was presented in. When a scenario asks for the meaning of a field, choose the data dictionary. For the origin and handling of a file, choose metadata. For why numbers moved between versions, choose a change description.
Common misconceptions
- "Every chart axis must start at zero." Bars must, because readers compare their lengths from the baseline. Line charts and scatter plots encode values by position and slope, so a clearly labeled non-zero axis can be honest there.
- "Executives want less rigor." They want the conclusion first and the uncertainty stated in decision terms. The 5,000-contact recommendation was stronger because it showed the range from $54,000 to $216,000, not weaker.
- "Accessibility means picking a color-blind-safe palette." Palette is one part. Fill patterns, marker shapes, direct labels, readable fonts, alt text, long descriptions, data tables and tagged document structure all matter, and a safe palette with color-only meaning still fails a grayscale print.
- "A data dictionary and metadata are the same thing." A data dictionary is a kind of metadata focused on defining each data element. Metadata also covers file-level facts such as creator, creation date, format, checksum, sensitivity and rights.
- "A dashboard is always better than a static report." Dashboards suit repeated decisions on changing data. A decision of record, an audit or a regulatory filing needs a fixed version that will not change after it is read.
- "If the overall number and the segment numbers disagree, one of them is wrong." Both can be correct when the mix of groups changes. That is Simpson's paradox, and the fix is to report both levels and explain the mix.
Looking back
- Objective 2.6 names three stakeholder groups: business executives (fund, stop or change), business domain experts (act on results in their own process) and peers or professionals (verify, reproduce and maintain).
- An AUC of 0.81 gave a net gain of $135,000 a month at 5,000 contacts and a loss of $108,000 at 20,000. A ranking metric becomes a business result only at a specific threshold with specific costs.
- Precision is TP / (TP + FP) and recall is TP / (TP + FN). Raising the threshold from 0.55 to 0.62 raised precision from 0.24 to 0.30 and cut recall from 0.074 to 0.052.
- Dashboards serve repeated operational decisions on changing data. Static reports are fixed records. Executive summaries serve one decision. Technical reports and notebooks serve peers.
- Chart choice follows the question, the data types, the number of dimensions and the level of aggregation: lines for time, sorted bars for categories, histograms for distributions, scatter plots for relationships. When an overall rate rises while every segment falls, a change in mix is the cause (Simpson's paradox), so report both levels.
- A bar axis starting at 90 percent made 92 against 94 percent look like a doubling. The true relative change was about 2.2 percent.
- Accessible charts do not rely on color alone: they add fill patterns, marker shapes and direct labels, avoid red-green and rainbow palettes, and meet contrast requirements.
- Alt text should be short (Berkeley suggests under 150 characters) and state the main finding. Complex charts also need a long description or an accessible data table, and documents need content tags for structure and reading order.
- A data dictionary defines fields, metadata describes datasets and files, code documentation explains programs, and a change description records what changed, why, and the effect on outputs. The NIST glossary calls data format structural metadata; NISO files file type under administrative (technical) metadata and keeps structural for how parts relate.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- UC Berkeley Digital Accessibility. (n.d.). Graphs, Charts, and Complex Images. dap.berkeley.edu
- NIST. (2025). NIST AMS 100-65 (metadata model for manufacturing data). nvlpubs.nist.gov
- NIST (National Bureau of Standards). (1980). FIPS PUB 76: Guideline for Planning and Using a Data Dictionary System. nvlpubs.nist.gov
- NIST CSRC. (n.d.). metadata (CSRC Glossary). csrc.nist.gov
- NIST. (n.d.). Metadata and Vocabulary Standards for NIST Data. data.nist.gov
- Key terms
- Business executive stakeholder
- A senior leader such as a CEO, CFO, COO, CIO or chief data officer who decides whether to fund, stop or change work, and needs the recommendation first, with impact stated in money or risk and uncertainty given as a range.
- Business domain stakeholder
- A subject matter expert who runs the business process a model affects, such as a retention manager or call-center supervisor, and needs results at the grain of daily work along with reasons they can act on.
- Level of aggregation
- The grain at which data is summarized for a chart or report, such as per customer, per day, per month or per segment. Changing it can change the pattern a reader sees.
- Simpson's paradox
- A trend that appears within every subgroup but reverses when the subgroups are combined, because the subgroups' relative sizes differ or have changed.
- Truncated axis
- A value axis that starts above zero. On a bar chart it exaggerates differences, because readers compare bar lengths from the baseline.
- Alt text
- A short text alternative attached to an image, read aloud by screen readers. It should give the chart type and its main finding, and complex charts should also have a longer description or a data table.
- Content tagging
- Labeling the parts of a document, such as headings, figures, tables and reading order, or labeling its meaning, such as sensitivity, so that assistive technology and other software can interpret it.
- Data dictionary
- A catalog of data elements giving each one's name, definition, type, units, allowed values, source and owner. It describes the elements but does not contain their actual values.
- Metadata
- Data that describes data, such as who created a dataset, when, its format, its structure, its sensitivity and the rights to use it. Frameworks group it differently: NIST's glossary names structural and descriptive types, while NISO uses descriptive, administrative, structural and markup languages.
- Change description
- A dated record, such as a changelog entry or release note, of what changed between versions of code, data or a model, why it changed, and how it affects outputs and metrics.
Module 3: Machine Learning
Fitting models that generalize, choosing and explaining models, statistical and tree-based supervised learning, deep learning and unsupervised learning.
Fitting Models That Generalize: Loss, Regularization and Validation
- Choose a loss function and a regularization penalty for a scenario, and explain how each one shapes the fitted model, including the link between squared loss and variance minimization.
- Design a validation procedure that keeps out-of-sample data honest: holdout, k-fold, stratified, group and time-series splits, grid or random search, and preprocessing fitted inside the folds so that data does not leak.
- Diagnose overfitting and underfitting from in-sample and out-of-sample scores, and recognize extrapolation and the curse of dimensionality.
- Handle class imbalance and multicollinearity with oversampling, undersampling, SMOTE, class weights, a correlation matrix and the variance inflation factor, and apply Occam's razor when choosing features.
A 98.5 percent accuracy that caught no fraud
An insurer's notebook prints accuracy: 0.985 for a fraud classifier trained on 40,000 past claims. The insurer is fictional, but the result is very common. Investigators had confirmed 600 of those claims as fraud. 600 divided by 40,000 is 1.5 percent, so a model that labels every claim honest also scores 98.5 percent. The classifier had learned the base rate and nothing else.
Three mistakes produced that number. The metric rewarded the majority class. The score came from rows the model had already been fitted on. And nobody checked whether every feature would exist at the moment a new claim arrives. Each mistake has a name on the exam, and each fix belongs at a particular point in the workflow. If you apply the fixes in the wrong order, they stop working and nothing warns you.
Exam objectives: CompTIA DataX DY0-001 objective 3.1, "Given a scenario, apply foundational machine-learning concepts."[1] This lesson teaches the bullets about fitting and validating a model. These are: loss function and variance minimization; the bias-variance tradeoff, overfitting and underfitting; variable and feature selection, including feature importance, multicollinearity, the correlation matrix and the variance inflation factor (VIF); class imbalance and its mitigations, which are oversampling, undersampling and the synthetic minority oversampling technique (SMOTE); regularization; cross-validation and k-fold; the curse of dimensionality; Occam's razor, also called the law of parsimony; in sample versus out of sample; interpolation versus extrapolation; hyperparameter tuning by grid search and random search; and data leakage. Lesson 13 covers the rest of 3.1: regressors and classifiers, ensembles, embeddings, recommender systems, explainability and model drift.
The procedure below is the lesson's spine. You will walk it once on the fictional claims data. Then you will walk it again with one step moved and watch a good-looking result fall apart.
| Step | Decision you make | Objective bullets |
|---|---|---|
| 1 | What counts as an expensive mistake? | Loss function, variance minimization |
| 2 | Which rows must the model never see? | In sample vs. out of sample; interpolation vs. extrapolation |
| 3 | Is one class rare, and how will you compensate? | Class imbalance: oversampling, undersampling, SMOTE |
| 4 | How many dimensions can the data support? | Curse of dimensionality; Occam's razor |
| 5 | Which variables stay? | Variable/feature selection: feature importance, multicollinearity, correlation matrix, VIF |
| 6 | How hard should complexity be penalized? | Regularization |
| 7 | Which settings win when judged on unseen folds? | Cross-validation, k-fold; hyperparameter tuning, grid search, random search |
| 8 | Is the model too rigid or too flexible? | Bias-variance tradeoff, overfitting, underfitting |
| Second run | Did any information cross from evaluation into training? | Data leakage |
Step 1: Write down the loss function before fitting anything
A loss function scores a single prediction. It takes the true value y and the prediction ŷ (read y-hat) and returns a number. That number is zero for a perfect prediction and grows as the prediction gets worse. Training a machine learning (ML) model means searching for the parameters that make the average loss over the training rows as small as possible. The optimizer pursues exactly that number and nothing else, so the loss is where you tell the model which mistakes are expensive.
Squared error is the usual default for regression. Cornell's CS4780 lecture notes give the reason plainly: squared loss has convenient mathematical properties and is the most common loss function.[2] Other losses suit other costs. These are the ones a senior practitioner is expected to recognize on sight.
| Loss | Per-example formula | Typical use | What minimizing it produces |
|---|---|---|---|
| Squared error (averaged: mean squared error, MSE) | (y - ŷ)2 | Regression; ordinary least squares (OLS) | Predictions of the conditional mean; large errors dominate |
| Absolute error (averaged: mean absolute error, MAE) | |y - ŷ| | Regression with outliers or heavy tails | Predictions of the conditional median; robust to outliers |
| Huber loss | 0.5(y - ŷ)2 when |y - ŷ| is at most δ; δ(|y - ŷ| - 0.5δ) when |y - ŷ| is larger than δ | Regression with occasional outliers | Squared near zero, linear in the tails; you choose the cutoff δ |
| Log loss (binary cross-entropy) | -[y ln p + (1 - y) ln(1 - p)], where p is the predicted probability of class 1 | Logistic regression, neural network classifiers | Probability estimates; confident wrong answers are punished hard |
| Hinge loss | max(0, 1 - y f(x)), with y coded as -1 or +1 | Support vector machines (SVM) | A margin; rows classified correctly with room to spare cost nothing |
The two Huber pieces meet smoothly. At |y - ŷ| = δ, the squared piece gives 0.5δ2 and the linear piece gives δ(δ - 0.5δ) = 0.5δ2, so there is no jump. Beyond δ, each extra unit of error adds only δ to the loss instead of a growing amount.
Root mean square error (RMSE) is the square root of MSE. Teams report it because it is in the same units as the target. The optimizer behaves the same either way, because whatever minimizes MSE also minimizes RMSE.
A worked example shows why the choice matters. A claim-reserve model misses three claims by 1, 2 and 10 thousand dollars.
- MSE = (1 + 4 + 100) / 3 = 35, so RMSE = √35 ≈ 5.92 thousand.
- MAE = (1 + 2 + 10) / 3 ≈ 4.33 thousand.
- The single 10-thousand miss supplies 100 of the 105 squared units, about 95 percent of the squared loss. It supplies only 10 of 13 units, about 77 percent, of the absolute loss.
Under squared loss, the optimizer will bend the whole model to shrink that one miss. That is right if a large under-reserved claim really costs far more than several small misses. It is wrong if the 10-thousand miss came from a data-entry error. In that case, MAE or Huber loss stops one bad row from steering the fit.
Log loss makes the same point for classifiers. Take a claim that really is fraud. A predicted probability of 0.90 costs -ln 0.90 ≈ 0.105. A predicted probability of 0.01 costs -ln 0.01 ≈ 4.61, about 44 times as much. A model trained on log loss learns to avoid being confidently wrong, which is why its outputs tend to be usable as probabilities.
The objective lists variance minimization under the loss function, and squared error is the link. Three facts connect them.
- The best constant is the mean. Suppose a model may only predict one number c for every row. The c that minimizes the average of (y - c)2 is the mean of y, and the smallest possible loss equals the variance of y. Minimizing squared loss means minimizing the spread around the prediction.
- OLS leaves the least residual variance. In a linear regression with an intercept, the residuals average exactly zero, so their mean square equals their variance. Minimizing the residual sum of squares (RSS) therefore minimizes the variance the model leaves unexplained. R2 = 1 - RSS / TSS, where TSS is the total sum of squares, measures the share of variance the model removes.
- Regression trees split to cut variance. A regression tree chooses the split that most reduces the weighted variance of the target inside the child nodes. That is the same as reducing squared error.
The tree case is easy to compute. A node holds target values 2, 4, 10 and 12. The mean is 7 and the squared deviations are 25, 9, 9 and 25, so the variance is 68 / 4 = 17. Split it into {2, 4} and {10, 12}. Each child has variance 1, so the weighted variance is 1 and the reduction is 16. Now try {2} and {4, 10, 12} instead. The right child has mean 8.67 and variance 11.56. Weighted by 3/4 that is 8.67, so the reduction is only 8.33. The tree takes the first split.
One warning before moving on. The word variance appears twice in objective 3.1 with different meanings. Here it is the spread of the target or of the residuals. In the bias-variance tradeoff (Step 8), it is the spread of the model itself across different training sets. Exam questions expect you to keep the two meanings apart.
Remember: the loss is the only thing the optimizer sees. Squared loss targets the mean and lets large errors dominate. Absolute loss targets the median. Log loss rewards honest probabilities. Minimizing squared error is the same as minimizing residual variance.
Step 2: Fence off out-of-sample data before you look closely
In sample means the rows a model was fitted on, and in-sample error is training error. Out of sample means rows the model never saw while its parameters, features or settings were being chosen. Only out-of-sample error estimates what will happen on new claims. Training error rewards memorization. A model that simply stored every training row and repeated its label would score perfectly in sample and tell you nothing about a new claim.
The standard remedy is to hold part of the data back as a test set before doing anything else, and to make every decision without it. For the claims data, the split looks like this.
| Partition | Rows | Fraud cases | Used for |
|---|---|---|---|
| Development set | 32,000 | 480 | All fitting, feature selection, resampling and tuning, through cross-validation (CV, Step 7) |
| Test set (20 percent, stratified) | 8,000 | 120 | One final, untouched score after every decision is made |
| Total | 40,000 | 600 |
Stratified means the split keeps the fraud rate equal in both parts. 20 percent of 600 frauds is 120, so both sets stay at 1.5 percent. The test set stays out of sample only as long as you leave it alone. Suppose you check it after every experiment and keep whichever changes improve it. Then you are fitting to it, and its score becomes as optimistic as a training score.
Out of sample can mean more than randomly chosen rows. When data change over time, the honest version is an out-of-time sample: train on claims filed in 2022-2024 and test on claims from 2025, because production will always score the future. When the data contain repeated entities, the honest version is an out-of-group sample: new claimants, not new claims from claimants the model already knows. Step 7 builds both into cross-validation.
Interpolation versus extrapolation: inside or outside the training range
Out of sample is not the same as outside the data's range. Take a fictional home-price model trained on houses from 800 to 3,000 square feet. A new 1,900-square-foot house is out of sample, but the model only has to perform interpolation: estimate between values it has seen. A 6,000-square-foot house forces extrapolation: a prediction beyond the range of the training data, where the model has no evidence at all. Model families behave very differently there.
| Model family | Behavior beyond the training range |
|---|---|
| Linear regression | Continues the fitted line forever. That is fine only if the relationship really stays linear. |
| High-degree polynomial | Can swing sharply, because the highest-power term dominates far from the data |
| Decision tree, random forest, gradient-boosted trees | Flat. Every value past the last split lands in the same leaf, so the prediction stops changing. A single tree or a random forest never predicts outside the range of its training targets. |
| k-nearest neighbors (KNN) | Flat. The nearest neighbors are always the edge cases. |
| Neural network with ReLU activations | Continues in straight lines, because a network built from rectified linear units (ReLU) is piecewise linear |
Extrapolation can also hide inside the range of every single feature. Picture a claimant aged 19 with a 30-year policy tenure. Each value passes a per-column range check, but the combination never appeared in the data and could not exist. In many dimensions, most new rows fall outside the region the training rows fill. This is one face of the curse of dimensionality in Step 4.
A cheap guard is a range check at scoring time. Here is one for the claims model, with fictional values.
| Feature | Training minimum | Training maximum | Incoming claim | Flag |
|---|---|---|---|---|
| claim_amount (dollars) | 200 | 48,000 | 260,000 | Extrapolation |
| policy_tenure_months | 0 | 312 | 14 | In range |
| vehicle_age_years | 0 | 24 | 3 | In range |
In-sample error is optimistic by construction, and a test set stays out of sample only while it is untouched. An out-of-sample row can still be a case of interpolation. Extrapolation means leaving the training range, where tree models go flat and polynomials can swing wildly.
Step 3: Measure the class imbalance and choose a mitigation
A dataset has class imbalance when one label is far more common than another. The common label is the majority class and the rare one is the minority class. Google's Machine Learning Crash Course gives realistic scales: in credit card data, fraudulent purchases can be under 0.1 percent of examples.[3] At 1.5 percent fraud, our claims data is mild by comparison, and it still fooled accuracy.
Imbalance causes trouble in two places. The first is the metric. Accuracy is dominated by the majority class, so use precision, recall, average precision (AP), which summarizes the precision-recall curve in one number, or the Matthews correlation coefficient (MCC) from the lesson on measuring models (Lesson 2). The second is learning. A model trained by gradient descent updates on small batches. Take a dataset with 200 majority rows and 2 minority rows. A batch of 20 rows holds on average 20 × 2 / 202 ≈ 0.2 minority rows, so most batches contain none at all, and the model gets almost no signal about what the rare class looks like.
The mitigations change either the rows the model trains on or the weight each row carries in the loss.
| Mitigation | What it does | Strength | Main risk |
|---|---|---|---|
| Random oversampling of the minority class | Duplicates minority rows (sampling with replacement) until the classes are closer in size | Keeps every majority row | Exact copies invite memorization, and a flexible model overfits them |
| Random undersampling of the majority class | Discards a random share of majority rows | Faster training; batches now contain minority rows | Throws away information; results vary with which rows were dropped |
| Downsampling plus upweighting | Undersamples the majority, then multiplies the kept majority rows' loss weight by the same factor | The model learns both what each class looks like and how common it is | One more hyperparameter to tune (the factor) |
| SMOTE | Creates synthetic minority rows on line segments between a minority row and its minority neighbors | No exact duplicates; fills in the minority region | Can create implausible points and blur the boundary near majority rows |
| Class weights | Leaves the rows alone and multiplies each class's loss by a weight | No data altered; cheap | Raw probabilities no longer match real frequencies |
| Threshold moving | Trains normally, then picks a decision cutoff other than 0.5 | Matches the operating point to the business cost | Needs validation data to choose the cutoff |
Why upweight after downsampling? A model must learn two things during training: what each class looks like, and how often each class occurs. Google's course points out that standard training on imbalanced data mixes those two goals together, and that downsampling followed by upweighting separates them. Downsampling means training on a disproportionately small share of the majority examples. In Google's example, the 200-to-2 dataset is 99 percent majority, and downsampling the majority by a factor of 25 leaves 8 majority rows for the 2 minority rows, an 80 to 20 split.[3] Each kept majority row then gets a loss weight of 25. In the loss, the 8 rows still stand in for 200, so the model keeps an accurate sense of the true frequency. How large a factor to use is a tuning question: treat it like any other hyperparameter and compare values on validation data.
The synthetic minority oversampling technique (SMOTE) builds new minority rows instead of copying old ones. The steps are:
- Take a minority row xi and find its k nearest minority neighbors (k = 5 is the usual default).
- Pick one of those neighbors at random and call it xnn.
- Draw a number u uniformly between 0 and 1.
- Create xnew = xi + u(xnn - xi).
The new point lies on the line segment between the two real ones. Here is a worked example with two standardized features, claim amount and days since the policy started. A fraud row sits at xi = (1.2, -0.8) and its chosen neighbor at xnn = (2.0, -1.6). The difference is (0.8, -0.8). With u = 0.25, a quarter of that difference is (0.2, -0.2), so xnew = (1.4, -1.0).
SMOTE has three cautions. It measures neighbors by distance, so standardize the features first, or a feature measured in dollars will dominate the distance. Interpolation also assumes the space between two frauds is fraud-like. If honest claims sit between them, the synthetic rows land in honest territory and blur the boundary. Finally, plain SMOTE interpolates categorical codes into meaningless values, such as 0.25 of a region. Variants such as SMOTE-NC handle mixed numeric and categorical data.
Class weights get a similar effect without touching any rows. scikit-learn's balanced setting gives each class the weight n_samples / (n_classes × n_class_samples). In the development set, fraud gets 32,000 / (2 × 480) ≈ 33.3 and honest claims get 32,000 / (2 × 31,520) ≈ 0.508. Each fraud row now counts about 66 times as much as an honest row in the loss. The two classes carry equal total weight: 480 × 33.3 ≈ 31,520 × 0.508 ≈ 16,000.
The mitigations differ in what they do to predicted probabilities. Random oversampling, undersampling on its own, SMOTE and balanced class weights all change the class ratio the model effectively learns from, so its raw scores overstate how common fraud is. Downsampling followed by a matching upweight is designed to restore the true ratio inside the loss, and threshold moving leaves training untouched. If downstream users need real probabilities, for a reserve calculation for example, recalibrate a model trained with one of the ratio-shifting methods on data with the true class ratio. If users only need a ranking, or a yes/no decision at a chosen threshold, the distortion matters less.
Whatever you choose, apply the mitigation to training data only. Validation folds and the test set keep the real 1.5 percent fraud rate, because that is the world the model will face. The second run at the end of this lesson shows what happens when that rule is broken.
Remember: random oversampling duplicates minority rows, undersampling discards majority rows, and SMOTE interpolates new minority rows between neighbors. Class weights and upweighting reweight the loss instead of changing the data. Every one of them is applied to the training portion only.
Step 4: Respect the curse of dimensionality and Occam's razor
The claims table arrives with 85 candidate features (fictional, like the rest of the project). Why not keep all of them and let the model sort them out? The answer is the curse of dimensionality. Every feature adds a dimension, and Google's crash course explains that as dimensions are added, the volume of the space grows so fast that the training data become sparse.[4] The sparser the data, the harder it is to tell real relationships from coincidences.
Two calculations show what sparse means here.
- Counting cells. Cut each feature's range into 10 bins. Two features make 102 = 100 cells, and 32,000 development rows give about 320 rows per cell. Five features make 100,000 cells, about 0.32 rows per cell, so most cells are empty. Ten features make 1010, which is ten billion cells for the same 32,000 rows. Any method that learns from nearby examples has no nearby examples in most of the space.
- Volume moves to the edge. The volume of a ball of radius r in d dimensions grows in proportion to rd. So the fraction of a unit ball's volume that lies within 1 percent of its surface is 1 - 0.99d. In 3 dimensions that is about 3 percent. In 100 dimensions it is about 63 percent. In 1,000 dimensions it is more than 99.99 percent. Almost every point is near the boundary and far from the center.
Alan Yuille's lecture notes at Johns Hopkins work through this sphere example and draw the general lesson: geometric intuitions built in three dimensions are often wrong in high dimensions.[5] The practical consequence is that learning a distribution in many dimensions takes far more data than intuition suggests.
One more symptom matters when you choose a model. For many common data distributions, as dimensions grow, a point's distance to its nearest neighbor and its distance to its farthest neighbor become similar. The nearest neighbor is then barely nearer than any other point. Methods built on distance, such as KNN, clustering and SMOTE itself, degrade first. The usual defenses are feature selection (Step 5), dimensionality reduction such as principal component analysis (PCA), which returns with unsupervised learning later in the course, regularization (Step 6) and more data.
The curse is a practical argument for keeping models small. Occam's razor is the principle behind it. Google's crash course traces the preference for simplicity to a fourteenth-century friar, William of Occam, and calls it an underlying principle of machine learning.[4] In ML, the principle, also called the law of parsimony, works as a tie-breaker. When two models perform about equally well out of sample, prefer the one with fewer features, fewer parameters or a simpler form. The preference has reasons behind it. A simpler model has fewer ways to fit noise, costs less to run, breaks in fewer ways in production and is easier to explain.
The razor does not say the simplest model is right. The too-simple model in Step 8 underfits. The comparison must be made on out-of-sample evidence. A common working version is the one-standard-error rule: find the best cross-validated score, then choose the simplest model whose score is within one standard error of it. The information criteria from Lesson 2, the Akaike information criterion and the Bayesian information criterion (AIC and BIC), build the same preference into a formula by adding a penalty for each parameter.
Remember: each added feature multiplies the space the data must fill, so the data thin out quickly and distance-based methods degrade first. Occam's razor prefers the simpler of two models only when their out-of-sample performance is about equal.
Step 5: Select variables with a correlation matrix, VIF and feature importance
Feature selection, which the objective also calls variable selection, means choosing a subset of the available columns to train on. It reduces dimensionality, cuts training time and leaves fewer things that can break in production. Selection tools fall into three families. The scikit-learn library offers examples of each.
| Family | How it decides | scikit-learn examples | Cost and caveat |
|---|---|---|---|
| Filter | Scores each feature without using the final model | VarianceThreshold; SelectKBest with f_classif or mutual_info_classif | Fast, but misses features that only matter in combination |
| Wrapper | Fits the model repeatedly on different subsets | RFE (recursive feature elimination); SequentialFeatureSelector | Expensive, and the selection itself can overfit the folds |
| Embedded | Selection happens during fitting | LASSO coefficients or tree importances, applied through SelectFromModel | One fit, but it inherits the model's biases |
A few details matter in exam scenarios. VarianceThreshold drops columns whose variance falls below a threshold you set; a column with the same value in every row has zero variance and carries no information. An F-test score measures only linear dependence between a feature and the target. Mutual information can capture any kind of dependence, but because it is estimated without assuming a distribution, it needs more rows to estimate well. Wrapper methods are costly. A backward sequential search going from m features to m - 1 tries removing each of the m features and scores each attempt with k-fold cross-validation, so one step costs m × k fits. With 85 features and 5 folds, the first step alone is 425 fits.
Feature importance is any score of how much a model relies on each feature. Two kinds dominate practice. Impurity-based importance, also called mean decrease in impurity, adds up how much each feature's splits reduced impurity across a tree ensemble. It comes free once the model is fitted, but scikit-learn's documentation discusses the caveats of using it as a proxy for a feature's real usefulness.[6] The best-known caveats are that it is computed on training data and that it favors features with many distinct values, such as IDs and continuous amounts. Permutation importance takes a different approach: it shuffles one column in held-out data and measures how much the score drops. It is slower, but it reflects how much the model relies on the feature out of sample. Both kinds share one trap. When two features are strongly correlated, the model can use either one, so each looks less important than the pair really is.
That trap has a name. Multicollinearity means that one predictor can be predicted well from the others. It does not necessarily hurt predictions, but it makes coefficient estimates unstable. Their standard errors grow, signs can flip when a related feature is added or removed, and a single coefficient stops meaning what it appears to mean. That is a real problem for an interpretable model, such as a claims model whose coefficients an auditor will read.
The first tool for spotting it is a correlation matrix, the table of pairwise correlations between features. Here is one for five candidate features, with fictional values.
| Feature | claim_amount | repair_estimate | vehicle_value | policy_tenure | prior_claims_3y |
|---|---|---|---|---|---|
| claim_amount | 1.00 | 0.94 | 0.61 | -0.05 | 0.12 |
| repair_estimate | 0.94 | 1.00 | 0.58 | -0.04 | 0.10 |
| vehicle_value | 0.61 | 0.58 | 1.00 | 0.03 | 0.02 |
| policy_tenure | -0.05 | -0.04 | 0.03 | 1.00 | 0.22 |
| prior_claims_3y | 0.12 | 0.10 | 0.02 | 0.22 | 1.00 |
The 0.94 between claim_amount and repair_estimate stands out. That makes sense, because most of the claim is the repair. But a correlation matrix only shows pairs. Suppose total_payout equals medical plus property plus rental. Each pairwise correlation might look moderate, yet the other three together determine total_payout exactly. Catching that takes a second tool.
The variance inflation factor (VIF) works one feature at a time. For feature j, regress that feature on all the other predictors and record the R2 of that auxiliary regression, written Rj2. Then VIFj = 1 / (1 - Rj2). The name says what it measures. VIF is the factor by which the variance of feature j's coefficient grows, compared with what it would be if j were uncorrelated with the other predictors. Its square root is the factor by which the standard error grows.
- Rj2 = 0.20 gives VIF = 1 / 0.80 = 1.25. This is mild.
- Rj2 = 0.75 gives VIF = 1 / 0.25 = 4. The standard error doubles, since √4 = 2.
- Rj2 = 0.90 gives VIF = 1 / 0.10 = 10. The standard error is about 3.16 times larger.
- For total_payout in the example above, Rj2 = 1 and VIF is infinite. OLS cannot find unique coefficients at all.
You can check one entry from the matrix by hand. Regress vehicle_value on just claim_amount and repair_estimate. With correlations of 0.61 and 0.58 to those two, and 0.94 between them, the auxiliary R2 is (0.612 + 0.582 - 2 × 0.94 × 0.61 × 0.58) / (1 - 0.942) = 0.0434 / 0.1164 ≈ 0.37. The two remaining features add almost nothing, so VIF ≈ 1 / 0.63 ≈ 1.6. Software computes every VIF at once from the same matrix. Here is the full report, rounded.
| Feature | Rj2 | VIF | Reading |
|---|---|---|---|
| claim_amount | 0.89 | 9.1 | Near the serious threshold; tied up with repair_estimate |
| repair_estimate | 0.884 | 8.6 | The other half of the same pair |
| vehicle_value | 0.37 | 1.6 | Acceptable |
| policy_tenure | 0.06 | 1.1 | Acceptable |
| prior_claims_3y | 0.07 | 1.1 | Acceptable |
Common rules of thumb treat a VIF above 5 as worth a look and above 10 as serious. These are conventions, not statistical tests, so read them in light of what the model is for. Neither collinear feature here crosses 10, but both sit well above 5, and an auditor reading their coefficients would be misled.
Here are the remedies, roughly in order of preference. You can drop one feature of the pair. Keep the one that is available when the prediction is made: the repair estimate arrives with the first notice of loss, but the final claim amount does not. You can combine the pair into one feature, such as a ratio. You can use ridge regression (Step 6), which tolerates correlated features by sharing weight between them. Or you can replace the pair with principal components, at some cost in interpretability.
Step 6: Regularize with L1 and L2 penalties
Regularization means changing the training objective so that complexity has a cost. Google's crash course describes one form of it as penalizing complex models, which forces them to become simpler during training.[4] Written out, the objective becomes: minimize loss + λ × complexity. The Greek letter λ (lambda) is the regularization rate. At λ = 0 you are back to minimizing loss alone. As λ grows, simplicity carries more weight in the objective.
For a linear model with weights w1 to wn, there are two standard ways to measure complexity.
| Penalty | Complexity term | Name in regression | Effect on weights |
|---|---|---|---|
| L2 | w12 + ... + wn2 | Ridge regression | Shrinks all weights toward zero; none reaches exactly zero |
| L1 | |w1| + ... + |wn| | LASSO (least absolute shrinkage and selection operator) | Shrinks weights and sets some exactly to zero, which selects features |
| L1 and L2 mixed by a ratio | A weighted sum of the two terms | Elastic net | Selects features while sharing weight among correlated ones |
Google's course works an L2 example with six weights, which shows how unevenly that penalty falls. The table adds an L1 column for comparison.
| Weight | Value | Squared (L2) | Absolute (L1) |
|---|---|---|---|
| w1 | 0.2 | 0.04 | 0.2 |
| w2 | -0.5 | 0.25 | 0.5 |
| w3 | 5.0 | 25.0 | 5.0 |
| w4 | -1.2 | 1.44 | 1.2 |
| w5 | 0.3 | 0.09 | 0.3 |
| w6 | -0.1 | 0.01 | 0.1 |
| Total | 26.83 | 7.3 |
The L2 total is 26.83, and the single weight w3 contributes about 93 percent of it.[7] Under L1, the same weight contributes 5.0 of 7.3, about 68 percent. Squaring makes L2 focus heavily on large weights and almost ignore small ones.
That difference explains the most-tested fact about the two penalties, and the mechanism lies in the gradients, the slopes the optimizer follows. The slope of λw2 is 2λw, so the L2 push toward zero is proportional to the weight. A weight of 0.01 gets a push one five-hundredth the size of the push on a weight of 5.0, and the push fades as the weight approaches zero. Google's course states the result: L2 drives weights toward zero but never all the way to zero.[7] The slope of λ|w| is λ times the sign of w. That is a constant push, however small the weight is. If a weight helps the loss less than that push hurts, the optimizer drives it to exactly zero. That is why LASSO doubles as a feature selector and ridge regression does not.
Two practical rules follow. First, standardize features before regularizing. The penalty applies to raw weights. A feature measured in dollars needs a far smaller weight than the same information measured in thousands of dollars, so without scaling, the penalty punishes features for their units. Second, choose λ on validation data, never on training error. Yuille's notes say λ is optimized using cross-validation.[5] Training error always prefers λ = 0.
Watch the parameter names in libraries. In scikit-learn, Ridge and Lasso call the strength alpha, and a larger alpha means more regularization. LogisticRegression and the support vector classes use C, which is the inverse of regularization strength, so a smaller C means a stronger penalty. If a scenario says a team raised C to fix overfitting, the team actually weakened the penalty and made things worse.
Regularization is broader than L1 and L2. Limiting tree depth, or requiring a minimum number of rows per leaf, regularizes trees. Early stopping ends training when validation loss stops improving. Dropout, a neural-network technique that returns with deep learning later in the course, randomly switches off units during training. All of them give up a little in-sample fit to get better out-of-sample behavior.
Remember: regularization minimizes loss plus λ times complexity. L2 (ridge) shrinks every weight but sets none to zero. L1 (LASSO) sets some weights to zero and so selects features. Standardize features first, and choose λ by cross-validation.
Step 7: Tune hyperparameters with k-fold cross-validation
A parameter is learned from data during fitting, such as a regression weight or a split threshold. A hyperparameter is set before fitting and controls how the learning happens. Examples include λ or C, tree depth, the number of neighbors k in KNN, the SMOTE neighbor count and the downsampling factor. Hyperparameter tuning is the search for the values that perform best out of sample. You cannot tune on the test set, because that would make it in sample. A single validation split wastes data and gives a noisy answer. Cross-validation solves both problems.
In k-fold cross-validation, you cut the development set into k equal folds and fit the model k times. Each time, one fold is held out for validation and the other k - 1 folds are used for training. The cross-validated score is the average of the k validation scores. Every row is used for validation exactly once and for training k - 1 times. The price is k fits instead of one; the gain is that no row is permanently set aside just to validate.
For the claims development set of 32,000 rows with k = 5, each fit trains on 25,600 rows and validates on 6,400. Here is the output for one candidate setting, with fictional values. The score is average precision, because accuracy is useless at 1.5 percent fraud.
| Fold | Training rows | Validation rows | Fraud cases in validation | Average precision |
|---|---|---|---|---|
| 1 | 25,600 | 6,400 | 96 | 0.54 |
| 2 | 25,600 | 6,400 | 96 | 0.49 |
| 3 | 25,600 | 6,400 | 96 | 0.55 |
| 4 | 25,600 | 6,400 | 96 | 0.51 |
| 5 | 25,600 | 6,400 | 96 | 0.51 |
| Mean | 0.52 |
The mean is 0.52, and the fold scores range from 0.49 to 0.55. That spread matters. With these folds, you cannot tell apart two candidates whose means differ by 0.01.
Plain k-fold assumes the rows are interchangeable. Three variants handle data where they are not.
- Stratified k-fold keeps the class proportions in each fold about the same as in the whole set.[8] With 480 frauds and 5 folds, each validation fold gets about 96, instead of a random count that might be 70 in one fold and 120 in another. It is the default choice for imbalanced classification. One side effect: because every fold gets the same share of rare cases, the spread of scores across folds can understate the real uncertainty.
- Group k-fold makes sure the same group never appears in both the training and validation parts of a split.[8] If a claimant files several claims, all of them go in one fold. Otherwise the model can memorize the person and look brilliant on that person's other claims.
- Time-series splits train on earlier rows and validate on later ones. The reason is autocorrelation: observations close together in time are correlated with each other.[8] Shuffled k-fold would put near-duplicates on both sides of the split and overstate performance. scikit-learn's TimeSeriesSplit moves the training window forward and always validates on the future.
At the extreme, leave-one-out cross-validation sets k equal to the number of rows. It wastes almost no data but needs one fit per row, so it suits small datasets.
Cross-validation tells you how good one setting is. The search strategy decides which settings to try.
| Question | Grid search | Random search |
|---|---|---|
| What it tries | Every combination of the listed values | A fixed number of configurations drawn from distributions you specify |
| Budget | The product of the list sizes, multiplied again by each new hyperparameter | Set directly (n_iter in scikit-learn) |
| Values tried for one important hyperparameter | Only the values on the grid | A new value on every draw |
| Best when | Few hyperparameters, each with a small set of meaningful values | Many hyperparameters, only a few of which matter |
| scikit-learn class | GridSearchCV | RandomizedSearchCV |
Work through the budget. Suppose you tune C over {0.001, 0.01, 0.1, 1} and class_weight over {none, balanced}. The grid has 4 × 2 = 8 configurations, and with 5 folds that is 40 fits. Now suppose only C really matters. The grid has spent 40 fits testing just 4 distinct values of C. Eight random draws cost the same 40 fits. If C is drawn log-uniformly between 0.001 and 100, they test 8 distinct values of C spread across five orders of magnitude. Add a third hyperparameter with 5 values, and the grid jumps to 40 configurations and 200 fits, while random search stays at whatever budget you set. Log-uniform sampling matters for scale-type settings like C and λ, because the step from 0.001 to 0.01 matters as much as the step from 10 to 100.
In scikit-learn, the whole step fits in a few lines. The sketch uses a pipeline: an object that chains preprocessing steps and a final model, so that when the pipeline is fitted, every step learns only from the data passed to it. Inside cross-validation, that means the scaler learns from the training folds alone. The sketch was written for this lesson, so check the parameter names against the documentation for your installed version.
from scipy.stats import loguniform
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, RandomizedSearchCV
pipe = Pipeline([
('scale', StandardScaler()),
('clf', LogisticRegression(max_iter=5000)),
])
space = {
'clf__C': loguniform(1e-3, 1e2),
'clf__class_weight': [None, 'balanced'],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = RandomizedSearchCV(pipe, space, n_iter=8, cv=cv,
scoring='average_precision', random_state=0)
search.fit(X_dev, y_dev)
print(search.best_params_, round(search.best_score_, 3))
The integer random_state on the splitter is deliberate. A fixed integer seed makes the splitter produce the same folds every time it is called, so two searches score their candidates on identical folds and can be compared fold by fold.
One more trap remains. The best of eight noisy cross-validated scores is biased upward, because you picked it partly for being lucky on these folds. search.best_score_ is therefore an optimistic estimate of the tuned model. There are two honest fixes. Nested cross-validation wraps the whole search in an outer loop: it tunes on the inner folds and scores on the outer fold. Alternatively, as in this project, the untouched test set scores the final choice once.
In short: k-fold cross-validation averages k validation scores, so every row is used for validation once. Stratify for imbalance, group by repeated entities and split forward in time for temporal data. Grid search tries every combination. Random search spends a fixed budget and tries more values of the hyperparameters that matter.
Step 8: Diagnose bias, variance, overfitting and underfitting
Now read the scores. For squared loss, a model's expected error at an input x splits into three parts. Stanford's CS229 notes write it as average squared error = σ2 + bias2 + variance.[9] Each term has a precise meaning.
- Irreducible error, written σ2 and often called noise, is the randomness in the data itself: two identical claims can still turn out differently. No model can remove it, because it belongs to the data, not to the model.
- Bias is the error that remains even with unlimited training data, because the model family cannot represent the true pattern. A straight line fitted to a curved relationship has high bias.
- Variance, in this sense, measures how much the fitted model changes when it is trained on a different training set.[2] A deep tree that rebuilds itself around every quirk of its sample has high variance.
The bias-variance tradeoff is the fact that the same change usually lowers one of these and raises the other. More flexible models reduce bias and increase variance. As complexity rises, training error keeps falling, but validation error first falls and then rises, tracing a U-shape.
Overfitting is the high-variance failure. The model fits the noise in its training sample, so it performs far better in sample than out of sample. Underfitting is the high-bias failure. The model is too rigid to capture the signal, so it does badly on both, and the two scores sit close together. The gap between the training and validation scores is your main diagnostic. Here are four candidates for the claims model, with fictional average precision (AP) scores on the training folds and in cross-validation (CV), where higher is better.
| Candidate | Training AP | CV AP | Gap | Diagnosis |
|---|---|---|---|---|
| Logistic regression, C = 0.001 | 0.31 | 0.30 | 0.01 | Underfitting: the penalty is so strong the model is nearly constant |
| Logistic regression, C = 1 | 0.55 | 0.52 | 0.03 | Reasonable fit |
| Gradient-boosted trees, depth 12, no early stopping | 0.99 | 0.41 | 0.58 | Overfitting: memorized the training folds |
| Gradient-boosted trees, depth 4, early stopping | 0.63 | 0.57 | 0.06 | Best out-of-sample score, with a modest gap |
The remedies follow from the diagnosis, and they point in opposite directions, which is why you diagnose first. For high variance, Cornell's notes list adding training data, reducing model complexity and bagging.[2] Bagging trains many copies of a model on bootstrap resamples of the data and averages their predictions, which cancels out much of each copy's variance. For high bias, the remedies run the other way: a more complex model, more features, or boosting, which fits models in sequence, each one to the errors the earlier ones left. Regularization is the dial between the two. Raising λ (or lowering C) moves a model toward bias. Lowering λ moves it toward variance. Ensembles themselves are covered in Lesson 13.
A learning curve plots training and validation error against the number of training rows, and it separates the two cases further. Under high variance, the curves start far apart and move together as rows are added, so more data helps. Under high bias, both curves flatten early at a poor level and stay close together. More data of the same kind does almost nothing; only a more expressive model or better features help.
The chosen model, the depth-4 boosted trees, now gets its single score on the 8,000-row test set. Suppose it returns 0.55. That is close to its CV score of 0.57, which is what an honest procedure should produce. The closeness is your evidence that the procedure worked.
Remember: expected squared error = noise + bias2 + variance. A large gap between training and validation scores signals overfitting (high variance), so simplify, regularize, add data or use bagging. Two poor scores close together signal underfitting (high bias), so add flexibility or features, or use boosting.
Second run: move one step and the verdict flips
Data leakage happens when information reaches the model during training that will not be available when it makes real predictions, or that comes from the data used to evaluate it. Leakage does not make a model look worse in development. It makes it look better, which is why it gets past review.
Rerun the procedure with one change. A colleague who is short on time resamples and selects features on the full dataset first, then cross-validates.
# Leaky order (fictional notebook)
X_res, y_res = SMOTE(random_state=0).fit_resample(X, y) # all 40,000 rows
X_sel = SelectKBest(f_classif, k=25).fit_transform(X_res, y_res)
scores = cross_val_score(model, X_sel, y_res, cv=5,
scoring='average_precision')
Compare the two runs, with fictional values.
| Version | Where SMOTE and feature selection run | CV average precision | Later score on next month's claims |
|---|---|---|---|
| First run | Inside each training fold | 0.57 | 0.55 |
| Second run | On all rows, before any split | 0.88 | 0.43 |
Two leaks are at work.
- Resampling before splitting. SMOTE built synthetic frauds by interpolating between real frauds. Many synthetic rows were made from a fraud that later landed in a validation fold, and the synthetic rows themselves landed in training folds. So the model trained on near-copies of the rows it was then tested on. The validation folds also contained synthetic frauds, so they no longer reflected the real 1.5 percent fraud rate.
- Selecting features with evaluation labels. SelectKBest chose the 25 features most associated with the label using every row, including the rows later used for validation. scikit-learn's documentation demonstrates this leak with 10,000 randomly generated features that carry no signal. Selecting 25 of them on all the data before splitting gives an accuracy much higher than expected, and redoing the same steps inside a pipeline gives 0.5, the chance level for its two-class problem. Its warning is direct: including test data in feature selection will optimistically bias the model.[10]
The same danger applies to almost every preprocessing step that learns from data, including scaling, imputation and PCA. The rule is to fit any transformation on the training portion only and then apply it to the held-out portion. In scikit-learn, that means fit_transform on the training subset and transform on the test subset. A pipeline does this automatically inside every fold, and scikit-learn describes the pipeline as a great way to prevent data leakage.[10] For resampling, the imbalanced-learn library supplies a pipeline that applies SMOTE only during fitting, so validation folds are never resampled.
Pipelines cannot catch the other big family of leaks. Target leakage is a feature that encodes the outcome because it is recorded after the outcome is known. Suppose the claims table contains siu_referral, a flag set when an adjuster refers a claim to the special investigations unit. It tops the feature-importance chart and pushes the test score close to perfect. But the flag is set because someone already suspects fraud. At first notice of loss, when the model must score the claim, it is always zero. The fix is to build every feature as of the moment of prediction. Treat any single feature with near-perfect predictive power as a suspect until you have checked when it is recorded.
Leakage can also come from the split itself. Shuffled k-fold on time-ordered data lets the model learn from the future. Random splits that scatter one claimant's claims across folds let it learn the person. Time-series splits and group k-fold from Step 7 exist to prevent exactly these problems.
| Leak type | Example | Prevention |
|---|---|---|
| Train-test contamination in preprocessing | Scaler, imputer or SelectKBest fitted on all rows | Fit inside a pipeline, on each training fold only |
| Resampling leakage | SMOTE run before the split | Resample training folds only (imbalanced-learn pipeline) |
| Target leakage | siu_referral; final settlement amount | Build features as of prediction time; audit timestamps |
| Group leakage | One claimant's claims in both training and validation | Group k-fold by claimant |
| Temporal leakage | Random folds on claims from 2022-2025 | Time-series splits; an out-of-time test set |
| Test-set reuse | Tuning against the test score | Use the test set once; use nested CV for estimates |
Remember: leakage inflates development scores instead of lowering them. Anything learned from data, whether scaling, imputation, feature selection or SMOTE, must be fitted on the training fold only. Target leakage needs a timestamp audit, because no pipeline can detect it.
Exam cues: words in the stem and where they point
| The stem says | It points to |
|---|---|
| Training error far below validation error | Overfitting (high variance): simplify, regularize, add data |
| Training and validation error both high and close together | Underfitting (high bias): use a more flexible model or more features |
| Score on the same data the model was fitted to | In-sample (training) error, which is optimistic |
| Validation score fell sharply once preprocessing moved into a pipeline | The earlier score was inflated by data leakage |
| A feature recorded after the outcome, with near-perfect importance | Target leakage |
| Every fold keeps the same class proportions | Stratified k-fold |
| The same patient, customer or claimant must not appear on both sides of a split | Group k-fold |
| Try every combination of the listed values | Grid search |
| Fixed budget of draws from distributions; many hyperparameters | Random search |
| Duplicate minority rows | Random oversampling of the minority class |
| Discard majority rows | Random undersampling of the majority class |
| Synthetic minority rows between nearest neighbors | SMOTE |
| Pairwise correlations between predictors | Correlation matrix (cannot catch a three-way dependence) |
| Coefficients flip sign when a related feature is added; VIF above 10 | Multicollinearity |
| Some coefficients exactly zero | L1 penalty (LASSO) |
| All coefficients shrink, none reach zero | L2 penalty (ridge) |
| Predict for an input beyond the training range | Extrapolation |
| Estimate between observed values | Interpolation |
| Adding features made nearest-neighbor results worse with the same rows | Curse of dimensionality |
| Prefer the simpler model when validation performance is about equal | Occam's razor, the law of parsimony |
Common misconceptions
- Cross-validation prevents overfitting. It measures out-of-sample performance, so it detects overfitting, but it does not stop it. Searching hundreds of settings on the same folds can even overfit the folds. That is why nested CV or an untouched test set gives the final estimate.
- High accuracy means a good classifier. At 1.5 percent fraud, predicting honest every time scores 98.5 percent. On imbalanced data, use precision, recall, average precision or MCC.
- Resampling before the split is harmless because it only adds or removes rows. Resampled data that reaches the validation folds leaks near-copies of the validation rows and distorts the class ratio. Resample inside each training fold.
- Multicollinearity ruins predictions. It mainly makes coefficient estimates unstable and inflates their variance. Predictive accuracy on similar data can be fine. It matters most when someone will interpret the coefficients.
- L2 regularization removes useless features. L2 shrinks weights but never to exactly zero. L1 (LASSO) or elastic net is what sets weights to zero.
- Out of sample means extrapolation. A held-out row inside the training range is interpolation. Extrapolation means predicting beyond the range the training data covered.
Recap
- Training minimizes the average of the loss function. Squared error targets the conditional mean, and minimizing it minimizes residual variance. Absolute error targets the median. Log loss punishes confident wrong probabilities.
- In-sample (training) error is optimistic. Only out-of-sample error estimates performance on new data, and a test set stays out of sample only while it is untouched.
- Interpolation predicts within the training range. Extrapolation predicts beyond it, where tree ensembles go flat and polynomials can swing wildly.
- Random oversampling duplicates minority rows, and undersampling discards majority rows. SMOTE creates xnew = xi + u(xnn - xi) between minority neighbors. All resampling happens on training folds only, and only downsampling with matching upweighting keeps the true class ratio in the loss.
- VIFj = 1 / (1 - Rj2), so Rj2 = 0.90 gives a VIF of 10, a common threshold for serious multicollinearity. A pairwise correlation matrix can miss dependence among three or more features.
- Regularization minimizes loss plus λ times complexity. L2 (ridge) shrinks all weights without zeroing any, and L1 (LASSO) zeroes some. Tune λ by cross-validation, on standardized features.
- k-fold CV averages k validation scores. Stratified folds keep class ratios, group k-fold keeps each entity in one fold, and time-series splits always validate on the future. Random search covers important hyperparameters better than a grid on the same budget.
- Expected squared error = noise + bias2 + variance. A large gap between training and validation scores means overfitting (high variance). Two poor scores close together mean underfitting (high bias).
- The curse of dimensionality makes data sparse as features are added, and distance-based methods suffer first. Occam's razor prefers the simpler model when out-of-sample performance is about equal.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Cornell University, Department of Computer Science. (2022). Bias-Variance Tradeoff (CS4780 Lecture Notes). cs.cornell.edu
- Google for Developers (Machine Learning Crash Course). (n.d.). Datasets: Class-imbalanced datasets. developers.google.com
- Google for Developers (Machine Learning Crash Course). (n.d.). Overfitting: Model complexity. developers.google.com
- Alan Yuille. (2014). Lecture Note 3 (Stat 161/261): Curse of Dimensionality and Bias-Variance. Johns Hopkins University. cs.jhu.edu
- scikit-learn developers. (n.d.). 1.13. Feature selection. scikit-learn.org
- Google for Developers (Machine Learning Crash Course). (n.d.). Overfitting: L2 regularization. developers.google.com
- scikit-learn developers. (n.d.). 3.1. Cross-validation: evaluating estimator performance. scikit-learn.org
- Stanford University. (2022). Bias-Variance (CS229 notes). cs229.stanford.edu
- scikit-learn developers. (n.d.). Common pitfalls and recommended practices (data leakage). scikit-learn.org
- Key terms
- Loss function
- A function that scores one prediction against the true value. It returns zero for a perfect prediction and larger values for worse ones, and training searches for the parameters that minimize its average over the training data.
- Out-of-sample error
- Error measured on data the model never saw while its parameters, features or settings were chosen. Unlike in-sample (training) error, it estimates how the model will perform on new data.
- Extrapolation
- Predicting for inputs outside the range covered by the training data. It contrasts with interpolation, which predicts between values the model has seen.
- SMOTE
- Synthetic minority oversampling technique. It creates new minority-class rows by interpolating between a minority row and one of its nearest minority neighbors, and it should be applied to training data only.
- Variance inflation factor (VIF)
- For predictor j, VIF = 1 / (1 - R-squared), where R-squared comes from regressing j on all the other predictors. Values above about 5 to 10 signal problematic multicollinearity.
- Regularization
- Adding a penalty on model complexity to the training objective, scaled by a rate lambda. L2 (ridge) shrinks weights toward zero, and L1 (LASSO) can set some weights exactly to zero.
- k-fold cross-validation
- Splitting data into k folds, training k times on k - 1 folds while validating on the remaining fold, then averaging the k scores to estimate out-of-sample performance.
- Bias-variance tradeoff
- Expected squared error splits into irreducible noise, squared bias and variance, and more flexible models tend to lower bias while raising variance.
- Data leakage
- Information reaching a model during training that will not be available at prediction time, or that comes from the evaluation data. It inflates development scores.
- Curse of dimensionality
- The problems that arise as features are added: the space grows so fast that a fixed amount of data becomes sparse, and distances between points lose contrast.
Choosing and Explaining Models: Regressors, Classifiers, Ensembles and Drift
- Match a business question to a regressor, a binary or multiclass classifier, an ensemble or a recommender system by the shape of the output it must produce.
- Explain how bagging, boosting, voting, stacking, similarity-based and ALS collaborative filtering, and embeddings work, including why the cold start problem defeats collaborative filtering.
- Choose between an interpretable model and post hoc global or local explanations for a stated audience and question.
- Distinguish data drift, concept drift and training-serving skew from monitoring evidence, and choose a fitting response.
Six questions on Larkspur's whiteboard
Larkspur Books is a fictional online bookshop that this lesson follows from start to finish. It sells 40,000 titles to 210,000 customers, and on a Monday morning its data team has six questions on the whiteboard. How many copies of each title will sell next week? Is this order fraudulent? Which of nine shelf categories does a newly listed title belong in? Which five books should appear on a customer's home page? Why was customer 88213's order held for review? And why has the churn model, which predicts who will stop buying, been wrong since July?
Each question needs a different tool. The quickest way to choose is to look at the shape of the answer the business wants. A number calls for a regressor. One label from a fixed set calls for a classifier. A ranked list of items for each person calls for a recommender system. A reason calls for an interpretable model or an explanation method. A model that used to work and has stopped working calls for a drift diagnosis. DataX scenario questions are built the same way: a few sentences of business context, and you pick the approach whose output matches.
Exam objectives: DY0-001 objective 3.1, Given a scenario, apply foundational machine-learning concepts. This lesson covers the objective's regressors, classifiers, ensemble models, recommender systems, embeddings, interpretable models, post hoc model explainability and model drift causes. Lesson 12 covered its loss, regularization, validation, feature selection, leakage and class imbalance bullets.[1]
| Question | Shape of the answer | Approach | Typical measure |
|---|---|---|---|
| Copies sold next week | A number | Regressor | Root mean square error (RMSE) |
| Is this order fraud? | Yes or no | Binary classifier plus a threshold | Precision, recall, area under the receiver operating characteristic curve (ROC-AUC) |
| Which of nine shelves? | Exactly one label of nine | Multiclass (multinomial) classifier | Accuracy, macro F1 (the F1 score averaged over classes), confusion matrix |
| Five books for this customer | A ranked list of items per person | Recommender system | Precision at k, hit rate |
| Why was order 88213 held? | Reasons for one prediction | Local explanation, or an interpretable model | Fidelity to the model |
| Why is the churn model wrong? | A diagnosis over time | Drift monitoring: data drift versus concept drift | Distribution distance, performance over time |
In short: read the output first. A number, a label, a ranked list, a reason or a diagnosis each points to a different family of methods, and most scenario questions are decided at that step.
Regressors: when the answer is a number
A regressor is any model whose output is a continuous number: copies sold, delivery hours, house price, temperature. The family is wide. Linear regression fitted by Ordinary least squares (OLS) chooses the coefficients that minimize the residual sum of squares (RSS), the total of the squared gaps between actual and predicted values. A decision tree regressor splits the data into regions and predicts the average target in each region. A k-nearest neighbors (KNN) regressor averages the targets of the k most similar training rows. Random forests, gradient boosting and neural networks all have regression versions too. What makes a model a regressor is its target, not its algorithm.
Worked example, with fictional numbers. Larkspur fits a linear model for weekly copies sold:
copies_hat = 120 + 0.8 * preorders + 35 * featured
Here preorders is the number of preorders, and featured is 1 if the title is on the home page banner and 0 if not. A featured title with 200 preorders gets 120 + 0.8 × 200 + 35 × 1 = 120 + 160 + 35 = 315 copies. To judge the model, compare its predictions with what happened over three weeks.
| Week | Actual copies | Predicted copies | Error (actual minus predicted) | Squared error |
|---|---|---|---|---|
| 1 | 300 | 315 | -15 | 225 |
| 2 | 280 | 270 | 10 | 100 |
| 3 | 350 | 330 | 20 | 400 |
The mean squared error is (225 + 100 + 400) / 3 = 241.7. The root mean square error (RMSE) is its square root, about 15.5 copies. RMSE is in the target's own units, which is why managers find it easier to read than the mean squared error. Squaring punishes large misses more than small ones: the single 20-copy miss contributes 400, more than the other two weeks combined (325).
Now change one input. A celebrity memoir arrives with 5,000 preorders, and the largest number in the training data was 900. The linear model predicts 120 + 4,000 + 35 = 4,155 copies, extending its straight line far beyond any data it has seen. A tree-based regressor does the opposite. It can only return averages of the leaf values it learned, so its forecast is capped near the best seller in its training set. Neither answer deserves trust. This is extrapolation, which means predicting outside the range of the training data, and model families fail there in different ways: linear models extend a trend that may not hold, and tree models cannot extrapolate at all. Interpolation, predicting inside the range the model has seen, is where both are on safer ground.
Two naming traps are worth clearing now. Logistic regression is a classifier, despite its name. It models the log-odds of a class as a linear function and outputs a probability between 0 and 1. And a count target, such as copies sold, is still a regression problem. Poisson regression is the classic choice when counts are small and their variance grows with their mean, partly because it can never predict a negative count.
Classifiers: binary, multiclass and the softmax function
A classifier predicts a category. A binary classifier chooses between two classes, such as fraud and not fraud. A multiclass classifier, which the exam also calls multinomial, chooses exactly one class from three or more, such as Larkspur's nine shelves. Most classifiers produce a score or a probability first and a label second. Many exam questions about classifiers turn on that two-step structure.
In the binary case, a linear classifier computes a score z = b0 + b1x1 + ... + bpxp, where each x is a feature and each b a learned coefficient. It passes z through the sigmoid function, σ(z) = 1 / (1 + e-z), which squeezes any real number into the range 0 to 1. One set of coefficients is enough, because the probability of the second class is 1 minus the first.
Worked example, fictional. Larkspur's fraud model gives order 5512 a score of z = 0.8. Then σ(0.8) = 1 / (1 + e-0.8) = 1 / (1 + 0.449) = 0.690. With the default threshold of 0.5, the order is flagged. Now change one input: the fraud team reports that manual reviews are expensive and most flags at this level are false alarms, so it raises the threshold to 0.75. The model is the same and so is the probability, but 0.690 is below 0.75, so the order now passes. The threshold is a business decision layered on top of the model, which is why Lesson 2 used ROC curves to see every threshold at once.
With three or more classes, a multinomial model computes one score per class and converts the scores with the Softmax function. The probability of class k is ezk divided by the sum of ezj over all classes j. Every output is positive, and the outputs sum to 1. scikit-learn documents that for a multiclass or multinomial problem its probability estimates come from the softmax function.[2] Suppose a new title scores Mystery 2.0, Romance 1.0 and Cookbook 0.1. We keep three classes so the arithmetic stays visible.
| Class | Score z | ez | Probability |
|---|---|---|---|
| Mystery | 2.0 | 7.389 | 7.389 / 11.212 = 0.659 |
| Romance | 1.0 | 2.718 | 2.718 / 11.212 = 0.242 |
| Cookbook | 0.1 | 1.105 | 1.105 / 11.212 = 0.099 |
| Total | 11.212 | 1.000 |
The predicted shelf is Mystery, with probability 0.66. Softmax preserves order, so the largest score always wins, but it stretches gaps. A score difference of 1.0 between Mystery and Romance became a probability ratio of e1, about 2.7 to 1.
There is a second route to multiclass. One-vs-rest (OvR) trains one binary classifier per class (Mystery versus everything else, Romance versus everything else, and so on) and picks the class whose classifier is most confident. Some algorithms are binary at heart and need this wrapper. In scikit-learn, the liblinear solver handles only binary problems and is extended to multiclass with OneVsRestClassifier; the other solvers fit the multinomial loss directly when there are three or more classes.[2] A third variant, one-vs-one, trains a classifier for every pair of classes and takes a vote. Support vector machines (SVM) often use it.
Do not confuse multiclass with multilabel. A title can be tagged both Historical and Mystery. That is a multilabel problem: each tag is its own yes-or-no question, so the model uses an independent sigmoid per tag, and the probabilities need not sum to 1. Softmax would force the tags to compete, which is wrong when they can coexist.
| Problem type | Larkspur example | Output layer | Usual training loss | Probabilities sum to 1? |
|---|---|---|---|---|
| Binary | Fraud or not | One sigmoid | Binary cross-entropy (log loss) | Yes, across the two classes |
| Multiclass (multinomial) | Exactly one of nine shelves | Softmax over K scores | Categorical cross-entropy | Yes |
| Multilabel | Any set of genre tags | One sigmoid per label | Sum of binary cross-entropies | No |
In short: a classifier is a probability model plus a threshold or an argmax (pick the highest). Use softmax when classes exclude each other and a sigmoid per label when they do not. The threshold belongs to the business, not the algorithm.
Ensemble learning: bagging, boosting, voting and stacking
An ensemble model combines the predictions of several models into one. The idea is old and the tooling is mature: scikit-learn's ensemble module, for example, ships classifier and regressor versions of each main method.
Why does combining help? Suppose you average n models. Each model's errors have variance σ2, and any two models' errors have correlation ρ (rho). The variance of the averaged prediction is:
Var(average) = ρσ² + (1 - ρ)σ² / n
Read the two terms separately. The second shrinks as you add models. The first never shrinks. With σ2 = 1 and 100 models, ρ = 0.3 gives 0.3 + 0.7 / 100 = 0.307, a 69 percent cut in variance. But ρ = 0.8 gives 0.8 + 0.2 / 100 = 0.802, barely better than one model. If every member makes the same mistakes (ρ = 1), a thousand copies are no better than one. So building an ensemble means building members that are individually decent and different from each other.
| Method | How members are built | How predictions combine | Mainly reduces | scikit-learn classes |
|---|---|---|---|---|
| Bagging (bootstrap aggregating) | Same algorithm on bootstrap samples (rows drawn with replacement), trained independently | Average for regression, vote for classification | Variance | BaggingClassifier, BaggingRegressor |
| Random forest | Bagged deep trees; each split considers only a random subset of features | Average or vote | Variance, by lowering ρ | RandomForestClassifier, RandomForestRegressor |
| Boosting | Weak learners trained in sequence, each one aimed at the errors left by the ensemble so far | Weighted sum | Bias, then variance through shrinkage | AdaBoostClassifier, GradientBoostingRegressor, HistGradientBoostingClassifier |
| Voting | Different algorithms on the same data | Majority label (hard) or averaged probabilities (soft) | Variance, when members err differently | VotingClassifier, VotingRegressor |
| Stacking | Different algorithms plus a meta-model | The meta-model learns how to weight the base models | Bias and variance | StackingClassifier, StackingRegressor |
Bootstrap aggregating, or bagging, suits models with low bias and high variance, such as deep decision trees. Each tree overfits its own bootstrap sample in its own way, and averaging cancels much of that noise while leaving the low bias intact. A Random forest adds one more trick: at each split a tree may consider only a random subset of the features. That stops every tree from splitting first on the same dominant feature, which lowers ρ in the formula above. (Extra-trees, a separate scikit-learn class, goes further and also randomizes the split thresholds.)
Gradient boosting works the other way round. It starts with a weak model, often a shallow tree, and adds trees one at a time. Each new tree is fitted to the negative gradient of the loss with respect to the current predictions. For squared-error loss that gradient is simply the residuals, so each tree learns what the ensemble still gets wrong. A learning rate scales down each tree's contribution, so many small corrections add up. AdaBoost, an earlier boosting method, instead reweights the training rows so that misclassified rows count more in the next round. Extreme Gradient Boosting (XGBoost) is a widely used gradient boosting library that adds regularization on tree complexity. Boosting can overfit if it runs too many rounds, so practitioners stop it early when a validation score stops improving.
A voting classifier combines finished models of different kinds. scikit-learn's VotingClassifier offers both soft voting and majority rule.[3] Stacked generalization, usually called stacking, goes further: it trains a final model on the base models' outputs. scikit-learn describes its StackingClassifier as a stack of estimators with a final classifier.[3] The meta-model must learn from out-of-fold predictions, made by base models that never saw those rows. If it learns from in-sample predictions, it trusts the most overfitted base model, which is the leakage problem from Lesson 12.
Worked example, fictional: hard and soft voting disagree. Three fraud models score one order, with a threshold of 0.5.
| Member | P(fraud) | Label at 0.5 |
|---|---|---|
| Gradient boosting | 0.90 | Fraud |
| Logistic regression | 0.40 | Not fraud |
| KNN | 0.45 | Not fraud |
Hard voting counts labels: one fraud, two not fraud, so the ensemble says not fraud. Soft voting averages probabilities: (0.90 + 0.40 + 0.45) / 3 = 1.75 / 3 = 0.583, which is above 0.5, so the ensemble says fraud. One confident yes outweighs two lukewarm no votes. Soft voting is usually the better choice when members output well-calibrated probabilities. When one member is badly overconfident, though, it dominates the average, and hard voting is safer.
Ensembles have costs. They are slower to train and serve, they need more memory, and a forest of 500 trees has no single readable rule. That last cost is why this lesson turns to explanation after recommenders and embeddings.
In short: bagging and random forests average many high-variance models to cut variance, and they work only when the members' errors are not strongly correlated. Boosting builds models in sequence to cut bias. Voting and stacking combine different algorithms, and stacking learns its weights from out-of-fold predictions.
Recommender systems: content-based filtering and collaborative filtering
Larkspur's home page shows five books to each customer. Search only finds what a customer already knows to type; a recommender can surface books the customer would never have thought to search for. Recommenders come in two broad families. Content-based filtering recommends items similar to ones the customer liked, judged by item attributes such as genre, author or description.[4] If you bought two cozy mysteries, you see more cozy mysteries. Collaborative filtering ignores item attributes and uses behavior across many customers instead: people who behaved like you liked this book, so you might too.
The data can be explicit, such as star ratings, or implicit, such as purchases, clicks and reading time. Most real systems run mainly on implicit feedback, because few customers rate anything. Either way, the data is a user-item matrix with a row per customer, a column per item, and most cells empty. Larkspur's full matrix has 210,000 × 40,000 = 8.4 billion cells, and a typical customer has filled perhaps a dozen.
The exam names two ways to do collaborative filtering: similarity-based and alternating least squares (ALS). We work one example of each.
Similarity-based collaborative filtering, worked
A similarity-based (also called neighborhood) method predicts a missing rating from the ratings of similar items or similar users. Here is a fictional four-customer slice of Larkspur's ratings on a 1 to 5 scale. Dee has not rated Book B. Should Larkspur recommend it?
| Customer | Book A (mystery) | Book B (mystery) | Book C (cookbook) |
|---|---|---|---|
| Ana | 5 | 4 | 1 |
| Ben | 4 | 5 | 2 |
| Chen | 1 | 2 | 5 |
| Dee | 5 | ? | 1 |
Step 1: measure how similar Book B is to the books Dee has rated, using the three customers who rated both. Item-item cosine similarity treats each book's column of ratings as a vector and computes cos(u, v) = (u · v) / (|u| |v|), the dot product divided by the product of the lengths.
- B = (4, 5, 2) and A = (5, 4, 1). The dot product is 20 + 20 + 2 = 42. |B| = √45 = 6.708 and |A| = √42 = 6.481. The similarity is 42 / 43.47 = 0.966.
- B = (4, 5, 2) and C = (1, 2, 5). The dot product is 4 + 10 + 10 = 24. |C| = √30 = 5.477. The similarity is 24 / 36.74 = 0.653.
Something is wrong. The cookbook is loved by exactly the people who dislike Book B, yet its raw similarity is 0.65. Raw cosine is inflated because every rating is positive, so all the vectors point into the same corner of the space. The standard repair is to subtract each customer's average rating first, which is called adjusted cosine. The averages are Ana 3.33, Ben 3.67 and Chen 2.67. After centering, sim(B, A) = 0.69 and sim(B, C) = -0.88. Now the cookbook correctly shows up as Book B's opposite.
Step 2: predict Dee's rating. Dee's average is (5 + 1) / 2 = 3, so her centered ratings are +2 for Book A and -2 for Book C. Take her average plus a similarity-weighted average of her centered ratings, dividing by the sum of absolute similarities:
prediction = 3 + (0.69 × 2 + (-0.88) × (-2)) / (0.69 + 0.88)
= 3 + (1.38 + 1.76) / 1.57
= 3 + 2.0 = 5.0
Both signals agree. Dee loved Book A, which resembles Book B, and disliked Book C, which is Book B's opposite. Recommend Book B. Item-item similarity is easy to explain to a customer (because you liked Book A), but it compares every item with every other, which gets expensive as the catalog grows.
Matrix factorization and alternating least squares (ALS)
Matrix factorization is the other main route. BigQuery's documentation calls it widely used as a collaborative filtering method for recommendation systems.[4] It approximates the sparse rating matrix R as the product of two smaller dense matrices: P, with one row per user, and Q, with one row per item, each row holding k latent factors. A latent factor is a learned number that nobody labels in advance. For books, one factor might end up tracking something like dark versus light tone. A predicted rating is the dot product of a user's row and an item's row: r̂ui = pu · qi.
Training minimizes squared error over the observed cells only, plus an L2 penalty (a charge on the sum of squared factor values) with strength λ (lambda) to keep factors small:
minimize sum over observed (u, i) of (r_ui - p_u · q_i)²
+ λ (sum of |p_u|² + sum of |q_i|²)
Solving for P and Q together is hard, because their product makes the problem non-convex. Alternating least squares breaks the deadlock. Hold Q fixed, and each user's row becomes an ordinary ridge regression (least squares with an L2 penalty), which has an exact closed-form solution. Then hold P fixed and solve every item's row the same way. Repeat until the error stops falling. Each user's update is independent of every other user's, so the work spreads easily across many machines, which is a large part of why ALS became popular for big catalogs. Variants for implicit feedback weight each observed interaction by a confidence level instead of treating it as a rating.
One ALS half-step, worked with k = 1 so every vector is a single number (fictional). The item factors are fixed at qA = 2.0, qB = 1.5 and qC = 0.5. A customer, Eli, rated A = 5 and B = 4, and λ = 0.25. With one factor, the ridge solution is the sum of rating × item factor over the items Eli rated, divided by the sum of those items' squared factors plus λ:
p_Eli = (5 × 2.0 + 4 × 1.5) / (2.0² + 1.5² + 0.25)
= (10 + 6) / (4 + 2.25 + 0.25)
= 16 / 6.5 = 2.46
predicted rating for C = 2.46 × 0.5 = 1.23
Change one input: raise λ to 2.0. The denominator becomes 8.25, so pEli = 1.94 and every prediction for Eli shrinks toward zero. This is Lesson 12's regularization at work: a larger λ trusts a customer's few ratings less.
The cold start problem
Collaborative filtering learns only from interactions. A customer who joined this morning has no row of ratings, so ALS has nothing to solve for, and a book listed today has no column. This is the cold start problem, and no amount of extra training fixes it, because the missing ingredient is data, not iterations.
| Cold start case | What is missing | Common remedies |
|---|---|---|
| New item | No one has bought or rated it | Content-based similarity from genre, author and description; a hybrid model that uses item features |
| New user | No history at all | Popular or trending items, onboarding questions (pick three genres), context such as the page they arrived from |
| New system | No interactions anywhere | Content-based and editorial recommendations until behavior accumulates |
Hybrid models are the lasting fix. BigQuery's documentation describes extending a collaborative filtering system with deep neural network and wide-and-deep models, and notes that these models can draw on query and item features to make recommendations more relevant.[4] The cold start benefit follows from that design rather than from the documentation: a model that reads item features such as genre and author can place a brand-new book near similar books before anyone has bought it. Recommenders are evaluated with ranking measures such as precision at k: of the top k items shown, the share the customer went on to engage with.
In short: content-based filtering uses item attributes; collaborative filtering uses behavior across users, through neighborhoods (similarity-based) or matrix factorization trained with ALS. Collaborative filtering cannot serve users or items with no interactions, so cold start needs content features, popularity or onboarding.
Embeddings: dense coordinates for words, users and items
Look again at the factor matrices P and Q. Each row is a short list of numbers that places a user or a book in a shared space, where nearby points behave alike. That is an embedding. Jurafsky and Martin's textbook on language processing describes a word modeled as a vector, a point in high-dimensional space, also called an embedding.[5] The idea generalizes beyond words to customers, products, songs and any other ID.
The contrast is with sparse representations. In a sparse word model, each dimension stands for one vocabulary word and each cell holds a co-occurrence count. One-hot encoding of an ID works the same way: Larkspur's 40,000 titles become 40,000 columns, each row holding a single 1. Every title is then equally distant from every other, so the model learns nothing about one title from data on a similar one. Dense embeddings are far shorter: the same textbook gives 50 to 1,000 dimensions as the typical size of dense word vectors.[5]
| Property | One-hot (sparse) | Learned embedding (dense) |
|---|---|---|
| Width for 40,000 titles | 40,000 columns | For example, 64 numbers |
| Similarity between titles | None: all pairs equally far apart | Similar titles sit close together |
| Values | Mostly zeros | Dense: most entries nonzero, all learned |
| Handles an ID never seen in training | No | No, unless built from content features |
| Meaning of one dimension | Exactly one title | Usually none on its own |
Embeddings come from several kinds of training. Matrix factorization produces them for users and items. In a neural network, an embedding layer is a lookup table of vectors, one row per ID, updated by gradient descent along with the rest of the network. Word2vec learns word embeddings by training a classifier to predict whether two words occur near each other, scoring each pair with the dot product of their two vectors. The training objective is what makes similar things end up close: words that appear in similar contexts, or books bought by similar customers, get similar vectors. Similarity is then read with the dot product or cosine, exactly as in the recommender example.
Because embeddings are learned once and reused, a team can take embeddings trained on a large corpus and feed them to a new, smaller model. That reuse is a common form of transfer learning. Two cautions apply. First, embeddings absorb the patterns in their training data, including social biases, and the same textbook reports that debiasing techniques can reduce bias in embeddings but do not eliminate it.[5] Second, individual coordinates rarely mean anything, and embeddings from two separate training runs cannot be compared coordinate by coordinate, because the whole space can come out rotated.
In short: an embedding maps each word or ID to a learned dense vector, so that similar things sit close together. Embeddings replace wide one-hot columns for high-cardinality features, and they power both recommenders and language models.
Interpretable models: when the explanation is the model
An interpretable model, sometimes called a glass-box model, is one whose structure a person can read directly. The explanation is not computed afterward. It is the model. Common examples are linear and logistic regression, shallow decision trees, rule lists and generalized additive models, which add up one learned curve per feature.
Worked example, fictional. Larkspur's logistic fraud model has a coefficient of 0.7 on prior chargebacks, the number of past payments a customer's bank reversed. In logistic regression, one extra unit of a feature adds its coefficient to the log-odds, so it multiplies the odds by e raised to the coefficient: e0.7 = 2.01. A customer with base odds of 0.05 (a probability of 0.05 / 1.05 = 0.048) moves to odds of 0.10 (a probability of 0.091) with one prior chargeback. A shallow tree is just as readable. A tree of depth 3 has at most 8 leaves, and each leaf is a rule an auditor can check, such as: billing country differs from shipping country, account under 7 days old, order over 200 dollars, so hold for review.
Choose an interpretable model when the explanation itself is a requirement: a lender who must give specific reasons for a decline, a clinician who must check the logic, or a regulator who wants to inspect every rule. Interpretability has preconditions too. Coefficients mislead when features are strongly collinear (Lesson 12's variance inflation factor), when features sit on different scales and are compared without standardizing, or when important interactions are left out. And a depth-12 tree with 4,000 leaves is technically a tree but readable by nobody.
Post hoc explainability: global and local explanations
When the best model is a black box, such as a boosted ensemble or a neural network, you explain it after training. That is post hoc explainability. The exam splits it by scope. A global explanation describes how the model behaves across the whole dataset: which features it relies on and how predictions change as a feature changes. A local explanation describes why the model made one particular prediction.
| Method | Scope | What it shows | Watch out for |
|---|---|---|---|
| Permutation importance | Global | How much the model's score drops when one feature's values are shuffled | Correlated features hide each other's importance; compute it on held-out data |
| Partial dependence (PD) plot | Global | The average prediction as one or two features vary | Averages can hide opposite effects in subgroups |
| Individual conditional expectation (ICE) plot | Local, one line per row | How one row's prediction moves as a feature varies | Cluttered with many rows; usually drawn with the PD line on top |
| SHAP (SHapley Additive exPlanations) | Local, averaged for a global view | Each feature's signed contribution to one prediction | Costly to compute exactly; depends on the chosen background data |
| LIME (Local Interpretable Model-agnostic Explanations) | Local | A simple model fitted to the black box's behavior near one row | Results can change with sampling settings |
| Global surrogate | Global | A shallow tree trained to mimic the black box | Check fidelity: how often the surrogate agrees with the model |
Permutation importance is the workhorse global method. It is defined as the decrease in a model score when a given feature is randomly permuted, so the bigger the drop, the more the model depends on that feature.[6] Here is real output from the auto-sklearn documentation, where a classifier predicts whether a phone's owner is running or walking from accelerometer and gyroscope readings, with each feature shuffled 10 times on a test set:
gyro_y : 0.001 +/- 0.001
gyro_x : 0.018 +/- 0.002
gyro_z : 0.033 +/- 0.004
acceleration_x: 0.076 +/- 0.009
acceleration_z: 0.123 +/- 0.005
acceleration_y: 0.275 +/- 0.008
Read it as: shuffling acceleration_y cost the model 0.275 of its score on average, with a standard deviation of 0.008 across the repeats, while shuffling gyro_y cost almost nothing. The same example then draws partial dependence plots for the top features, including a two-feature plot that shows how acceleration_y and acceleration_z interact, and overlays ICE lines, each tracing how one sample's predicted response changes as one feature's value changes. A PD line is the average of the ICE lines. If the ICE lines fan out in different directions while the PD line stays flat, the feature matters a great deal, but in opposite ways for different rows.
For local explanations, SHAP is the method most monitoring tools adopt. Google's Vertex AI documentation describes its feature attributions as signed, pushing a prediction up or down, and states that the attributions across all features must add up to the model's inference score.[7] In SHAP's own framing, a baseline (the average prediction) plus the feature contributions reconstructs the prediction. Here is the explanation for customer 88213's held order (fictional; the hold threshold is 0.40):
| Component | Contribution to P(fraud) | Running total |
|---|---|---|
| Baseline (average prediction) | 0.06 | 0.06 |
| Shipping country differs from billing country | +0.22 | 0.28 |
| Account age 3 days | +0.15 | 0.43 |
| Order value 4 times the customer's median | +0.09 | 0.52 |
| Paid with a previously used card | -0.04 | 0.48 |
The baseline plus the contributions gives 0.48, above 0.40, so the order was held, mainly because of the address mismatch and the new account. A support agent can act on that. But this explanation describes the model, not the world. It says the model relies on the address mismatch; it does not prove that a mismatch causes fraud. The auto-sklearn example itself warns that permutation importances have pitfalls, and correlated features are the usual one: if two features carry the same information, shuffling either one alone barely hurts the model, so both can look unimportant.
In short: interpretable models are explanations by construction; post hoc methods explain a black box after training. Global methods such as permutation importance and PD plots answer which features matter overall, and local methods such as SHAP, LIME and ICE answer why this one prediction came out as it did.
Why deployed models decay: data drift and concept drift
Larkspur's churn model was accurate in April and wrong by August, though nobody touched its code. Monitoring vendor Fiddler separates the terms. It defines model drift broadly as a decline in a model's performance over time, and it contrasts this with data drift, which covers only shifts in the input distribution; model drift can happen even when input distributions stay stable.[8] To see why there are two separate causes, factor the joint distribution of inputs X and target y:
P(X, y) = P(y | X) × P(X)
Either factor can change on its own.
- Data drift means P(X) changes: the inputs look different. A social media campaign brings in younger customers, so the age and acquisition-channel distributions shift. The rule linking features to churn may still hold, and the model may still be fine, or it may now be working in regions where it had little training data. The textbook name is covariate shift.
- Concept drift means P(y | X) changes: the relationship between inputs and target changes.[8] A competitor starts offering free shipping, and customers with exactly the same order history now leave more often. The inputs can look perfectly normal while the model's predictions go wrong. Google's Vertex AI documentation gives a similar case: a model predicting customer lifetime value loses accuracy as customer habits change and the factors that predict spending change with them.[7]
A third cause looks like drift but often is not a change in the world at all. Vertex AI defines training-serving skew as a production feature distribution that deviates from the distribution used to train the model.[7] Its drift check uses a different baseline, the distribution seen in production in the past, so skew compares production with training while drift compares production with its own history.[7] When skew is there from the first day of serving, the usual culprit is a production pipeline that computes a feature differently from the training pipeline, for example in grams instead of kilograms, or with nulls filled differently. Then the fix is the pipeline, not retraining.
The two causes are detected differently, and that difference decides many exam questions. Data drift needs no labels. You compare the distribution of each input in a recent window with a baseline, using a distance such as the L-infinity distance for categorical features (the largest absolute difference in any category's share) or the Jensen-Shannon divergence. Worked example, fictional:
| Acquisition channel | Training share | Last 30 days | Absolute difference |
|---|---|---|---|
| Search | 0.50 | 0.38 | 0.12 |
| Social | 0.20 | 0.36 | 0.16 |
| 0.25 | 0.21 | 0.04 | |
| Referral | 0.05 | 0.05 | 0.00 |
The L-infinity distance is the largest difference, 0.16, driven by the social channel. With an alert threshold of 0.10, chosen here for the example, an alert fires. A Vertex AI alert email reports the feature that drifted, the threshold, and the measured statistical distance.[9] Now change one input: if social had moved only from 0.20 to 0.27 and search from 0.50 to 0.43, the largest difference would be 0.07 and no alert would fire, even though the mix had changed.
Concept drift, by contrast, can be confirmed only with labels, because it is a change in outcomes for given inputs. Churn labels may arrive 60 days late, fraud chargebacks weeks late. Until the labels arrive, teams watch proxies: the distribution of the model's own predictions, and feature attributions, where a sudden drop in a key feature's importance is a warning sign. When labels do arrive, a clean test is to compare outcomes within a fixed slice of inputs: if search-channel customers with the same order history churn more than they used to, the relationship has changed, whatever the channel mix is doing. Feedback loops make diagnosis harder. Fiddler notes the difficulty when a model's outputs influence its future inputs, as in recommendation systems or pricing models.[8] A recommender that only shows mysteries will see mostly mystery purchases and conclude that customers love mysteries.
| Cause | What changed | Signal | Usual response |
|---|---|---|---|
| Data drift | P(X) | Input distance rises; labeled performance may hold | Investigate; retrain on recent data if errors grow in the new regions |
| Sudden concept drift | P(y | X), all at once | Performance drops when labels arrive; inputs may look normal | Retrain on data from after the change; revisit features |
| Gradual or seasonal concept drift | P(y | X), slowly or in cycles | Slow decay, or a pattern that repeats each year | Scheduled retraining, seasonal features, shorter training windows |
| Training-serving skew | Usually the pipeline, not the world | Production differs from training from the first day | Fix the feature pipeline |
| Upstream data break | A source system | Sudden spike in nulls, new categories or a unit change | Repair the data; never retrain on broken inputs |
In short: data drift is a change in the inputs and can be seen without labels; concept drift is a change in what the inputs mean for the outcome and needs labels to confirm. Skew and broken pipelines look like drift but are fixed in the data, not the model.
Exam cues: matching the stem to the answer
| The stem says | Points to | Commonly confused with |
|---|---|---|
| How many, how much, a dollar amount, a duration | Regressor | A classifier over binned values, which throws away information |
| Exactly one of several categories; probabilities sum to 1 | Multiclass (multinomial) classifier with softmax | Multilabel |
| Can carry several tags at once | Multilabel, one sigmoid per label | Softmax multiclass |
| Yes or no, and false alarms are costly | Binary classifier with a tuned threshold | Retraining a new model |
| Many deep trees, bootstrap samples, reduce variance, train in parallel | Bagging or random forest | Boosting |
| Sequential, each model corrects the last, reduce bias | Boosting (AdaBoost, gradient boosting, XGBoost) | Bagging |
| Average the predicted probabilities of different models | Soft voting | Hard (majority) voting |
| A final model learns how to weight the base models | Stacking | Voting |
| Customers like you also bought | Collaborative filtering | Content-based filtering |
| Similar genre, author or description | Content-based filtering | Collaborative filtering |
| Sparse user-item matrix, latent factors, alternating solves | Matrix factorization with ALS | Similarity-based neighborhoods |
| New user or new item with no history | Cold start problem | Data drift |
| High-cardinality IDs or words as dense vectors | Embeddings | One-hot encoding |
| A regulator must see exactly how every decision is made | Interpretable model | Post hoc explanation of a black box |
| Why this one prediction | Local explanation (SHAP, LIME, ICE) | Global explanation |
| Which features matter across all predictions | Global explanation (permutation importance, PD plot) | Local explanation |
| Input distributions moved away from the baseline over time | Data drift | Concept drift |
| Same inputs now lead to different outcomes | Concept drift | Data drift |
| Production features differ from training from day one | Training-serving skew | Gradual drift |
Common misconceptions
- Logistic regression is a regressor because of its name. It outputs a class probability and is used with a threshold to assign labels, so it is a classifier. The regression in its name refers to modeling the log-odds as a linear function.
- If the input distributions have not changed, the model cannot have drifted. Concept drift changes P(y | X) while P(X) stays put. Only labeled performance data reveals it, which is why input monitoring alone is not enough.
- Adding more models to an ensemble always helps. The variance of an average has a floor of ρσ2. Members that make the same mistakes add cost without adding accuracy, which is why random forests deliberately decorrelate their trees.
- A high feature importance means the feature causes the outcome. Importance and SHAP values describe what the model relies on. Correlated features can share or hide importance, and none of these methods tests cause and effect.
- Collaborative filtering will pick up new books once they are in the catalog. Until someone interacts with a new book, it has no column to learn from. Cold start needs content features, popularity or onboarding, not more ALS iterations.
- Multiclass and multilabel are the same thing. Multiclass picks exactly one class with softmax; multilabel answers a separate yes-or-no question for each label, with probabilities that need not sum to 1.
What to carry forward
- A regressor outputs a continuous number and is judged with measures such as RMSE; tree regressors cannot extrapolate beyond the target range they saw, while linear models extrapolate a straight line that may not hold.
- A binary classifier needs one sigmoid and one set of coefficients; a multinomial classifier uses softmax over K scores so that the probabilities sum to 1; a multilabel model uses one sigmoid per label.
- The ensemble variance formula ρσ2 + (1 - ρ)σ2/n shows why bagging and random forests need decorrelated members; boosting trains members in sequence to reduce bias.
- Hard voting counts labels and soft voting averages probabilities, so they can disagree; stacking trains a meta-model on out-of-fold predictions to avoid leakage.
- Content-based filtering uses item attributes; collaborative filtering uses behavior across users, either through similarity-based neighborhoods (mean-centered cosine) or matrix factorization trained with ALS.
- ALS alternates because, with one factor matrix fixed, each row's update is a ridge regression with a closed-form solution; each row solves independently, so the work parallelizes.
- The cold start problem arises because collaborative filtering has no interactions to learn from for new users or items; content features, popularity, onboarding and hybrid models address it.
- An embedding is a learned dense vector, typically tens to hundreds of dimensions, in which similar items sit close together; it replaces wide one-hot columns, and it carries the biases of its training data.
- Data drift is a change in P(X) and is detectable without labels; concept drift is a change in P(y | X) and is confirmed only once labels arrive; training-serving skew compares production with training and is usually fixed in the pipeline, not by retraining.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn. (n.d.). sklearn.linear_model.LogisticRegression. scikit-learn.org
- scikit-learn. (n.d.). sklearn.ensemble API reference (Ensembles: gradient boosting, random forests, bagging, voting, stacking). scikit-learn.org
- Google Cloud BigQuery documentation. (n.d.). Recommendation overview. docs.cloud.google.com
- Daniel Jurafsky and James H. Martin. (2025). Speech and Language Processing, Chapter 5: Embeddings. Stanford University. web.stanford.edu
- auto-sklearn (AutoML.org). (n.d.). Model Explanation. automl.github.io
- Google Cloud. (n.d.). Introduction to Vertex AI Model Monitoring. docs.cloud.google.com
- Fiddler AI documentation. (n.d.). Model drift. docs.fiddler.ai
- Google Cloud. (n.d.). Monitor feature skew and drift. docs.cloud.google.com
- Key terms
- Regressor
- A supervised model whose output is a continuous number, such as a price, a count or a duration, evaluated with error measures such as RMSE.
- Multiclass (multinomial) classifier
- A classifier that assigns each row exactly one of three or more mutually exclusive classes, usually by applying softmax to one score per class so the probabilities sum to 1.
- Stacking
- An ensemble method in which a meta-model is trained on the out-of-fold predictions of several different base models and learns how to combine them.
- Collaborative filtering
- A recommendation approach that predicts a user's interest in an item from the behavior of many users, without needing attributes of the items themselves.
- Alternating least squares (ALS)
- A way to train matrix factorization that holds the item factors fixed while solving each user's factors by regularized least squares, then swaps, repeating until the error stops falling.
- Cold start problem
- The inability of a collaborative filtering recommender to serve a new user or new item that has no recorded interactions to learn from.
- Embedding
- A learned dense vector that represents a word, user, item or other ID, placed so that items which behave alike end up close together.
- Local explanation
- A post hoc explanation of why a model produced one particular prediction, such as SHAP attributions or a LIME surrogate for that single row.
- Data drift
- A change over time in the distribution of a model's input features compared with a baseline, detectable without outcome labels.
- Concept drift
- A change over time in the relationship between input features and the target, so the same inputs lead to different outcomes; confirming it requires labels.
Statistical Supervised Machine Learning
- Diagnose which OLS assumption has failed from residual and VIF evidence, and choose between weighted least squares, ridge, LASSO and elastic net as the fix.
- Compute and interpret logit and probit predictions, odds ratios and marginal effects for a binary outcome.
- Choose between LDA, QDA and naive Bayes from class covariance structure, data size and feature type, and work a smoothed naive Bayes calculation by hand.
- Calculate support, confidence and lift for association rules and decide which rules are worth acting on.
Five tickets on a Monday morning
At 9:05 on a Monday, the data scientist at Harbor Lane Grocery opens five tickets. Harbor Lane is a fictional 38-store chain, and every example in this lesson comes from it. Finance wants a model of weekly spend per loyalty customer, and the first attempt has errors that grow as baskets grow. Retention wants the probability that each member leaves within 90 days. Loss prevention wants returns sorted into three types using 20 numeric features. Customer service wants incoming emails sent to the right queue. Merchandising wants to know which products sell together, so it can shelve them near each other.
None of these tickets needs a neural network. Each one suits a classical statistical method: a model with explicit probability assumptions, a few parameters per feature, and coefficients a person can read. The skill is matching the method to the problem and noticing when an assumption has broken.
Exam objectives: 3.2 Given a scenario, apply appropriate statistical supervised machine-learning concepts.[1] The objective lists linear regression models (ordinary least squares and its assumptions, weighted least squares, ridge, LASSO and elastic net), logistic regression models (probit and logit), linear discriminant analysis, quadratic discriminant analysis, association rules (confidence, lift, reinforcement and support) and naive Bayes.
| Ticket | Target or question | Problem found | Method reached |
|---|---|---|---|
| 1. Weekly spend | Dollars per customer-week (continuous) | Errors widen with basket size; 61 correlated predictors | OLS, then weighted least squares and ridge, LASSO or elastic net |
| 2. Churn | Leaves within 90 days: yes or no | A straight line predicts probabilities below 0 and above 1 | Logit or probit |
| 3. Returns | Three return types from 20 numeric features | Classes differ in spread as well as in center | Linear or quadratic discriminant analysis |
| 4. Email routing | Queue label from the words in an email | Thousands of word features, few labeled emails per queue | Naive Bayes |
| 5. Shelf placement | Which items are bought together | Popular items seem to go with everything | Association rules with support, confidence and lift |
We take the tickets in order. For each one, we try the simplest tool, find where it fails, and then bring in the fix.
Ordinary least squares: the baseline for the spend ticket
Ticket 1 starts with the baseline. Ordinary least squares (OLS) fits the linear model y = β0 + β1x1 + ... + βpxp + ε. Here y is the target, the x's are the p predictors, the β's are coefficients, and ε is the error: the part of y that the predictors do not explain. OLS chooses the coefficients that make the residual sum of squares (RSS) as small as possible. RSS = Σ(yi - ŷi)2, the sum over all rows of the squared gap between each observed value yi and the model's prediction ŷi.
In the matrix notation of Lesson 4, X is the n × (p + 1) design matrix with a column of ones for the intercept. The solution is β̂ = (XTX)-1XTy, where β̂ (read 'beta-hat') is the vector of estimated coefficients. The inverse exists only when no column of X is an exact linear combination of the others. Remember that condition, because it returns twice later in this lesson.
With one predictor, the formula reduces to two steps you can do by hand. The slope is Sxy / Sxx and the intercept is ȳ - slope × x̄. Here x̄ and ȳ are the means, Sxy = Σ(xi - x̄)(yi - ȳ), and Sxx = Σ(xi - x̄)2. Below is a fictional sample of four customers. The predictor x is household size and the target y is weekly spend in tens of dollars.
| x | y | x - x̄ | y - ȳ | Product | (x - x̄) squared | Fitted ŷ | Residual |
|---|---|---|---|---|---|---|---|
| 1 | 3 | -1.5 | -2.5 | 3.75 | 2.25 | 3.1 | -0.1 |
| 2 | 5 | -0.5 | -0.5 | 0.25 | 0.25 | 4.7 | 0.3 |
| 3 | 6 | 0.5 | 0.5 | 0.25 | 0.25 | 6.3 | -0.3 |
| 4 | 8 | 1.5 | 2.5 | 3.75 | 2.25 | 7.9 | 0.1 |
| Sum | Sxy = 8.0 | Sxx = 5.0 | 0.0 |
The means are x̄ = 2.5 and ȳ = 5.5. The slope is 8.0 / 5.0 = 1.6, so each extra household member adds about $16 a week. The intercept is 5.5 - 1.6 × 2.5 = 1.5. The residuals sum to zero, which always happens when OLS includes an intercept. The RSS is 0.01 + 0.09 + 0.09 + 0.01 = 0.20, and no other straight line through these four points has a smaller RSS.
Why square the residuals? Squaring makes every residual positive. It also gives a smooth, bowl-shaped objective with one minimum and a closed-form solution. And it punishes a residual of 10 a hundred times more than a residual of 1. That last property has a cost: one wild row can drag the whole line toward itself. When the errors are normally distributed, the OLS estimate is also the maximum likelihood estimate. That link matters for the probability models later in this lesson.
The OLS assumptions and what breaks when each one fails
OLS always returns coefficients. Whether those coefficients and their p-values mean anything depends on assumptions about the error term ε. The table lists the standard set, how to check each one, and what goes wrong when it fails. Read the last column carefully, because the damage differs. Some failures bias the coefficients. Others leave the coefficients fine and spoil only the standard errors, which then makes the t-tests and confidence intervals from Lesson 1 wrong.
| Assumption | Plain meaning | How to check | What breaks if it fails | Usual fix |
|---|---|---|---|---|
| Linearity | The mean of y is a linear function of the coefficients (x squared or log x terms are allowed) | Curved pattern in a plot of residuals against fitted values | Biased predictions and coefficients | Transform variables, add terms, or use a nonlinear model |
| Exogeneity | The errors average zero at every value of the predictors; no left-out variable is tied to the included ones | Domain reasoning; residuals alone cannot prove it | Biased coefficients (omitted-variable bias) | Add the missing variable or improve the study design |
| Independent errors | One row's error says nothing about another's | Study design; the Durbin-Watson test for time order | Standard errors too small, so effects look too certain | Clustered standard errors or the time-series models of Lesson 5 |
| Homoscedasticity | Constant error variance at every value of the predictors | Fan shape in the residual plot; Breusch-Pagan test | Coefficients still unbiased, but standard errors are wrong and OLS is no longer the most precise estimator | Weighted least squares, robust standard errors, or a log of y |
| No perfect multicollinearity | No predictor is an exact linear combination of the others | Variance inflation factor (VIF) | Perfect: XTX cannot be inverted. High: unstable, inflated coefficients | Drop or combine predictors; ridge regression |
| Normal errors | The errors follow a normal distribution | Quantile-Quantile (Q-Q) plot of residuals | Exact t and F tests fail in small samples; coefficients stay unbiased | Larger samples, transformations, or bootstrap intervals |
The Gauss-Markov theorem covers the first five rows. If they hold, OLS is the best linear unbiased estimator, often shortened to BLUE. Among all estimators that are linear in y and unbiased, OLS has the smallest variance. Normality is not needed for that result. It is needed only for exact small-sample tests. Note the qualifier 'among unbiased estimators'. Ridge and LASSO, below, can beat OLS on test error by leaving that group on purpose: they accept a little bias in exchange for a large cut in variance.
Here is the diagnostic summary from the first spend model, written as a fictional printout.
Fictional diagnostic summary: weekly_spend, OLS
rows (customer-weeks) 4,812
predictors 61
R-squared, training 0.71
R-squared, 5-fold cross-validation 0.52
Breusch-Pagan p-value < 0.001
residual standard deviation, top decile
of fitted values / bottom decile 3.4
largest VIFs promo_emails_sent 23.4
promo_emails_opened 22.9
coupons_redeemed 11.8
Read it line by line. The Breusch-Pagan test asks whether residual variance depends on the predictors. A p-value below 0.001, together with a ratio of 3.4 between the residual standard deviation in the top and bottom deciles, means the constant-variance assumption has failed. Next, the VIF for predictor j is 1 / (1 - Rj2), where Rj2 comes from regressing predictor j on all the other predictors. A VIF of 23.4 means that coefficient's variance is 23.4 times what it would be if the predictors were uncorrelated. Common rules of thumb start to worry at 5 or 10. Finally, R-squared falls from 0.71 in training to 0.52 under cross-validation. That gap suggests the 61-predictor model is partly fitting noise in the training data.
That is three findings but two separate problems: unequal error variance, and too much variance in the model itself. Each needs its own fix.
The upshot: heteroscedasticity (error variance that changes across the data) leaves OLS coefficients unbiased but makes their standard errors wrong. Multicollinearity leaves them unbiased but unstable. Weighted least squares targets the first. Regularization targets the second.
Weighted least squares: when some rows are noisier than others
OLS treats every row as equally trustworthy, so the noisy large-basket weeks pull the coefficients around as hard as the precise small-basket weeks do. Weighted least squares (WLS) lets each row count in proportion to how reliable it is. The NIST/SEMATECH e-Handbook of Statistical Methods describes WLS as useful when the response values vary by different amounts across combinations of the predictor values.[2] The criterion is the same sum of squared residuals with one addition: a weight wi on each row that sets how much that row influences the final estimates.[2]
The weighted criterion is Q = Σ wi(yi - ŷi)2. For a linear model the solution is β̂ = (XTWX)-1XTWy, where W is a diagonal matrix that holds the weights. The standard choice is wi = 1 / σi2, the inverse of row i's error variance. A row with a quarter of the variance gets four times the weight.
The simplest case to work by hand is a model with only an intercept, where the estimate is just a weighted mean. Suppose three stores report an average weekly spend for the same customer segment, in tens of dollars (fictional numbers). Store C is a new store with few customers, so its figure is much noisier.
| Store | Estimate y | Error variance | Weight 1 / variance | Weight × y |
|---|---|---|---|---|
| A | 10 | 1 | 1.00 | 10.0 |
| B | 12 | 1 | 1.00 | 12.0 |
| C | 30 | 25 | 0.04 | 1.2 |
| Total | 2.04 | 23.2 |
OLS weights all three equally: (10 + 12 + 30) / 3 = 17.33. WLS divides the weighted sum by the total weight: 23.2 / 2.04 = 11.37. The noisy new store barely moves the estimate, as it should.
Now change one input. Suppose all three stores have the same error variance, say 4. Every weight becomes 0.25, and the WLS estimate is (2.5 + 3 + 7.5) / 0.75 = 17.33, exactly the OLS answer. This second run makes the general point: WLS with equal weights is OLS. The weights matter only when the variances differ.
Where do the weights come from? Three common sources:
- Known precision. Instruments or surveys sometimes report a standard error for each measurement.
- Averages of different sizes. If row i is the mean of ni raw values, its variance is σ2 / ni, so the weight is ni.
- A fitted variance model. Fit OLS, model how the size of the residuals depends on the fitted values, and use the inverse of the predicted variance as the weight. This is called feasible WLS. For Harbor Lane, if the residual standard deviation grows in proportion to the fitted spend, the weights are 1 / ŷi2.
Estimated weights add their own noise, and badly chosen weights can do more harm than equal ones. A common alternative keeps the OLS coefficients and replaces only the standard errors with heteroscedasticity-robust ones. Robust standard errors repair the p-values. WLS also improves precision, but only when the weights are right. Modeling log(spend) is a third route, but it changes the question the model answers, because coefficients then describe percentage changes.
Two different motives get called 'weighting', so keep them apart. WLS weights reflect error variance. Sample weights used for class imbalance or survey design reflect how much a row should represent. Neither kind of weight is a way to hide outliers that are really data errors. Those belong to the cleaning work of Lesson 7.
Ridge regression: shrinking correlated coefficients
Now for the second problem: 61 predictors, several of them near-copies of each other. Promo emails sent and promo emails opened move together, so OLS can trade one off against the other almost freely. A typical symptom (fictional numbers) is a coefficient of +4.1 on emails opened and -3.8 on emails sent. The two nearly cancel, and they flip sign from one bootstrap sample to the next. Regularization stops this by charging the fit for large coefficients.
Ridge regression minimizes RSS + λΣβj2. Lambda (λ) is a tuning value of zero or more, chosen by the analyst. David Blei's Columbia lecture notes present the same idea in constrained form: minimize the RSS subject to a limit on the sum of the squared coefficients.[3] The two forms are equivalent, because each budget on the coefficients matches some λ.
Ridge still has a closed form: β̂ = (XTX + λI)-1XTy, where I is the identity matrix. Adding λ to every diagonal entry of XTX makes the matrix invertible for any positive λ. That holds even when predictors are perfectly collinear or there are more predictors than rows, the two cases where OLS has no unique answer. Set λ = 0 and you are back to OLS. Let λ grow without limit and every coefficient heads toward zero.
Blei summarizes ridge as a kind of shrinkage: it pulls the coefficients close to zero and close to each other.[3] The second half is what tames the emails pair. Instead of +4.1 and -3.8, ridge gives two small coefficients of similar size that share the credit.
Two practical rules follow from the form of the penalty. First, the intercept is normally left out of the penalty, because shrinking it would only shift every prediction up or down. Second, standardize the predictors before fitting. The penalty charges every coefficient on the same scale, so the same feature would be penalized differently if it were measured in cents instead of dollars.
To see shrinkage in numbers, go back to the four-customer sample and center both variables so the intercept drops out. The one-predictor ridge objective is Σ(yi - βxi)2 + λβ2. Set its derivative to zero: -2Sxy + 2βSxx + 2λβ = 0. That gives β̂ = Sxy / (Sxx + λ) = 8 / (5 + λ). The ridge column of the table in the next section shows the result: the slope shrinks steadily as λ grows, but it never reaches zero, because a positive number divided by a positive number stays positive.
LASSO and elastic net: shrinking some coefficients to exactly zero
The Least Absolute Shrinkage and Selection Operator (LASSO) swaps the squared penalty for an absolute one: minimize RSS + λΣ|βj|. Yanjun Qi's University of Virginia lecture notes make the consequence explicit. When the budget on the sum of absolute coefficients is tight enough, which is the same as λ being large enough, the lasso sets some coefficients exactly to zero.[4] Blei calls this a form of feature selection: the lasso picks out a relevant subset of the predictors.[3] For Harbor Lane, that means a short list of spend drivers that finance can actually read.
The one-predictor case shows why. The derivative of |β| is +1 or -1 and does not fade as β approaches zero. Setting the derivative of Σ(yi - βxi)2 + λ|β| to zero for a positive β gives -2Sxy + 2βSxx + λ = 0, so β̂ = (Sxy - λ/2) / Sxx. Once λ/2 reaches Sxy, no positive value can lower the objective, and the estimate stops at exactly zero. With Sxy = 8 and Sxx = 5, that happens at λ = 16.
| λ | Ridge: 8 / (5 + λ) | LASSO: (8 - λ/2) / 5, floored at 0 |
|---|---|---|
| 0 | 1.600 | 1.600 |
| 4 | 0.889 | 1.200 |
| 10 | 0.533 | 0.600 |
| 16 | 0.381 | 0.000 |
| 30 | 0.229 | 0.000 |
Ridge's penalty has slope 2λβ, which shrinks to nothing as β approaches zero, so ridge never quite finishes the job. LASSO's penalty keeps slope λ all the way down, so it does. Geometrically, the LASSO constraint region is a diamond with corners on the axes, and the best fit often lands on a corner, where some coefficient is zero. The ridge region is a circle with no corners. Unlike ridge, the lasso has no closed-form solution in general, so software fits it iteratively, usually by coordinate descent.
One caution: λ values do not carry over from one library to another. Some scale the RSS by 1/(2n) and some do not. The numbers in the table belong to the formula written here, not to any particular package.
LASSO has two known weaknesses. Given a group of highly correlated predictors, it tends to keep one and drop the rest, and which one survives can change with a small change in the data. And when there are more predictors than rows, it can keep at most as many predictors as there are rows. The elastic net addresses both. Blei describes it as a convex combination of the L1 (absolute) and L2 (squared) penalties.[3] One common way to write it is λ[αΣ|βj| + (1 - α)Σβj2 / 2], with α between 0 and 1. At α = 1 it is the LASSO, and at α = 0 it is ridge. In between, it still produces exact zeros, but the ridge part makes correlated predictors enter or leave together.
Watch the names of the tuning settings. In R's glmnet package, alpha is the mix and lambda is the strength. In scikit-learn, alpha is the strength and l1_ratio is the mix. Whatever the names, the strength (and the mix, for elastic net) are tuned by cross-validation. Lesson 12 covered how to do that without leaking test data.
| Property | OLS | Ridge | LASSO | Elastic net |
|---|---|---|---|---|
| Added to RSS | Nothing | λΣβj2 | λΣ|βj| | A mix of both |
| Exact zeros | No | No | Yes | Yes |
| Closed form | Yes | Yes | No | No |
| Correlated group of predictors | Unstable, may swing in sign | Shares credit across the group | Tends to keep one, drop the rest | Keeps or drops the group together |
| More predictors than rows | No unique solution | Works | Works, but keeps at most n predictors | Works |
| Reach for it when | Assumptions hold and you need unbiased inference | Many correlated predictors, all plausibly relevant | You need a short list of drivers | You need a short list from correlated groups |
The upshot: all three penalties trade a little bias for less variance. Only the absolute-value penalty, alone or in the elastic net mix, removes predictors. If a stem asks for feature selection, ridge is the wrong answer however well it handles multicollinearity.
Logit and probit: modeling a probability for the churn ticket
Ticket 2's target is 1 if a member churns within 90 days and 0 if not. Running OLS on a 0/1 target gives the linear probability model. It is easy to read, but a straight line keeps rising, so for extreme customers it predicts 'probabilities' below 0 or above 1. Its errors are also heteroscedastic by construction. Bernard Lejeune's econometrics notes say that the logit and probit models overcome these shortcomings, and that the price is that they are more complicated to interpret.[5]
Both models have the form P(y = 1 | x) = G(xβ). Here xβ is the familiar linear score, and G is a function that always returns a value strictly between 0 and 1. The two models differ only in their choice of G.
- Logit model (logistic regression). G(z) = ez / (1 + ez) = 1 / (1 + e-z), which is the cumulative distribution function (CDF) of the standard logistic distribution. Inverting it gives ln(p / (1 - p)) = xβ, so the linear score is the log of the odds. That inverse, the logit, names the model.
- Probit model. G is Φ, the CDF of the standard normal distribution, which cannot be written in closed form.[5] Inverting it gives Φ-1(p) = xβ.
Both are generalized linear models: a linear score, a link function, and a distribution for y. The Oxford statistical machine learning notes describe logistic regression as a generalized linear model with a Bernoulli likelihood and a logit link.[6] The probit model swaps in the probit link. Neither has a closed-form solution. Both are fit by maximum likelihood, iteratively, and tested with z statistics, Wald tests or likelihood ratio tests rather than the OLS t and F tests.
The latent variable view explains when to pick which. Imagine an unobserved score y* = xβ + e, and let y = 1 whenever y* is above zero. If e follows a standard logistic distribution you get the logit model. If e is standard normal you get the probit model. An econometrician who thinks of default as a normally distributed creditworthiness score crossing a threshold will reach for probit. A data scientist who wants to tell a stakeholder 'each complaint doubles the odds of leaving' will reach for logit, because its coefficients turn directly into odds ratios.
In practice the two usually give very similar results.[5] Their coefficients differ by a scale factor, not in substance. The standard logistic distribution has standard deviation π/√3, about 1.81, compared with 1 for the standard normal. So logit coefficients usually come out about 1.6 to 1.8 times the probit ones on the same data. Never compare a logit coefficient directly with a probit coefficient.
Reading logit coefficients: odds, probabilities and marginal effects
Suppose the fitted churn logit (fictional) has intercept -2.0 and coefficient 0.35 on months since last purchase. A probit fit to the same data gives intercept -1.22 and coefficient 0.215, about 1.63 times smaller, as the scale argument predicts.
| Months since last purchase | Logit score z = -2.0 + 0.35 × months | Odds ez | Logit probability 1 / (1 + e-z) | Probit probability Φ(-1.22 + 0.215 × months) |
|---|---|---|---|---|
| 0 | -2.00 | 0.135 | 0.119 | 0.111 |
| 4 | -0.60 | 0.549 | 0.354 | 0.359 |
| 8 | 0.80 | 2.226 | 0.690 | 0.691 |
| 12 | 2.20 | 9.025 | 0.900 | 0.913 |
Work the 4-month customer through. The score is z = -2.0 + 0.35 × 4 = -0.6. Then e0.6 = 1.822, so p = 1 / (1 + 1.822) = 0.354. At a 0.5 threshold this customer is not flagged.
Now change the input to 8 months. The score becomes z = 0.8, e-0.8 = 0.449, and p = 1 / 1.449 = 0.690. The prediction has crossed the threshold, so the customer is flagged. The probit column agrees to within about 0.01 in the middle of the range and differs a little more in the tails. That is where the logistic distribution's heavier tails show.
Three readings of the same coefficient 0.35 are worth keeping apart:
- Log-odds. Each extra month adds 0.35 to the log-odds of churn. That statement is exact but hard to explain to anyone.
- Odds ratio. Each extra month multiplies the odds by e0.35 = 1.419, an increase of about 42 percent. Check it with the table: from 4 to 8 months the odds go from 0.549 to 2.226, a factor of 4.06, which equals 1.4194.
- Marginal effect on probability. This is not constant. For the logit it equals p(1 - p)β. At 4 months that is 0.354 × 0.646 × 0.35 = 0.080, so one more month adds about 8 percentage points. At 8 months it is 0.690 × 0.310 × 0.35 = 0.075. The effect peaks at p = 0.5 (0.25 × 0.35 = 0.0875) and fades toward both ends.
Despite its name, logistic regression is used here as a classifier. It outputs a probability, and you choose the threshold from the cost of each kind of error, using the confusion-matrix tools of Lesson 2. If one predictor perfectly separates churners from stayers in training, maximum likelihood pushes that coefficient toward infinity. The ridge and LASSO penalties from the previous sections work on the logistic loss as well, and they are the usual cure.
The upshot: logit and probit pass the same linear score through different S-shaped CDFs. Choose logit when you need odds ratios and probit when a normal latent variable is the natural story. Never treat a logit coefficient as a fixed change in probability.
Linear and quadratic discriminant analysis for the returns ticket
Loss prevention labels returns as ordinary returns, store errors, or wardrobing (buying an item, using it, then returning it). Each return has 20 numeric features, such as days held and the share of the receipt returned. Logistic regression would model the probability of each type given the features directly. Discriminant analysis works the other way round. As Pier Francesco Palamara's Oxford notes put it, LDA and QDA estimate p(x|y), the distribution of the features within each class.[6] Bayes' rule then turns that into p(y|x), the probability of each class given the features. That makes them generative models. Logistic regression is a discriminative model.
The recipe has three steps. First, for each class k, estimate the prior πk (the class's share of the training rows), the mean vector μk and a covariance matrix. Second, model the features within class k as multivariate normal. Third, assign a new point to the class with the largest πkfk(x), where fk is that class's normal density. The boundary between two classes is the set of points where their posterior probabilities are equal.
Linear discriminant analysis (LDA) assumes that every class shares one covariance matrix Σ. Write out the log of πkfk(x) and the quadratic term xTΣ-1x is the same for every class, so it cancels when you compare two classes. What remains is linear in x, so the boundaries are straight lines, planes or hyperplanes. Quadratic discriminant analysis (QDA) gives each class its own covariance matrix Σk. Now the quadratic term differs by class and does not cancel, so the discriminant function is quadratic in x. QDA boundaries can curve, and they can even enclose one class inside another.
A one-feature example with two classes shows both behaviors. Let ordinary returns (class 1) have mean 0 and wardrobing (class 2) have mean 4, with a shared variance of 1. Setting the two log posteriors equal and solving gives the LDA boundary:
x* = (μ1 + μ2) / 2 + σ2 ln(π1 / π2) / (μ2 - μ1)
With equal priors, the log term is zero and x* = 2, the midpoint. A return at x = 2.3 is classed as wardrobing. Now change the priors to the realistic 0.9 and 0.1. The boundary moves to 2 + ln(9) / 4 = 2 + 2.197 / 4 = 2.55, and the same return at 2.3 is now classed as ordinary. The rarer class has to earn its label with stronger evidence.
Next, give the classes the same mean but different spreads. Let ordinary returns have mean 0 and variance 1, and let store errors have mean 0 and variance 9. LDA's shared-covariance model sees two identical classes and cannot separate them at all. QDA compares the two log densities: -x2/2 for ordinary returns against -ln 3 - x2/18 for store errors. They are equal when x2(1/2 - 1/18) = ln 3, so x2 = 1.0986 / 0.444 = 2.47 and |x| = 1.57. With equal priors, QDA classes a return as ordinary when |x| is below 1.57 and as a store error otherwise. That is two boundaries, one on each side, which no straight line can produce.
The flexibility has a price, and the parameter count shows it. Each covariance matrix for p features has p(p + 1) / 2 distinct entries, because it is symmetric.
| Piece | LDA | QDA |
|---|---|---|
| Class means (K × p) | 60 | 60 |
| Covariance entries | 210 (one shared matrix) | 630 (one matrix per class) |
| Total | 270 | 690 |
| Decision boundaries | Linear | Quadratic |
The Oxford notes give the trade-off in two sentences. If the class covariances are very different, QDA will probably beat LDA.[6] But the extra flexibility comes at a price: more variance and potential overfitting.[6] If loss prevention has only 25 labeled wardrobing cases, a 20 × 20 covariance matrix for that class is very poorly estimated. With 20 or fewer rows it would be singular and could not be inverted at all. Regularized discriminant analysis (RDA) blends each class covariance with the shared one through a mixing weight, giving a range of models between LDA and QDA. Cross-validation picks the blend.
LDA has a second job. Fisher's discriminant analysis looks for the directions that best separate the class means relative to the spread within classes, and Ghojogh and Crowley's tutorial proves that LDA and Fisher discriminant analysis are equivalent.[7] With K classes, LDA projects the data onto at most K - 1 such directions. For the returns ticket, that means a two-dimensional plot that shows the three types as clusters, which is useful for exploratory analysis and for explaining results to stakeholders.
One trap with the name: in text work, LDA can also mean latent Dirichlet allocation, a topic model. If a stem mentions topics in documents, it means the topic model, not this classifier.
Naive Bayes for the email routing ticket
Customer service has a vocabulary of thousands of words and a few hundred labeled emails per queue. A discriminant model would need a covariance matrix with millions of entries. The naive Bayes classifier sidesteps this with a strong simplification. The scikit-learn documentation describes the family as applying Bayes' theorem with the 'naive' assumption of conditional independence between every pair of features, given the class.[8] In symbols: P(y | x1, ..., xn) is proportional to P(y) × P(x1 | y) × ... × P(xn | y). Each factor is a one-dimensional distribution that can be estimated from simple counts.
| Variant | Model for each feature given the class | Typical data |
|---|---|---|
| Gaussian | Normal distribution with a class-specific mean and variance | Continuous measurements |
| Multinomial | Share of word counts, estimated from frequencies | Word counts in documents |
| Bernoulli | Present or absent; absence of a telling word counts as evidence | Short texts, binary flags |
| Categorical | Probability of each category level | Encoded categorical features |
Here is a fictional multinomial example with two queues, Refund and Delivery, and a four-word vocabulary. In 1,000 training emails, 400 went to Refund and 600 to Delivery, so the priors are 0.4 and 0.6. Word probabilities use additive smoothing: θ = (count + α) / (total + α × vocabulary size), with α = 1. scikit-learn explains that the smoothing constant accounts for features missing from the training samples and prevents zero probabilities.[8] Setting α = 1 is called Laplace smoothing.
| Word | Refund count | Refund probability | Delivery count | Delivery probability |
|---|---|---|---|---|
| refund | 30 | 31/54 = 0.574 | 2 | 3/74 = 0.041 |
| late | 5 | 6/54 = 0.111 | 40 | 41/74 = 0.554 |
| driver | 0 | 1/54 = 0.019 | 28 | 29/74 = 0.392 |
| card | 15 | 16/54 = 0.296 | 0 | 1/74 = 0.014 |
| Total | 50 | denominator 50 + 4 = 54 | 70 | denominator 70 + 4 = 74 |
First email: 'my refund is late'. Only the vocabulary words count.
- Refund score: 0.4 × 0.574 × 0.111 = 0.0255.
- Delivery score: 0.6 × 0.041 × 0.554 = 0.0135.
- Normalize: 0.0255 / (0.0255 + 0.0135) = 0.65. The email goes to Refund.
Second email: 'my refund is late, the driver never came'. One more word changes the result.
- Refund: 0.0255 × 0.019 = 0.00047.
- Delivery: 0.0135 × 0.392 = 0.00528.
- Delivery now holds 0.00528 / (0.00528 + 0.00047) = 92 percent of the probability, so the email goes to Delivery.
Without smoothing, Refund's probability for 'driver' would be 0/50 = 0. Any email containing 'driver' would then get a Refund probability of exactly zero, whatever else it said. Real vocabularies make the products tiny, so implementations add log probabilities instead of multiplying, to avoid numeric underflow.
The independence assumption is plainly false for text: 'late' and 'driver' go together. Even so, naive Bayes classifiers have worked well in many real-world settings, document classification and spam filtering most famously.[8] They train in one pass over the counts, need little data, and handle thousands of features. The cost shows up in the probabilities. Correlated words count the same evidence twice, which pushes the outputs toward 0 and 1. scikit-learn warns that naive Bayes is a decent classifier but a bad estimator, so its probability outputs should not be taken too seriously.[8] Use the ranking. If a downstream decision needs real probabilities, calibrate them or use logistic regression. For continuous features, Gaussian naive Bayes is QDA with every covariance matrix forced to be diagonal, so you can place it at the simple end of the same family.
The upshot: naive Bayes trades a false independence assumption for speed and tiny data needs. Smoothing keeps one unseen word from vetoing a class, and the output is a good ranking but a poor probability.
Association rules for the shelf ticket: support, confidence and lift
Merchandising's question has no single labeled target. It asks which items appear together in the same basket. Association rule learning answers it with rules of the form X to Y ('baskets with X tend to contain Y'). X is the antecedent and Y the consequent. Textbooks usually file this under unsupervised learning, but CompTIA lists it under objective 3.2, so expect it there. Three measures do the work. Here N is the number of baskets and count(X and Y) is the number of baskets that contain both.
- Support of the rule = count(X and Y) / N. How common the pair is. Low support means a rule based on a handful of baskets.
- Confidence = support(X and Y) / support(X). Of the baskets with X, the share that also contain Y. It estimates P(Y | X), and it depends on the direction of the rule.
- Lift = confidence / support(Y) = support(X and Y) / (support(X) × support(Y)). How much X raises the chance of Y compared with independence. Lift is symmetric: X to Y and Y to X have the same lift.
Take 1,000 fictional baskets. 200 contain pasta, 250 contain pasta sauce, and 120 contain both. 600 contain milk, 500 contain bread, and 310 contain both. 300 contain coffee, 700 contain bananas, and 200 contain both. A rule miner run on these three pairs, with minimum support 0.10 and minimum confidence 0.45, prints something like this:
Fictional rule-mining output (min support 0.10, min confidence 0.45)
antecedent consequent support confidence lift
pasta sauce 0.120 0.600 2.40
sauce pasta 0.120 0.480 2.40
milk bread 0.310 0.517 1.03
bread milk 0.310 0.620 1.03
coffee bananas 0.200 0.667 0.95
Work the first line. Support = 120 / 1,000 = 0.12. Confidence = 120 / 200 = 0.60. Lift = 0.60 / 0.25 = 2.40: a pasta buyer is 2.4 times as likely as an average shopper to buy sauce. Reverse the rule and the confidence changes to 120 / 250 = 0.48, but the lift stays 0.48 / 0.20 = 2.40. The reverse of coffee to bananas is missing because its confidence, 200 / 700 = 0.286, falls below the 0.45 minimum.
Now the line that fools people. Coffee to bananas has the highest confidence on the list, 200 / 300 = 0.667. But 70 percent of all baskets contain bananas anyway, so the lift is 0.667 / 0.70 = 0.95. Coffee buyers are slightly less likely than average to buy bananas. The two milk and bread rules have the highest support, but their lift of 1.03 is close to independence: both items are simply popular. Of the three pairs, only pasta and sauce deserve a shared display. Confidence alone would have pointed to bananas.
Rule miners such as the Apriori algorithm find frequent itemsets first and then build rules from them. The key fact that makes this feasible is that support can only fall as an itemset grows. If {pasta, sauce} fails the minimum support, then {pasta, sauce, parmesan} must fail too, so the algorithm never needs to count it. Two cautions apply to whatever the miner prints. Rules describe co-occurrence, not cause: placing sauce beside pasta may or may not move sales, which is a job for the experiments of Lesson 10. And with thousands of items, some high-lift rules appear by chance, so demand enough support before acting on any of them.
What 'reinforcement' might mean on this objective
The objective's association-rules list includes 'reinforcement' beside confidence, lift and support. It is not one of the standard rule measures, and the objectives document gives no definition. What follows are two plausible readings, not an established definition, so let the wording of the stem tell you which one a question means.
The first reading, an interpretation rather than a standard term, is the direction that lift reports. When lift is above 1, you could say the antecedent reinforces the consequent: the items act as complements, and promoting one may pull the other along. When lift is below 1, as with coffee and bananas, the antecedent works against the consequent: the items behave like substitutes or serve different shoppers.
The second reading is reinforcement learning. This is a separate, well-established branch of machine learning in which an agent learns a policy by acting, receiving rewards and adjusting, rather than by fitting labeled examples or counting baskets. A recommender that learns which product to show next from clicks and purchases is the usual business example.
Neither reading changes how support, confidence and lift are computed.
Exam cues: which method the stem is pointing at
| The stem says | Points to | Commonly confused with |
|---|---|---|
| Residuals fan out; variance grows with fitted values; some measurements are more precise | Weighted least squares | Ridge, which fixes variance in the coefficients, not in the errors |
| High VIF; correlated predictors; keep all features but stabilize them | Ridge | LASSO |
| Feature selection; sparse model; short list; coefficients exactly zero | LASSO | Ridge |
| Sparse model plus groups of correlated predictors, or more predictors than rows | Elastic net | LASSO |
| Binary outcome; probability; odds ratio | Logit (logistic regression) | OLS on a 0/1 target |
| Latent normal variable; standard normal CDF link | Probit | Logit |
| Shared covariance; linear boundary; few labeled rows; project onto K - 1 dimensions | LDA | QDA |
| Class covariances differ; curved boundary; plenty of data per class | QDA | LDA |
| Text; spam; word counts; conditional independence; very fast training | Naive Bayes | Logistic regression |
| How often the items appear together | Support | Confidence |
| Of baskets with X, the share that also contain Y | Confidence | Lift |
| Compared with chance or independence; above or below 1 | Lift | Confidence |
Common misconceptions
- 'Heteroscedasticity biases the OLS coefficients.' It does not. The coefficients stay unbiased. What fails is their standard errors, and OLS is no longer the most precise estimator. That is why robust standard errors are a valid alternative to WLS.
- 'Ridge regression does feature selection.' Ridge shrinks every coefficient but sets none to exactly zero, because its penalty's slope fades as a coefficient approaches zero. Only the absolute-value penalty of LASSO or elastic net removes predictors.
- 'A logit coefficient of 0.35 means the probability rises 0.35 per unit.' The coefficient is a change in log-odds. The odds multiply by e0.35, and the change in probability is p(1 - p)β, which depends on where the customer starts.
- 'QDA is more flexible, so it always beats LDA.' QDA must estimate a covariance matrix for every class. With few rows per class, that extra variance can make it worse than LDA, and with no more rows than features a class covariance cannot be inverted at all.
- 'A high-confidence rule is a strong rule.' Confidence ignores how common the consequent already is. A rule pointing to an item in 70 percent of baskets can have high confidence and a lift below 1.
- 'Naive Bayes probabilities can be used as real probabilities.' Double-counted correlated evidence pushes them toward 0 and 1. The class ranking is usually sound. The probability values need calibration first.
What to remember
- OLS minimizes the residual sum of squares, with solution (XTX)-1XTy. Under the Gauss-Markov conditions it is the best linear unbiased estimator. Normal errors are needed only for exact small-sample tests.
- Heteroscedasticity and multicollinearity leave OLS coefficients unbiased. The first spoils the standard errors, and the second makes the coefficients unstable (VIF = 1 / (1 - Rj2)).
- Weighted least squares multiplies each squared residual by a weight, usually 1 / σi2. With equal weights it gives the OLS answer.
- Ridge adds λΣβ2 and shrinks without zeroing. LASSO adds λΣ|β| and can set coefficients exactly to zero. Elastic net mixes the two so that correlated groups enter or leave together. Penalty settings are tuned by cross-validation on standardized predictors, with the intercept left unpenalized.
- Logit uses the standard logistic CDF and probit the standard normal CDF. Their fitted probabilities are usually very close, and logit coefficients run about 1.6 to 1.8 times probit ones.
- In a logit, eβ is the odds ratio per unit, and the effect on probability is p(1 - p)β, largest at p = 0.5.
- LDA shares one covariance matrix and gives linear boundaries. QDA gives each class its own covariance and curved boundaries, at the cost of K times as many covariance parameters.
- Naive Bayes assumes the features are independent given the class. Additive smoothing (α = 1 is Laplace) prevents zero probabilities, and its probability outputs are poorly calibrated.
- Support = count(X and Y) / N. Confidence = support(X and Y) / support(X). Lift = confidence / support(Y). Lift below 1 means X makes Y less likely than chance.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- NIST. (n.d.). NIST/SEMATECH e-Handbook: Weighted Least Squares Regression. itl.nist.gov
- David Blei. (2015). Regularized regression. Columbia University. cs.columbia.edu
- Yanjun Qi. (2016). Linear regression and regularization (L6 lrReg). University of Virginia. cs.virginia.edu
- University of Liège. (2021). Lecture Notes Ch 17 - Binary Response Models. orbi.uliege.be
- University of Oxford. (2019). HT19 Lecture 9 (Statistical Machine Learning: discriminant analysis). stats.ox.ac.uk
- Benyamin Ghojogh and Mark Crowley. (2019). Linear and Quadratic Discriminant Analysis: Tutorial. arXiv. arxiv.org
- scikit-learn. (2022). 1.9. Naive Bayes. scikit-learn.org
- Key terms
- Ordinary least squares (OLS)
- The standard way to fit a linear regression. It chooses the coefficients that minimize the residual sum of squares, the total of the squared gaps between observed and predicted values.
- Homoscedasticity
- The OLS assumption that error variance is the same at every value of the predictors. When it fails (heteroscedasticity), the coefficients stay unbiased but their standard errors are wrong.
- Weighted least squares (WLS)
- Least squares in which each squared residual is multiplied by a weight, usually the inverse of that row's error variance, so that noisier rows influence the fit less.
- Ridge regression
- Linear regression that adds lambda times the sum of the squared coefficients to the residual sum of squares. It shrinks coefficients toward zero and toward each other but never makes any exactly zero.
- LASSO
- Least Absolute Shrinkage and Selection Operator: regression that adds lambda times the sum of the absolute coefficients to the residual sum of squares. A large enough penalty sets some coefficients exactly to zero, so it selects features.
- Elastic net
- Regularized regression whose penalty is a weighted mix of the LASSO (L1, absolute-value) and ridge (L2, squared) penalties. It produces sparse models while keeping groups of correlated predictors together.
- Logit and probit models
- Models for a yes-or-no outcome that pass a linear score through a cumulative distribution function to get a probability between 0 and 1: the standard logistic CDF for logit, the standard normal CDF for probit.
- Quadratic discriminant analysis (QDA)
- A generative classifier that models each class as a multivariate normal distribution with its own covariance matrix, which gives curved (quadratic) decision boundaries. Linear discriminant analysis shares one covariance matrix across classes and gives straight boundaries.
- Naive Bayes
- A classifier that applies Bayes' theorem on the assumption that features are independent given the class. It multiplies the class prior by one likelihood per feature.
- Lift
- For an association rule X to Y: the share of baskets with X that also contain Y, divided by the share of all baskets that contain Y. Above 1 means X raises the chance of Y compared with independence; below 1 means it lowers it.
Tree-Based Supervised Machine Learning
- Diagnose an overfit decision tree from training and validation scores and choose the control (depth, leaf size, pruning) or ensemble that repairs it.
- Compute Gini impurity for candidate splits and explain how CART and random forests choose which split to make.
- Explain how bagging and random forests reduce variance through bootstrap samples, out-of-bag estimates and per-split feature sampling.
- Explain how gradient boosting and XGBoost reduce bias by fitting trees to the negative gradient, and set learning rate, rounds and regularization in a given scenario.
A churn tree that scored 1.000 and failed review
Training accuracy 1.000, validation accuracy 0.712. Those two numbers head a review note for a churn model built from 40,000 telecom customer records. The note is a fictional example, but reviewers see this kind of reasoning all the time. The analyst grew one decision tree with no depth limit and then wrote:
"The tree has learned the training data perfectly, so the validation split must be unrepresentative. Next step: grow it deeper, then boost it to lift validation. Contract type is clearly the main driver of churn, because the tree splits on it first."
None of the conclusions after the numbers is supported by the evidence, and each one lines up with a bullet of the objective. A perfect training score from an unrestricted tree is a symptom, not a result. Blaming the validation split skips the more likely explanation. Growing the tree deeper makes the symptom worse. Boosting treats a different problem from the one this tree has. And the root split only tells you which feature won one greedy comparison. It does not tell you which feature drives churn. This lesson debugs the note line by line, and it introduces decision trees, bootstrap aggregation, random forests, gradient boosting and XGBoost as each repair needs them.
Exam objectives: CompTIA DataX DY0-001, objective 3.3, "Given a scenario, apply tree-based supervised machine-learning concepts." Its bullets are decision trees, random forest, boosting (gradient boosting and XGBoost) and bootstrap aggregation (bagging).[1] Expect scenario questions that give you training and validation scores, a description of the data or a change to a hyperparameter, and then ask which tree method or setting fits.
How a decision tree chooses its splits
A decision tree predicts a target by asking a chain of yes-or-no questions about the features, such as "is tenure under 12 months?" Each internal node holds one question, each branch is one answer, and each leaf holds a prediction. The scikit-learn documentation describes decision trees as a non-parametric supervised learning method used for both classification and regression.[2] Non-parametric means the model has no fixed number of parameters chosen in advance. The tree grows as large as the data and its limits allow.
The prediction surface looks like a staircase. Every row that lands in the same leaf gets the same output, which is why the documentation calls a tree a piecewise constant approximation.[2] A classification leaf outputs its majority class, or its class proportions if you ask for a probability. A regression leaf outputs the mean target of the training rows that reached it.
The standard algorithm is CART (classification and regression trees), from the 1984 book of that name by Breiman, Friedman, Olshen and Stone. CART grows the tree from the top down. At each node it tries every feature and every candidate threshold, measures how much each split would reduce impurity, takes the best split, and then repeats inside each child.
Why not search for the best tree overall? Because that search is out of reach. Learning an optimal tree is NP-complete under several definitions of optimality. NP-complete names a class of problems for which no known algorithm finishes in time that grows only polynomially with the size of the input. Practical learners therefore use greedy heuristics that make the locally best choice at each node.[2] Greedy means the algorithm never looks ahead. It never asks whether a weaker split now would allow a much better split one level down.
For classification, the usual impurity measure is Gini impurity. Suppose a node's K classes appear in proportions p1, ..., pK. Then Gini = 1 - Σ pk2, the probability that two rows drawn at random from the node, with replacement, belong to different classes. A pure node scores 0, and a 50/50 two-class node scores 0.5. The alternative is entropy, H = -Σ pk log2 pk. The drop in entropy produced by a split is called information gain. Regression trees usually split on the reduction in squared error instead: a split is good when the rows in each child sit close to that child's mean.
Here is a worked example. A node holds 10 customers: 6 churned and 4 stayed. Its Gini is 1 - (0.62 + 0.42) = 1 - (0.36 + 0.16) = 0.48. Two candidate splits are on offer.
| Candidate split | Left child | Right child | Weighted Gini | Impurity decrease |
|---|---|---|---|---|
| Contract is month-to-month | 5 rows: 5 churn, 0 stay. Gini 0 | 5 rows: 1 churn, 4 stay. Gini 1 - (0.04 + 0.64) = 0.32 | 0.5 × 0 + 0.5 × 0.32 = 0.16 | 0.48 - 0.16 = 0.32 |
| Tenure under 12 months | 6 rows: 4 churn, 2 stay. Gini 1 - (0.444 + 0.111) = 0.444 | 4 rows: 2 churn, 2 stay. Gini 0.5 | 0.6 × 0.444 + 0.4 × 0.5 = 0.467 | 0.48 - 0.467 = 0.013 |
Each child's Gini is weighted by its share of the parent's rows, because purifying 9 rows matters more than purifying 1. The contract split reduces impurity by 0.32 and the tenure split by only 0.013, so CART takes the contract split. Remember these two rows. A random forest will later reverse this choice on purpose.
You can print a fitted tree as rules: scikit-learn's export_text function writes a tree in a compact text format. The output below is illustrative, with invented feature names and thresholds, but it has the shape you will see.
|--- contract_month_to_month <= 0.50
| |--- monthly_charge <= 70.25
| | |--- class: 0
| |--- monthly_charge > 70.25
| | |--- class: 1
|--- contract_month_to_month > 0.50
| |--- tenure_months <= 11.50
| | |--- class: 1
| |--- tenure_months > 11.50
| | |--- class: 0
A 0/1 flag is split at 0.50, which simply means "flag off" on the left and "flag on" on the right. Each line deeper in the listing is one level deeper in the tree.
So what?: a tree is a greedy stack of questions, each chosen to cut impurity as much as possible at that node. Its readable structure is its main strength. Its greediness and its staircase shape cause every weakness that follows.
Bug 1: reading a perfect training score as success
Why did the churn tree score 1.000? Because nothing stopped it. With no depth limit, CART keeps splitting until every leaf is pure or holds a single row. Cornell's CS3780 notes say that a tree grown to maximum depth can drive training error to zero whenever the examples have distinct feature vectors, and that such a tree often overfits badly.[3] A perfect training score from an unrestricted tree only shows that no two rows with different labels had identical features. The validation score of 0.712 is the honest number.
In the bias-variance language of Lesson 12, a full-depth tree has low bias, because its staircase can bend to fit almost any pattern. It has high variance, because its shape depends heavily on which rows it happened to see. Small changes in the data can produce a completely different tree. Retrain the churn tree on a different 90 percent of the rows and the root split may survive while the lower levels change completely. Each lower split is chosen from fewer rows, so noise in those rows decides between candidates that are nearly tied.
Check the analyst's explanation, an unrepresentative validation split, once before you dismiss it. If the validation rows come from a later month or a different region, distribution shift is possible, and Lesson 13 covers drift. But a fall from 1.000 to 0.712 on a random split is the classic signature of overfitting. The fix is to constrain the tree or average many trees, not to blame the data.
The standard constraints are pruning, a minimum number of samples at a leaf, and a maximum depth. The table gives the scikit-learn names, because those are the ones you will meet in code.
| Parameter | What it limits | Effect of making it stricter |
|---|---|---|
| max_depth | Number of question levels from root to leaf | Fewer, larger leaves; less variance, more bias |
| min_samples_split | Rows a node needs before it may split | Small nodes stop splitting, so leaves cannot chase a few rows |
| min_samples_leaf | Rows each child must keep after a split | No leaf can rest on one or two rows |
| max_leaf_nodes | Total number of leaves | Caps complexity regardless of shape |
| ccp_alpha | Cost-complexity pruning strength | Cuts branches that do not earn their extra leaves |
| class_weight | How much each class counts in impurity | Stops a majority class dominating the splits |
Cost-complexity pruning needs a formula, because it is the one control that looks at the whole tree. First grow the tree fully. Then score each pruned version T by Rα(T) = R(T) + α|T|. Here R(T) is the total training impurity or error of the leaves, |T| is the number of leaves, and α (alpha) is the price charged for each leaf. At α = 0 the full tree wins. As α rises, the branches whose impurity reduction does not pay for their extra leaves are cut, weakest first. You choose α by cross-validation, the same way you would choose a ridge penalty.
Four traits of a single tree to know
- It cannot extrapolate. Predictions are flat steps, so the scikit-learn documentation states plainly that trees are not good at extrapolation.[2] Picture a rent tree trained on apartments up to 120 square meters. A 200 square meter penthouse falls into the largest-size leaf and gets that leaf's mean rent, as if size stopped mattering at 120. A linear regression would continue the trend. The same flat line appears when a tree forecasts a series that keeps rising beyond its training range. Every tree ensemble in this lesson inherits this limit, because averaging or adding staircases still gives a staircase.
- A dominant class skews it. Tree learners build biased trees when some classes dominate. With 3 percent fraud, most leaves can predict "not fraud" and still reach about 97 percent accuracy. Use class_weight="balanced" or resampling, such as SMOTE (Synthetic Minority Oversampling Technique), and judge the model with recall, precision or the Matthews Correlation Coefficient (MCC) rather than accuracy.
- Greedy search misses interactions that hide at the root. Exclusive OR (XOR), parity and multiplexer problems are classic concepts trees struggle to express. Suppose churn happens when exactly one of two flags is on. Split on either flag alone and each child is still 50/50, so the impurity decrease is zero. A greedy learner sees no reason to make that split, even though the pair of splits together would separate the classes perfectly.
- It needs little scaling, but categories still need encoding. This trait helps you. A split asks only whether a value is above a threshold, so rescaling a feature, or applying any other transformation that keeps the order of values, leaves the tree unchanged. Features can sit on different scales and in different units, so standardizing inputs for a tree is wasted effort. Encoding is a different matter. scikit-learn's decision tree and random forest estimators expect numeric arrays, so a text category such as contract type must still be encoded, for example one-hot or ordinal, before fitting. Native categorical support differs across libraries and estimators, so check the documentation for the version you run.
So what?: treat a near-perfect training score from a deep tree as an alarm. Then choose between restricting the tree (depth, leaf size, pruning) when you need one readable model, and averaging many trees when accuracy matters more.
Bug 2: deeper and boosted are opposite treatments
The note's plan, "grow it deeper, then boost it," mixes two treatments meant for two different problems. Cornell's notes sum up the split in two lines: bagging mainly targets variance, and boosting mainly targets bias.[3] A tree that scores 1.000 in training and 0.712 in validation has a variance problem. Growing it deeper raises variance further. Boosting is designed to reduce bias, and the deep tree has almost no bias left to reduce.
| Training score | Validation score | Diagnosis | Tree-based remedy |
|---|---|---|---|
| 1.00 | 0.71 | High variance: memorizing the training rows | Limit depth or leaf size, prune, or average trees with bagging or a random forest |
| 0.74 | 0.73 | High bias: the model is too simple | Allow deeper trees, or boost many shallow trees |
| 0.93 | 0.89 | Reasonable fit with a small gap | Tune within the method; confirm on an untouched test set |
An ensemble method combines the predictions of several base models with the aim of generalizing better, and being more robust, than a single model would. It is a design goal, not a guarantee: an ensemble of badly chosen members can still disappoint. The two families in the objective differ in how they build their members. Bagging trains the members independently on resampled data and averages them. Boosting trains them in sequence, with each one correcting the errors of those before it.
Bootstrap aggregation (bagging): many trees from one dataset
Start with a thought experiment. If you could draw m independent training sets, fit one deep tree to each and average their predictions, you would reduce variance by a factor of m, the same way averaging m independent noisy measurements does. The catch is that you have only one dataset.
Bootstrap aggregation, or bagging, introduced by Leo Breiman in 1996, fakes those extra datasets. For each member model, build a new dataset of the same size n by sampling rows from the original with replacement, uniformly at random.[3] Fit the base learner to that bootstrap sample. Repeat m times, then aggregate: average the predictions for regression, and vote or average class probabilities for classification. Some variants draw random subsamples without replacement instead, but the bootstrap is the classic form.
Sampling with replacement means some rows appear twice or more and others not at all. How many are left out? The chance that a given row is missed on a single draw is 1 - 1/n, so the chance it is missed on all n draws is (1 - 1/n)n. For n = 10 that is 0.910 ≈ 0.349. As n grows, the value approaches e-1 ≈ 0.368. So each bootstrap sample contains about 63.2 percent of the distinct rows, and about 36.8 percent are out-of-bag (OOB) for that tree.
A tiny example with n = 5: the draw 3, 1, 3, 5, 5 contains row 3 twice and row 5 twice, and rows 2 and 4 are out-of-bag. Those two rows played no part in fitting that tree, so the tree can be tested on them.
That gives you a free validation estimate. For each row, collect predictions only from the trees that did not see it, then score those predictions. Cornell's notes describe this OOB error as acting like a built-in validation estimate, because each point is evaluated only by models trained without it.[3] In scikit-learn, setting oob_score=True on a forest computes this estimate and stores it in the oob_score_ attribute. OOB is most useful when data are too scarce to set aside a holdout. It is not a substitute for a time-ordered split when the data have a time order, because bootstrap rows ignore time.
Averaging has a limit, and it is the most important formula in this section. Suppose each tree's prediction has variance σ2, and every pair of trees has correlation ρ (rho). The variance of the average of m trees is ρσ2 + (1 - ρ)σ2/m. This is a standard result, and Cornell's notes state the idea in words: the clean 1/m reduction depends on independence, and correlation weakens it.[3] Work two cases with σ2 = 1 and m = 100 trees.
| Correlation between trees | Calculation | Variance of the average |
|---|---|---|
| ρ = 0 (independent) | 0 + 1 × 1/100 | 0.010 |
| ρ = 0.6 | 0.6 + 0.4 × 1/100 | 0.604 |
With correlated trees, the second term shrinks as you add trees, but the first term, ρσ2, does not change at all. At ρ = 0.6, a million trees still leave a variance above 0.6. Adding trees cannot beat correlation. Only making the trees less alike can.
Two practical points follow. First, bagging pays off for unstable, high-variance learners such as deep trees, and barely helps stable ones. Bag a linear regression and the models fit to different bootstrap samples come out nearly identical, so there is little variance to average away. Second, the members do not depend on each other, so they can be trained independently and in parallel. Adding more trees to a bagged ensemble does not cause overfitting the way deepening a single tree does. Validation error falls and then levels off, so you choose the number of trees for compute cost rather than as a regularizer.
Random forest: bagging plus a random choice of features
Cornell's notes define a random forest as bagging applied to full-depth decision trees, with one extra randomization step.[3] Before each split in each tree, the algorithm draws a random subset of k of the d features, and it searches for the best split using only those k features.
Why add that step? Because of the ρσ2 term. If one feature is very strong, plain bagging may split on that same feature near the root of almost every tree.[3] The trees then look alike, make the same mistakes, and correlate highly. Go back to the 10-customer node. A bagged tree that sees the contract feature will choose it every time, because it reduces impurity by 0.32. Now suppose that, at this node, the forest's random draw offers only tenure and two weak features. The tree must split on tenure, which reduces impurity by only 0.013. That single tree is worse, and that is deliberate. Across 500 trees, many grow their structure around tenure, monthly charge and other features, so their errors differ. The correlation ρ falls, and the average improves even though each member is weaker.
A common default for classification is k = √d, the square root of the number of features. With 16 features, each split considers 4. In practice forests are usually not very sensitive to the exact number of trees or the exact k, which is one reason they work so well out of the box. Setting k = d switches the extra step off and turns the forest back into bagged trees.
Three scikit-learn details matter in practice. By default the trees are fully grown and unpruned, so they can become very large and use a lot of memory on big data sets. The forest combines its trees by averaging their predicted probabilities rather than counting single-class votes, which differs from Breiman's original 2001 description.[4] And because features are randomly permuted at each split, results can vary between runs unless you fix random_state. A typical setup, shown here as an example, looks like this:
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(
n_estimators=500, # number of trees
max_features="sqrt", # k = square root of d at each split
min_samples_leaf=1, # fully grown trees
oob_score=True, # out-of-bag estimate of accuracy
n_jobs=-1, # train trees on all processor cores
random_state=42) # reproducible bootstrap and feature draws
forest.fit(X_train, y_train)
print(forest.oob_score_)
Expect a forest's training score to sit near 1.0. Each training row was in the bag for about 63 percent of the trees, and those deep trees memorized it. That is not the alarm it was for the single tree. Judge the forest on its OOB or validation score, never on its training score.
A close relative, Extra-Trees (extremely randomized trees), goes one step further and draws split thresholds at random as well as features. It reduces correlation even more, at some cost in bias.
So what?: a random forest is bagging plus random feature subsets at every split. The feature sampling exists to lower the correlation between trees, which is the one thing more trees cannot fix.
Bug 3: why boosting cannot rescue a deep tree
Boosting begins from a theoretical question. A weak learner is a model that does only slightly better than random guessing.[5] Kearns and Valiant asked in the late 1980s whether many weak learners could be combined into one strong learner, and Schapire showed in 1990 that they can. Boosting trains its learners one after another, and each new learner concentrates on what the current ensemble still gets wrong.
The first practical version, AdaBoost (adaptive boosting, Freund and Schapire), works on the training rows' weights. It raises the weight of every example the current model gets wrong and lowers the weight of those it gets right. The next weak learner, often a stump (a tree with one split), is fit to the reweighted data, and the final prediction is a weighted vote in which more accurate learners get bigger votes.
Now the debugging point. Boosting works by finding leftover error on the training data. A fully grown tree leaves none, because its training error is already zero, so there is nothing for the second learner to correct. Boosting a deep tree adds cost and no learning. Boosting is used with shallow trees: scikit-learn contrasts random forests, which rely on deep trees that overfit individually, with boosting models, which build shallow trees that underfit individually and are faster to fit.[4] Boosting also has a price bagging does not. Each round depends on the one before, so the rounds cannot run in parallel, and ensembles with many trees are slow to train.
Gradient boosting: each tree fits the negative gradient
Gradient boosting generalizes the idea from reweighting rows to minimizing any differentiable loss. The name comes from Jerome Friedman's 2001 paper "Greedy Function Approximation: A Gradient Boosting Machine." The model is a sum of trees, FM(x) = F0(x) + ν h1(x) + ... + ν hM(x), where F0 is a constant starting guess, each hm is a small regression tree, and ν (nu) is the learning rate, also called shrinkage. Learning all the trees at once is intractable, so the XGBoost tutorial describes an additive strategy instead: keep what has been learned and add one new tree at a time.[6]
Which tree gets added? The one that points the predictions downhill on the loss. A UC San Diego lecture states it directly: each tree is fitted to best approximate the negative gradient.[7] Boosting is gradient descent, but the steps are taken in the space of predictions rather than in a parameter vector. For squared loss, L = ½(y - F)2. Its derivative with respect to the prediction F is -(y - F), so the negative gradient is y - F, which is the ordinary residual. For binary log loss, with F on the log-odds scale and p the predicted probability, the negative gradient is y - p. Either way, each new tree is fit to how far each row still is from its target, measured in the units of that loss.
Work one round by hand. Four apartments (fictional) have monthly rents of 1000, 1200, 1800 and 2000 dollars. Start from the mean, F0 = 1500. The first tree is a stump that splits on size at 67.5 square meters. Each leaf outputs the mean residual of its rows: -400 for the two small apartments and +400 for the two large ones.
| Apartment | Size (square meters) | Rent y | Residual y - F0 | Stump output | F1 with ν = 0.1 | F1 with ν = 1.0 |
|---|---|---|---|---|---|---|
| A | 40 | 1000 | -500 | -400 | 1460 | 1100 |
| B | 55 | 1200 | -300 | -400 | 1460 | 1100 |
| C | 80 | 1800 | +300 | +400 | 1540 | 1900 |
| D | 95 | 2000 | +500 | +400 | 1540 | 1900 |
Check the sum of squared errors. Before the round it is 5002 + 3002 + 3002 + 5002 = 680,000. With ν = 0.1 the new residuals are -460, -260, +260 and +460, so the sum becomes 2 × (211,600 + 67,600) = 558,400, a drop of about 18 percent. With ν = 1.0 the residuals become -100, +100, -100 and +100, so the sum is 40,000, a drop of about 94 percent in one round.
Now the flip. On training data, ν = 1.0 looks far better. On real, noisy data it usually generalizes worse. A full-size step lets each tree absorb that round's residuals completely, noise included. Small steps make the model build its fit from many trees, each correcting a little, and that averages out the noise. The cost is that a smaller ν needs more trees. Gradient boosting can overfit if rounds keep coming, which forests do not. So the number of rounds is itself a regularizer: hold out a validation set, watch the validation loss each round, and stop when it stops improving. This is called early stopping.
Friedman followed up in 2002 with a paper titled "Stochastic gradient boosting." Its idea, now standard, is row subsampling: each tree is fit to a random fraction of the rows, which speeds training and adds a regularizing effect, much as bootstrap samples do in bagging. For large tabular data, scikit-learn's histogram-based gradient boosting estimators first bin each feature into a limited number of integer bins, which sharply cuts the number of candidate split points. Expect to tune more here than with a forest, because several gradient boosting hyperparameters matter at once: the learning rate, the number of rounds, tree depth and the subsample fraction.
So what?: gradient boosting adds shallow trees one at a time, each fit to the negative gradient of the loss (the residual, for squared error). The learning rate and the number of rounds trade off together, and early stopping on a validation set decides when to stop.
XGBoost: regularized gradient boosting built for scale
XGBoost, short for Extreme Gradient Boosting, is not a new kind of model. Its documentation describes an optimized, distributed gradient boosting library designed to be highly efficient, flexible and portable.[8] It implements what is also known as GBDT (gradient boosted decision trees) or GBM (gradient boosting machine). What sets it apart is a regularized training objective and heavy systems engineering.
The objective first. The XGBoost tutorial insists that the objective always contains both training loss and regularization.[6] It is written obj = Σi l(yi, ŷi) + Σk Ω(fk), where l is the loss for row i and Ω (omega) is the complexity of tree fk. In XGBoost's formulation, Ω(f) = γT + ½λ Σj wj2. T is the number of leaves, wj is the score (weight) in leaf j, γ (gamma) is a charge for each leaf, and λ (lambda) is an L2 penalty, meaning a charge on the sum of squared leaf scores. A plain gradient boosting machine has no such term in the objective. It relies on depth limits, shrinkage and early stopping.
XGBoost also uses a second-order (Newton) approximation of the loss. For each row it computes the gradient gi, the first derivative of the loss with respect to the current prediction, and the Hessian hi, the second derivative. Summing these over the rows in leaf j gives Gj and Hj, and the best score for that leaf is wj* = -Gj / (Hj + λ). Apply this to the two small apartments above. With squared loss l = ½(y - ŷ)2, the gradient is ŷ - y and the Hessian is 1. At ŷ = 1500, the gradients are 500 and 300, so G = 800 and H = 2.
| λ | Calculation | Leaf score w* |
|---|---|---|
| 0 | -800 / (2 + 0) | -400 (exactly the mean residual) |
| 1 | -800 / (2 + 1) | -266.7 |
| 10 | -800 / (2 + 10) | -66.7 |
With λ = 0, XGBoost reproduces ordinary gradient boosting's leaf. As λ rises, leaf scores shrink toward zero, and a leaf holding only a few rows (small H) shrinks the most. The γ term works on structure instead: a split is kept only if its loss reduction exceeds γ, so larger γ means fewer, more conservative splits. Training still adds one split at a time, because enumerating every possible tree structure is intractable.
Then the engineering. The documentation covers distributed training, with guides for environments such as Hadoop, Spark, Dask and Kubernetes. The parallel work happens inside each tree, in the search for the best split. The rounds themselves stay sequential. XGBoost supports histogram-based split finding like the scikit-learn estimators above, has GPU (Graphics Processing Unit) support, and handles missing values natively by learning which direction missing values should go at each split. The documentation read for this lesson was for version 3.4.2.[8] The project releases often, so check parameter names against the version you actually run.
| Parameter | What it controls | Raise it when |
|---|---|---|
| n_estimators | Maximum boosting rounds | Learning rate is small; pair with early stopping |
| learning_rate (eta) | Shrinkage ν on each tree | Rarely; lower it to generalize better, at the cost of more rounds |
| max_depth | Depth of each tree; interaction order | Validation shows underfitting (high bias) |
| subsample | Fraction of rows per tree | Lower it to fight overfitting |
| colsample_bytree | Fraction of features per tree | Lower it to decorrelate trees, as in a forest |
| reg_lambda (lambda) | L2 penalty: a charge on squared leaf scores | Leaves built on few rows give extreme scores |
| reg_alpha (alpha) | L1 penalty: a charge on absolute leaf scores | You want many leaf scores pushed to exactly zero |
| gamma (min_split_loss) | Minimum loss reduction to keep a split | Trees contain many tiny, low-value splits |
| early_stopping_rounds | Rounds without validation improvement before stopping | Always set it when you have a validation set |
An example setup:
import xgboost as xgb
model = xgb.XGBClassifier(
n_estimators=3000, # upper limit; early stopping picks the real number
learning_rate=0.05,
max_depth=4, # shallow trees: boosting reduces bias
subsample=0.8,
colsample_bytree=0.8,
reg_lambda=1.0,
eval_metric="auc",
early_stopping_rounds=50)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)])
print(model.best_iteration)
One subtle point closes the section. The XGBoost tutorial observes that random forests and boosted trees are really the same models, sums of trees, and that the difference lies in how they are trained.[6] XGBoost can even train random forests. So "uses tree ensembles" never separates the two in a question. The training procedure does: independent trees on bootstrap samples, or sequential trees fit to gradients.
So what?: choose XGBoost when a scenario calls for gradient boosting with explicit regularization (λ, α and γ on the trees), native handling of missing values, and speed or distribution across large tabular data.
Bug 4: the root split is not a ranking of drivers
The note's last claim was that contract type is the main driver because the tree splits on it first. The root split is the single best greedy cut on the full training set. It is not a measure of a feature's total contribution, and a correlated feature that narrowly lost at the root may matter just as much. It is also not causal. Contract type may stand in for price sensitivity that the data never recorded.
Ensembles make this question both harder and more important. A boosting model can contain hundreds of regression trees, so you cannot interpret it by inspecting the trees one at a time. Two summaries are common.
- Impurity-based importance (mean decrease in impurity, MDI) adds up each feature's impurity reductions across all splits and trees. It is computed on training data, so it can reward features the trees used to memorize noise. It tends to favor features with many distinct values, such as an ID-like column.
- Permutation importance shuffles one feature's values in held-out data and measures how much the score drops. It reflects what the model needs to predict well on new rows. When two features are correlated, shuffling one leaves the other available, so both can look less important than they are.
Report permutation importance on validation data when a stakeholder asks what drives the prediction, and say clearly that it describes the model, not the causes in the world (Lesson 11 covers presenting this).
Bagging, random forest, gradient boosting and XGBoost compared
| Property | Bagging | Random forest | Gradient boosting | XGBoost |
|---|---|---|---|---|
| Main error targeted | Variance | Variance, more strongly | Bias | Bias, with built-in regularization |
| Base trees | Deep, unpruned | Deep, unpruned | Shallow (stumps to a few levels deep) | Shallow, with leaf-score penalties |
| Row sampling | Bootstrap per tree | Bootstrap per tree | None, or a subsample in stochastic gradient boosting | subsample per tree |
| Feature sampling | None (all features at every split) | Random k features at every split | Usually none | colsample_bytree and related options |
| Training order | Parallel, independent | Parallel, independent | Sequential | Sequential rounds, parallel split search |
| Combining rule | Average or vote | Average or vote | Weighted sum ν × each tree | Weighted sum ν × each tree |
| Effect of more trees | Error levels off | Error levels off | Can overfit; use early stopping | Can overfit; use early stopping |
| Built-in validation | Out-of-bag estimate | Out-of-bag estimate | Validation set for early stopping | eval_set for early stopping |
| Tuning effort | Low | Low | High | High |
Read the table by row. The training-order row explains why forests scale easily across processor cores and boosting does not. The effect-of-more-trees row explains why you can set a forest's tree count generously but must early-stop a booster. The base-trees row is the bias-variance logic in one line: average deep trees to remove variance, and add shallow trees to remove bias.
Exam cues: what the stem says and what it points to
| Words in the question | Points to | Commonly confused with |
|---|---|---|
| Single tree, training near 100 percent, validation much lower | Overfitting (high variance): limit max_depth or min_samples_leaf, prune, or use a random forest | Boosting, which targets bias |
| Small changes in the data produce a different tree | Instability; fix by bagging or a random forest | Data drift, which is a change over time in production |
| Rules a regulator or manager can read | A single shallow decision tree | Random forest, which is accurate but hard to read |
| Sampling with replacement, average many models | Bootstrap aggregation (bagging) | Cross-validation, which partitions rows without replacement |
| Estimate generalization without a holdout set | Out-of-bag score | Training score |
| One dominant feature makes the trees look alike | Random forest feature subsampling (max_features) | Adding more bagged trees, which cannot fix correlation |
| Weak learners, sequential, misclassified rows reweighted | AdaBoost | Gradient boosting, which fits gradients rather than reweighting |
| Each tree fits the residuals or the negative gradient | Gradient boosting | Bagging, which fits each tree to the original targets |
| Validation loss rises after some round | Early stopping, or a lower learning rate with more rounds | Growing deeper trees |
| L1 or L2 penalties on leaf scores, minimum split loss, native missing values, distributed | XGBoost | Plain gradient boosting without a regularized objective |
| Predictions flatten beyond the training range | Trees cannot extrapolate | Underfitting from too few trees |
Common misconceptions
- "A random forest is just bagged trees." Bagging resamples rows. A random forest also restricts each split to a random subset of features, and that step is what lowers the correlation between trees. With max_features equal to the number of features, a forest is plain bagging.
- "More trees make a forest overfit." Adding trees to a forest or a bagged ensemble makes validation error level off, not rise. Boosting is the family where more rounds can overfit, which is why boosters need early stopping.
- "Boosting a strong, deep tree gives an even stronger model." A deep tree leaves no training error to correct, so later rounds learn nothing useful. Boosting works with shallow, high-bias trees.
- "Tree models need standardized features." Splits are thresholds on the order of values, so any transformation that keeps the order leaves a tree unchanged. Scaling matters for distance-based and gradient-trained linear models, not for trees. Categorical text values still need encoding in scikit-learn.
- "XGBoost is a different algorithm from gradient boosting." XGBoost is a gradient boosting library. Its differences are a regularized objective, second-order optimization and engineering for speed and scale.
- "The root split shows the most important feature." It shows the best greedy cut on the full training set. Use permutation importance on held-out data, and do not read causation into either.
The short version
- CART grows a tree greedily, choosing at each node the split with the largest weighted impurity decrease. Gini impurity is 1 - Σ pk2, and a 6/4 node scores 0.48.
- An unrestricted tree can reach zero training error. A large gap between training and validation scores means high variance, which you treat with max_depth, min_samples_leaf, cost-complexity pruning (ccp_alpha) or averaging.
- Trees predict piecewise constant values, so they and their ensembles cannot extrapolate beyond the range of the training targets.
- Bagging fits each model to a bootstrap sample of size n drawn with replacement. About 63.2 percent of the distinct rows land in each sample, and the other 36.8 percent are out-of-bag and give a built-in validation estimate.
- Averaging m trees with correlation ρ leaves variance ρσ2 + (1 - ρ)σ2/m. More trees shrink only the second term, and random feature subsets at each split shrink ρ.
- A random forest is bagging of deep trees plus random feature subsets at each split, commonly √d features for classification. Its trees train in parallel, and adding more of them does not overfit.
- Boosting trains shallow trees in sequence to reduce bias. AdaBoost reweights misclassified rows, and gradient boosting fits each tree to the negative gradient of the loss, which is the residual for squared error.
- A smaller learning rate generalizes better but needs more rounds. Choose the number of rounds with early stopping on a validation set.
- XGBoost (Extreme Gradient Boosting) adds the penalty γT + ½λΣw2 to the loss, sets leaf scores to -G/(H + λ), handles missing values natively, and distributes training across large data.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn developers. (n.d.). 1.10. Decision Trees. scikit-learn.org
- Cornell University, CS3780. (2026). Bagging. cs.cornell.edu
- scikit-learn developers. (n.d.). 1.11. Ensembles: Gradient boosting, random forests, bagging, voting, stacking. scikit-learn.org
- University of Washington. (2024). CSE/STAT 416 Lecture 9. courses.cs.washington.edu
- XGBoost developers. (n.d.). Introduction to Boosted Trees. xgboost.readthedocs.io
- Yu-Xiang Wang. (2025). Lecture 13: Boosting. UC San Diego, DSC 240. cseweb.ucsd.edu
- XGBoost developers. (n.d.). XGBoost Documentation. xgboost.readthedocs.io
- Key terms
- Decision tree
- A non-parametric supervised model that predicts by passing a row through a sequence of threshold questions on its features; each leaf outputs a constant, such as a class or a mean value.
- Gini impurity
- A node impurity measure equal to 1 minus the sum of squared class proportions; 0 for a pure node and 0.5 for an even two-class node. CART splits where the weighted Gini of the children drops most.
- Cost-complexity pruning
- Pruning a fully grown tree by minimizing total leaf impurity plus alpha times the number of leaves, so branches that do not justify their extra leaves are removed; alpha is chosen by cross-validation.
- Bootstrap aggregation (bagging)
- An ensemble method that trains each model on a sample of n rows drawn with replacement from the training set and averages or votes their predictions, mainly reducing variance.
- Out-of-bag (OOB) estimate
- A validation score for a bagged ensemble computed by predicting each training row only with the models whose bootstrap samples did not include it; roughly 36.8 percent of rows are out-of-bag per model.
- Random forest
- Bagging applied to deep decision trees, with a random subset of features considered at each split so that the trees are less correlated and their average has lower variance.
- Gradient boosting
- An additive ensemble that trains shallow trees one after another, each fit to the negative gradient of the loss at the current predictions (the residuals for squared error), scaled by a learning rate.
- Learning rate (shrinkage)
- In boosting, the factor that multiplies each new tree's output before it is added; smaller values usually generalize better but require more boosting rounds.
- Early stopping
- Ending boosting when a validation metric has not improved for a set number of rounds, so the number of trees acts as a regularizer.
- XGBoost
- Extreme Gradient Boosting: a gradient boosting library whose objective adds a penalty on the number of leaves and on the leaf scores, using second-order gradients, native missing-value handling and distributed training.
Deep Learning Concepts
- Explain how artificial neurons, activation functions and the input, hidden, pooling and output layer types combine into a network, and why non-linearity is required.
- Trace backpropagation through a small network and tell it apart from the optimizers (stochastic gradient descent, mini-batch, momentum, root mean square propagation and Adam) and the learning-rate schedulers that use its gradients.
- Choose among dropout, batch normalization and early stopping, and recognize vanishing gradients, exploding gradients and dead ReLU (rectified linear unit) units from their symptoms.
- Match convolutional and recurrent networks, long short-term memory, transformers, autoencoders, generative adversarial networks, one-shot, few-shot and zero-shot learning, and PyTorch, TensorFlow/Keras and automated machine learning to the problems they suit.
A claims desk, 4,212 photos and one artificial neuron
Harborline Mutual, an invented mid-sized car insurer, opens one Monday with 4,212 claim photos and 1,900 free-text adjuster notes waiting for review. The company and everything that happens to it in this lesson are fictional. Its lead data scientist, Dana, already has a gradient-boosted model that scores claims from tabular fields such as policy age and repair estimate. That model cannot look at a photo or read a sentence. To do either, Dana needs deep learning, and by the end of the project she will have used every item in objective 3.4.
Why do neural networks dominate this kind of work now, when many of the ideas are decades old? Dive into Deep Learning, the open textbook by Zhang, Lipton, Li and Smola, tabulates datasets, memory and computing power by decade. It observes that computing power has grown faster than the datasets themselves.[1] With computing cycles to spare, the authors argue, the sweet spot in machine learning moved from generalized linear models and kernel methods to deep neural networks.[1] The same book dates convolutional networks to LeCun and colleagues in 1998 and long short-term memory to Hochreiter and Schmidhuber in 1997.[1] The ideas were waiting for the hardware.
Exam objectives: 3.4 Explain concepts related to deep learning.[2] The objective lists five groups of ideas:
- Network architecture: the perceptron, the artificial neuron, the multilayer perceptron, the activation functions rectified linear unit (ReLU), sigmoid, hyperbolic tangent (tanh) and softmax, and the input, hidden, pooling and output layer types.
- Training the network: backpropagation, the optimizers (stochastic gradient descent, mini-batch, momentum, root mean square propagation (RMSprop) and Adam) and learning-rate schedulers.
- Regularization methods: dropout, batch normalization and early stopping.
- Learning from little data: one-shot, few-shot and zero-shot learning.
- Model types and tools: convolutional neural networks (CNNs), recurrent neural networks (RNNs), long short-term memory (LSTM), generative adversarial networks (GANs), autoencoders, transformers, PyTorch, TensorFlow/Keras and automated machine learning (AutoML).
The verb is "explain". Expect questions that describe a symptom or a need and ask which concept fits it.
The artificial neuron: a weighted sum, then a bend
Dana starts small. Before she touches any photos, she wants to predict whether a claim is a likely total loss from two numbers. The first, x1, is the repair estimate as a fraction of the car's value. The second, x2, is 1 if an airbag deployed and 0 if not.
An artificial neuron is the unit every network is built from, and it does two things. First it computes a weighted sum of its inputs plus a constant called the bias: z = w1x1 + w2x2 + b. Then it passes z through an activation function f, and f(z) is its output a. Stanford's CS231n course notes describe the same unit: each neuron takes inputs, computes a dot product, and may then apply a non-linearity.[3] The weights say how much each input matters. The bias shifts the threshold. Training is the search for good weights and biases.
A worked example with fictional numbers. Let w1 = 4.0, w2 = 2.0 and b = -4.5. A claim with x1 = 0.9 and x2 = 1 gives:
- Weighted sum: z = 4.0 × 0.9 + 2.0 × 1 - 4.5 = 3.6 + 2.0 - 4.5 = 1.1.
- With a step activation, which outputs 1 if z ≥ 0 and 0 otherwise: a = 1, meaning "total loss".
- With a sigmoid activation: a = 1 / (1 + e-1.1) = 1 / (1 + 0.333) = 0.750, which reads as a 75 percent score.
Change one input and the decision flips. Take the same car with no airbag deployment, so x2 = 0. Now z = 3.6 - 4.5 = -0.9. The step neuron outputs 0, and the sigmoid gives 1 / (1 + e0.9) = 1 / (1 + 2.460) = 0.289. So a neuron is a linear score followed by a function that squashes it or thresholds it. Nothing more.
The perceptron and the line it cannot bend
Frank Rosenblatt introduced the perceptron in 1958. It is an artificial neuron with a step activation and a simple learning rule. You show it each training example in turn. If the prediction ŷ is right, nothing changes. If it is wrong, each weight moves by wi ← wi + η(y - ŷ)xi and the bias moves by b ← b + η(y - ŷ). Here η (eta) is the learning rate, a small positive number that sets the size of each nudge.
Here is one update worked through. Start with w1 = w2 = b = 0 and η = 0.1. The example x = (1, 0) has label y = 0. Then z = 0, the step gives ŷ = 1, and the error y - ŷ is -1. The updates are:
- w1 ← 0 + 0.1 × (-1) × 1 = -0.1
- w2 ← 0 + 0.1 × (-1) × 0 = 0
- b ← 0 + 0.1 × (-1) = -0.1
The next time it sees this example, z = -0.2 and the output is a correct 0. Notice that w2 did not move. An input of 0 contributed nothing to the mistake, so its weight gets no blame.
Suppose the two classes can be separated by a straight line, or by a flat plane when there are more inputs. Then this rule is guaranteed to find a separating line after a finite number of updates. If no such line exists, it never settles. Dana's fraud team hands her exactly that kind of pattern. In their (fictional) experience, a claim is suspicious when exactly one of two flags is set: the claim was filed within 30 days of the policy start, or it was filed with no police report. Both flags together usually means a legitimate new driver after a minor scrape, and neither flag is ordinary. That is the exclusive-or (XOR) pattern:
| New policy (x1) | No police report (x2) | Suspicious (y) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
No single perceptron can fit this table, and the proof is short:
- The row (0, 0) → 0 needs b < 0.
- The rows (1, 0) → 1 and (0, 1) → 1 need w1 + b ≥ 0 and w2 + b ≥ 0.
- Adding those two gives w1 + w2 + 2b ≥ 0, so w1 + w2 + b ≥ -b. By step 1, -b is positive.
- So the row (1, 1) would output 1, not 0. That contradicts the table.
Google's Machine Learning Crash Course makes the same point with a picture: two colors of dots that no linear function can cleanly separate.[4]
The multilayer perceptron: input, hidden and output layers
The fix is to stack neurons. A multilayer perceptron (MLP) arranges neurons in layers. Every neuron in one layer feeds every neuron in the next. Signals flow only forward, from input to output, so an MLP is the standard example of a feed forward neural network (FFNN). Every MLP has three of the objective's layer types:
- Input layer. One slot per feature. It holds the data and does no computation, which is why people often leave it out when they count layers.
- Hidden layers. The layers between input and output. Their values never appear in the data, which is why they are called hidden. Each hidden neuron computes a weighted sum and an activation, so each layer builds new features from the outputs of the layer before.
- Output layer. Its size and activation match the task. A regression target such as repair cost gets one linear neuron. A yes-or-no label gets one sigmoid neuron. K mutually exclusive classes get K softmax neurons.
Here is XOR solved by hand with two hidden step neurons:
- h1 = step(x1 + x2 - 0.5) fires if at least one flag is set. This is OR.
- h2 = step(x1 + x2 - 1.5) fires only if both flags are set. This is AND.
- The output step(h1 - h2 - 0.5) means "at least one, but not both".
Check two rows. For (1, 1): h1 = 1 and h2 = 1, so the output is step(-0.5) = 0. For (1, 0): h1 = 1 and h2 = 0, so the output is step(0.5) = 1. The hidden layer created two new features, OR and AND. The output neuron then drew an ordinary straight line in that new feature space.
That is the whole reason hidden layers exist. Google's crash course puts it this way: during training, a neural network learns for itself the feature crosses that a linear model would need a person to engineer.[4] A network counts as deep when it has more than one hidden layer, which is the definition Google's crash course uses in its training guidance.[5]
The activation function is not decoration. Without it, each layer is a matrix multiplication plus a bias. Two such layers combine into W2(W1x + b1) + b2 = (W2W1)x + (W2b1 + b2), which is again a single linear layer. A hundred linear layers can represent no more than one.
The objective's fourth layer type, the pooling layer, does not appear in a plain MLP. It belongs to convolutional networks, where it shrinks an image-shaped grid of values. The convolutional section below works through it.
Worth holding on to: a neuron is a weighted sum plus a bias, passed through an activation, and one neuron can draw only one line. Hidden layers with non-linear activations let a network build its own features. Without the non-linearity, any stack of layers collapses into a single linear model.
Activation functions: ReLU, sigmoid, tanh and softmax
Dana's next choice is which activation function to use in each layer. Four are on the exam. In the table, z is the neuron's weighted sum and e ≈ 2.718 is the base of the natural logarithm.
The slope (derivative) column needs a word of explanation first. To train a network, you need each weight's gradient: the slope of the loss with respect to that weight, which says which way to nudge the weight and how hard. Training finds these gradients by passing an error signal backward through the network, and on the way back the signal is multiplied by each activation's slope. So an activation with a small slope weakens the signal. The backpropagation section below works this through step by step.
| Function | Formula | Output range | Slope (derivative) | Usual place | Main weakness |
|---|---|---|---|---|---|
| ReLU (rectified linear unit) | max(0, z) | 0 to infinity | 1 if z > 0, else 0 | Hidden layers; the default | A unit can "die" and output 0 for every input |
| Sigmoid | 1 / (1 + e-z) | 0 to 1 | σ(z)(1 - σ(z)), at most 0.25 | Binary or multi-label outputs; gates inside LSTMs | Saturates: slope near 0 when |z| is large |
| Tanh (hyperbolic tangent) | (ez - e-z) / (ez + e-z) | -1 to 1 | 1 - tanh2(z), at most 1 | Hidden states of RNNs; zero-centered hidden layers | Saturates like sigmoid, though less severely |
| Softmax | ezi / Σj ezj | Each 0 to 1; all sum to 1 | Depends on all the inputs together | Output layer for mutually exclusive classes | Overconfident when logits are large; wrong for multi-label tasks |
The rectified linear unit (ReLU) is the default for hidden layers. Its slope is exactly 1 wherever it is active, so it does not shrink the backward error signal. That guards against vanishing gradients, the problem in which the signal shrinks toward 0 before it reaches the early layers. Google recommends ReLU as a way to help prevent vanishing gradients.[5] Its weakness is the dead unit. If a ReLU's weighted sum falls below 0 for every input, it outputs 0, its slope is 0, and no gradient can reach its weights to pull it back.[5] Google's suggested remedy is a lower learning rate, so that one large update cannot push the unit permanently negative.[5] Variants such as leaky ReLU keep a small slope for negative z for the same reason.
The sigmoid function squashes any number into the range 0 to 1, so its output reads naturally as a probability. Its slope peaks at 0.25 when z = 0 and falls toward 0 in both tails. In a stack of ten sigmoid layers, the sigmoid slopes alone multiply the backward signal by at most 0.25 per layer, so by at most 0.2510 ≈ 0.00000095 in total. The layer weights also multiply the signal, on top of that factor, and unless they are large they cannot make up the loss. The early layers then barely learn. That arithmetic is why sigmoid fell out of favor for hidden layers.
The hyperbolic tangent (tanh) is a rescaled sigmoid, tanh(z) = 2σ(2z) - 1, with outputs from -1 to 1. Its outputs are centered on 0, so the next layer does not receive only positive inputs, and optimization tends to run more smoothly than with sigmoid. Its slope peaks at 1, but it still saturates when |z| is large.
The softmax function is a different kind of function. Instead of acting on one number, it takes a whole vector of scores, called logits, and turns them into probabilities that sum to 1. Dana's damage classifier has three classes: minor, moderate and total loss. Suppose a photo produces logits (2.0, 1.0, 0.1):
| Class | Logit z | ez | Probability |
|---|---|---|---|
| Minor | 2.0 | 7.389 | 7.389 / 11.212 = 0.659 |
| Moderate | 1.0 | 2.718 | 2.718 / 11.212 = 0.242 |
| Total loss | 0.1 | 1.105 | 1.105 / 11.212 = 0.099 |
Two variations show how softmax behaves.
- Shift every logit. Add 5 to all three and nothing changes. Every ez is multiplied by the same e5, which cancels between the top and bottom of the fraction. Softmax cares only about the differences between logits.
- Scale every logit. Double them to (4.0, 2.0, 0.2). The exponentials become 54.598, 7.389 and 1.221, which sum to 63.208, so the probabilities sharpen to 0.864, 0.117 and 0.019. Larger gaps between logits make softmax more confident.
When should Dana use sigmoid outputs instead? When the labels are not mutually exclusive. A single photo can show glass damage and bumper damage at once. That is a multi-label task, so the output layer gets one sigmoid per damage type, and each sigmoid answers its own yes-or-no question. Softmax would force the scores to compete for shares of 1, which is wrong when both labels can be true.
Backpropagation: sending the error back through the layers
Dana now has an architecture with random starting weights. To train it, she needs an answer to one question for every weight: if this weight rises a little, does the loss rise or fall, and by how much? That quantity is the partial derivative of the loss with respect to the weight. The vector of all these derivatives is the gradient. Backpropagation is the algorithm that computes the gradient efficiently. Google calls it the most common training algorithm for neural networks.[5] It also notes that backpropagation is what makes gradient descent practical for networks with several layers.[5]
It works in two passes. The forward pass runs the input through the network and keeps every intermediate value. The backward pass starts at the loss and applies the chain rule from calculus one layer at a time. It reuses the stored values, so each derivative is computed only once. That reuse is why training needs much more memory than prediction. CS231n notes that a network's activations are kept in memory because backpropagation needs them.[3]
Here is a worked example with one hidden ReLU neuron and one linear output neuron, using fictional numbers:
- Setup: input x = 1.0; weights w1 = 0.5 (input to hidden) and w2 = 2.0 (hidden to output); no biases; target y = 2.0; loss L = ½(ŷ - y)2; learning rate η = 0.1.
- Forward pass: z1 = w1x = 0.5; h = ReLU(0.5) = 0.5; ŷ = w2h = 1.0; L = ½(1.0 - 2.0)2 = 0.5.
- Backward pass, output end: ∂L/∂ŷ = ŷ - y = -1.0. Because ŷ = w2h, the gradient for w2 is ∂L/∂w2 = -1.0 × h = -0.5. The signal passed back to the hidden neuron is ∂L/∂h = -1.0 × w2 = -2.0.
- Backward pass, through the ReLU: z1 > 0, so the ReLU's slope is 1 and ∂L/∂z1 = -2.0. Because z1 = w1x, the gradient for w1 is ∂L/∂w1 = -2.0 × x = -2.0.
- Gradient descent step: w2 ← 2.0 - 0.1 × (-0.5) = 2.05 and w1 ← 0.5 - 0.1 × (-2.0) = 0.7.
- Checking the result: a new forward pass gives h = 0.7, ŷ = 0.7 × 2.05 = 1.435 and L = ½(0.565)2 ≈ 0.160. The loss fell from 0.5 to 0.16.
Now change one input. Set x = -1.0 and keep everything else the same. The forward pass gives z1 = -0.5, so h = ReLU(-0.5) = 0, ŷ = 0, and the loss is ½(0 - 2.0)2 = 2.0. That is worse than before. Yet the backward pass gives ∂L/∂w2 = -2.0 × h = 0. The ReLU's slope at -0.5 is 0, so ∂L/∂w1 = 0 as well. The error is larger and the network learns nothing. That is the dead-ReLU mechanism in miniature. If every training input left this unit negative, it would never recover.
The same chain-rule product explains the two classic training failures. Each layer's backward step multiplies the signal by that layer's weights and activation slopes.
- If those factors are mostly small, the gradient that reaches the early layers shrinks toward 0. This is the vanishing gradient problem, and Google notes that layers affected by it train very slowly, or not at all.[5]
- If the factors are mostly large, the product blows up. The result is exploding gradients, which grow too large for training to converge.[5]
ReLU activations help against vanishing gradients. Batch normalization and a lower learning rate help against exploding ones.[5] Gradient clipping, which caps a gradient's size before each update, is another common guard against explosion.
In practice nobody writes the backward pass by hand. Frameworks record the operations of the forward pass and differentiate them automatically, a feature called automatic differentiation. Google notes that libraries such as Keras handle backpropagation for you, so you never do the arithmetic yourself.[5] The mechanism still matters, because it is how you diagnose dead units and vanishing gradients.
Worth holding on to: backpropagation computes gradients and does not update anything. It applies the chain rule from the loss backward, reusing stored forward-pass values. The products it forms explain why gradients vanish through saturating activations and explode through large weights.
Optimizers: stochastic gradient descent, mini-batches, momentum, RMSprop and Adam
Backpropagation hands over a gradient g for each weight θ (theta). An optimizer decides what to do with it. The plain rule is gradient descent, θ ← θ - ηg: a step downhill, scaled by the learning rate η. The variants differ in two ways: how much data each gradient comes from, and what the optimizer remembers between steps.
How much data per step. Full-batch gradient descent computes g from the entire training set. That is exact but slow, and with millions of photos the data may not fit in memory. Stochastic gradient descent (SGD), in its strict sense, uses one example per step, which is cheap but noisy. Mini-batch gradient descent, the practical default, averages the gradient over a batch of B examples, commonly a few dozen to a few hundred. Dive into Deep Learning builds exactly this, a minibatch stochastic gradient descent optimizer, as part of its from-scratch linear regression.[1] In everyday usage, "SGD" usually means mini-batch SGD.
Two more terms. One step on one batch is an iteration. One pass over the whole training set is an epoch. Dana has 48,000 labeled photos and uses B = 256, so one epoch is 48,000 / 256 = 187.5 batches. That rounds up to 188 iterations, with a partial final batch.
The noise in mini-batch gradients is not only a cost. It jostles the weights enough to escape flat or shallow regions of the loss surface. Batch size is itself a tuning choice. Larger batches give smoother gradients and use the hardware better. Smaller batches add noise and take more steps per epoch.
Stochastic gradient descent with momentum. Plain SGD zigzags in a long, narrow valley of the loss surface, because the steepest direction points across the valley rather than along it. Momentum keeps a running velocity v. Each step computes v ← βv + g and then θ ← θ - ηv, where β is typically 0.9. Parts of the gradient that point the same way every step build up; parts that flip sign cancel out. With a constant gradient g = 1 and β = 0.9, the velocity grows 1, 1.9, 2.71, 3.44 and approaches g / (1 - β) = 10. So momentum can move up to ten times faster along a consistent direction. PyTorch's SGD class takes momentum as an option, and the first example in its documentation sets momentum=0.9.[6]
RMSprop (root mean square propagation) was proposed by Geoffrey Hinton in lecture slides rather than in a paper. It gives each weight its own effective step size. It keeps a running average of squared gradients, s ← ρs + (1 - ρ)g2, and divides each step by its square root: θ ← θ - ηg / (√s + ε). Here ρ (rho) is a decay rate such as 0.9, and ε (epsilon) is a tiny constant that prevents division by zero. √s is the root mean square of recent gradients, which gives the method its name. A weight whose gradients are always large gets damped. A weight with tiny gradients gets amplified.
The Adam optimizer (adaptive moment estimation, from Kingma and Ba) combines the two ideas. It keeps a momentum-style average of gradients and an RMSprop-style average of squared gradients:
- m ← β1m + (1 - β1)g. This is the first moment: the average direction.
- v ← β2v + (1 - β2)g2. This is the second moment: the average squared size.
- Both averages start at 0, so in early steps they are biased toward 0. Adam corrects this at step t: m̂ = m / (1 - β1t) and v̂ = v / (1 - β2t).
- Update: θ ← θ - η m̂ / (√v̂ + ε). The original paper's defaults are β1 = 0.9, β2 = 0.999 and ε = 10-8.
Work the first step to see what bias correction does. Suppose g = 4 at step t = 1:
- m = 0.1 × 4 = 0.4, and m̂ = 0.4 / (1 - 0.9) = 4.
- v = 0.001 × 16 = 0.016, and v̂ = 0.016 / (1 - 0.999) = 16, so √v̂ = 4.
- The step is η × 4 / 4 = η.
Repeat with g = 0.01 and you again get a step of about η. Adam's early steps are close to η in size, whatever the scale of the gradient. That is one reason it works without much tuning on so many problems. Plain SGD with g = 0.01 would move only 0.01η.
| Optimizer | What it remembers | Step size per weight | Strength | Typical pitfall |
|---|---|---|---|---|
| SGD (mini-batch) | Nothing | The same η for all weights | Simple; often generalizes well when tuned | Slow in narrow valleys; sensitive to η |
| SGD with momentum | Running velocity of gradients | The same η, amplified along consistent directions | Faster, with less zigzag | Can overshoot if η and β are both large |
| RMSprop | Running average of squared gradients | Adapted per weight | Handles weights with very different gradient scales | Still needs a tuned η |
| Adam | Both averages, bias-corrected | Adapted per weight, with momentum | Robust defaults; fast early progress | Can generalize slightly worse than tuned SGD on some tasks; interacts poorly with weight decay, which AdamW addresses |
In PyTorch, every optimizer has a step() method that applies the update once gradients have been computed.[6] A training loop therefore always makes the same five moves. This illustrative sketch follows the pattern in the PyTorch documentation. The names model, loss_fn and loader stand for objects Dana has already defined.
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in range(20):
for images, labels in loader: # one mini-batch per iteration
optimizer.zero_grad() # clear the last step's gradients
outputs = model(images) # forward pass
loss = loss_fn(outputs, labels)
loss.backward() # backpropagation fills in gradients
optimizer.step() # the optimizer updates the weights
The last two lines keep the two jobs apart: loss.backward() is backpropagation, and optimizer.step() is the optimizer. Swapping Adam for SGD with momentum changes the first line and nothing in the loop.
Worth holding on to: full-batch, mini-batch and strict SGD differ in how much data feeds each gradient. Momentum remembers direction. RMSprop scales each weight's step by the root mean square of its recent gradients. Adam does both, with bias correction, so its early steps are about η in size.
Schedulers: changing the learning rate as training goes
A single learning rate is a compromise. Early in training, a large η makes fast progress. Late in training, the same η keeps the weights bouncing around the bottom of the valley. A learning rate scheduler is a rule that changes η over the course of training. PyTorch keeps its schedulers in torch.optim.lr_scheduler. There are three common families:
- Fixed-schedule decay. The rate falls on a timetable, whatever the results. ExponentialLR multiplies η by a factor gamma every epoch. MultiStepLR multiplies it by gamma at chosen milestone epochs. Cosine annealing lowers η smoothly along half of a cosine curve.
- Feedback-driven decay. ReduceLROnPlateau watches a validation measurement and lowers η only when that measurement stops improving.[6]
- Learning-rate warmup. The rate starts small and rises over the first few hundred or thousand steps, and decay begins after that. Transformers are usually trained with warmup, because large early updates, made while Adam's averages are still unreliable, can destabilize them.
The table shows what two schedulers from PyTorch's documented examples do to a starting rate of 0.01: ExponentialLR with gamma = 0.9, and MultiStepLR with milestones at epochs 30 and 80 and gamma = 0.1.
| Epoch | ExponentialLR (gamma 0.9) | MultiStepLR (milestones 30 and 80; gamma 0.1) |
|---|---|---|
| 0 | 0.01 | 0.01 |
| 1 | 0.009 | 0.01 |
| 2 | 0.0081 | 0.01 |
| 10 | 0.01 × 0.910 ≈ 0.0035 | 0.01 |
| 30 | ≈ 0.00042 | 0.001 |
| 80 | ≈ 0.0000022 | 0.0001 |
The table carries a practical lesson. Exponential decay at 0.9 per epoch has cut the rate a hundredfold by about epoch 44, so a long run needs a gamma closer to 1. Two details matter in code. First, the scheduler should step after the optimizer has stepped.[6] Usually that means once per epoch. Second, schedulers can be chained, so that each one changes the rate the previous one produced.[6]
Do not confuse a scheduler with an optimizer. Adam adjusts each weight's step relative to the other weights. A scheduler scales the global η that Adam, or any other optimizer, multiplies by. The two are used together.
Keeping a flexible network honest: dropout, batch normalization and early stopping
Dana's first full training run reaches 99 percent training accuracy but only 81 percent validation accuracy (fictional figures). That gap is overfitting, and deep networks are prone to it. Dive into Deep Learning observes that a deep network can overfit even with only a few features.[7] It places deep networks at the opposite end of the bias-variance spectrum from linear models: low bias, high variance.[7] The authors also report that researchers have shown neural networks perfectly fitting labels that were assigned at random, where no real pattern exists.[7] The three tools in the objective fight overfitting in different ways.
Dropout regularization. During training, dropout sets each hidden unit's output to 0 with probability p, independently at every step.[7] Google describes it as randomly dropping unit activations for a single gradient step.[5] Because any unit might vanish, no unit can rely on a particular partner, so the network learns redundant features instead of fragile combinations. Another way to see it: each step trains a different thinned sub-network, and the final model behaves like an average of many of them. The rate p sets the strength of the regularization. A rate of 0 means no dropout, and a rate of 1 drops every unit, so the model learns nothing.[5] Dive into Deep Learning advises lower dropout rates near the input layer.[7] Its example uses 0.2 on the first hidden layer and 0.5 on the second.[7]
There is one subtlety. Suppose half the units vanish during training, but all of them are present at prediction time. The next layer would suddenly receive about twice as much total input. Modern frameworks prevent this with inverted dropout: during training, the surviving activations are divided by (1 - p). With p = 0.5, activations (4, 5, 6, 7) and a random mask of (1, 0, 1, 0), the output is (8, 0, 12, 0). On average, that matches the original values. At inference, dropout is switched off and nothing is rescaled. In PyTorch the switch is model.eval(). Forgetting it leaves dropout active, and predictions then change from one call to the next.
Batch normalization (Ioffe and Szegedy, 2015) standardizes a layer's values across each mini-batch. For each unit, it computes the batch mean μB and the batch variance σB2. It normalizes each value as x̂ = (x - μB) / √(σB2 + ε) and then applies a learned scale and shift: y = γx̂ + β. The learned γ (gamma) and β (beta) let the network undo the normalization if that works better. For example, suppose one unit's values over a batch of four are 2, 4, 6 and 8:
- The mean is 5.
- The variance is (9 + 1 + 1 + 9) / 4 = 5, so the standard deviation is about 2.236.
- The normalized values are -1.342, -0.447, 0.447 and 1.342.
Keeping every layer's inputs on a steady scale lets training use larger learning rates and makes it less sensitive to the starting weights. Google lists batch normalization as a defense against exploding gradients.[5] Two cautions apply.
- At inference there may be only one example, so the layer uses running averages of the mean and variance collected during training instead of batch statistics. This is another behavior that model.eval() switches.
- Very small batches give noisy statistics. That is one reason transformers use layer normalization instead, which normalizes across a single example's features.
The noise in batch statistics gives batch normalization a mild regularizing side effect, but its main purpose is faster, more stable optimization.
Early stopping checks validation loss after every epoch. If the loss has not improved for a set number of epochs, called the patience, training stops and the weights from the best epoch are restored. Here is Dana's (fictional) training log with a patience of 3:
| Epoch | Training loss | Validation loss | Epochs without improvement |
|---|---|---|---|
| 1 | 0.92 | 0.88 | 0 |
| 2 | 0.61 | 0.66 | 0 |
| 3 | 0.48 | 0.57 | 0 |
| 4 | 0.40 | 0.53 (best) | 0 |
| 5 | 0.34 | 0.54 | 1 |
| 6 | 0.29 | 0.56 | 2 |
| 7 | 0.25 | 0.59 | 3: stop |
Training stops after epoch 7 and restores the weights from epoch 4. Training loss fell the whole time. Only the validation loss shows that the network began memorizing the training data after epoch 4. With a patience of 1, training would have stopped after epoch 5 and restored the same weights here. On a noisier curve, though, a single bad epoch could then end a run that would have recovered. One more point: the stopping epoch was chosen using the validation set, so that set's loss is now slightly optimistic. Report final performance on a separate test set.
Worth holding on to: dropout randomly zeroes units, during training only. Batch normalization standardizes each layer's inputs per mini-batch and switches to running averages at inference. Early stopping halts training after a patience of non-improving validation epochs and keeps the best weights.
The convolutional neural network and the pooling layer
Now Dana turns to the photos. A 224 × 224 color image holds 224 × 224 × 3 = 150,528 input values, one per pixel per color channel. A fully connected layer of just 64 neurons on top of it needs 150,528 × 64 + 64 = 9,633,856 parameters. It would also have to learn separately that a dent in the top-left corner looks like a dent in the bottom-right.
A convolutional neural network (CNN) solves both problems with two constraints. First, its layers hold neurons in three dimensions, width, height and depth, as CS231n describes.[3] Depth here is the third dimension of a layer's grid of values, not the number of layers in the network. At the input it is the color channels; in later layers it is the number of filters. A CIFAR-10 image, for instance, is a 32 × 32 × 3 volume.[3] Each neuron connects only to a small region of the layer before it.[3] Second, all neurons in one depth slice share the same weights, called a filter or kernel.
A filter is a small grid of weights, say 3 × 3 × 3, slid across the image. At each position it computes a dot product, so it responds wherever its pattern appears, in any part of the image. Sixty-four 3 × 3 filters over a 3-channel input need only 3 × 3 × 3 × 64 + 64 = 1,792 parameters, compared with 9.6 million for the fully connected layer. That layer's output has a depth of 64, one slice per filter. The output width is (W - F + 2P) / S + 1, where W is the input width, F the filter size, P the padding (rows of zeros added around the border) and S the stride (how far the filter moves each step). With W = 224, F = 3, P = 1 and S = 1, the output is 224 wide again.
CS231n names three main layer types for building CNNs: convolutional, pooling and fully connected.[3] The pooling layer is the fourth layer type in the objective. It has no weights. It slides a window across each depth slice and keeps a summary of each window, usually the maximum. Here is a 4 × 4 grid of fictional values:
| Row | Column 1 | Column 2 | Column 3 | Column 4 |
|---|---|---|---|---|
| 1 | 1 | 3 | 0 | 4 |
| 2 | 2 | 9 | 6 | 1 |
| 3 | 5 | 2 | 3 | 8 |
| 4 | 7 | 0 | 1 | 2 |
Max pooling with a 2 × 2 window and stride 2 splits the grid into four non-overlapping windows and keeps each maximum:
- Rows 1-2, columns 1-2 hold (1, 3, 2, 9), so the maximum is 9.
- Rows 1-2, columns 3-4 hold (0, 4, 6, 1), so the maximum is 6.
- Rows 3-4, columns 1-2 hold (5, 2, 7, 0), so the maximum is 7.
- Rows 3-4, columns 3-4 hold (3, 8, 1, 2), so the maximum is 8.
The 4 × 4 grid becomes a 2 × 2 grid with 9 and 6 on top and 7 and 8 below. That is a quarter of the values, and the result barely changes if a feature shifts by one pixel within its window. During backpropagation, max pooling passes the gradient only to the input that held the maximum in the forward pass.[3] Pooling is not compulsory. The All Convolutional Net paper proposed dropping it and shrinking the grid with larger convolution strides instead.[3]
A typical CNN stacks blocks of convolution, ReLU and pooling, then flattens the result into fully connected layers ending in a softmax output. The costs are lopsided. CS231n notes that most memory and compute go to the early convolutional layers.[3] Most parameters, by contrast, sit in the last fully connected layers.[3] For Dana, the practical route is transfer learning: start from a CNN pretrained on millions of general images and fine-tune its last layers on her 48,000 claim photos.
Reading the notes: recurrent networks, LSTM and the transformer
Adjuster notes are sequences, such as "Rear impact at low speed, driver reports neck pain, no prior claims." Word order carries meaning, and the notes vary in length. Three architectures handle sequences.
A recurrent neural network (RNN) reads one token at a time, where a token is a word or a piece of a word. It carries a hidden state forward from step to step: ht = tanh(Wxxt + Whht-1 + b). Here xt is the token at step t and ht-1 is the previous hidden state. The same weights are reused at every step, so one network handles sequences of any length. Training unrolls the sequence and runs backpropagation through time. The unrolled network is deep, with one layer per token, and it multiplies by Wh and a tanh slope at every step. Over 50 or 100 tokens, the gradients vanish or explode. A plain RNN forgets the start of a long note.
Long short-term memory (LSTM), from Hochreiter and Schmidhuber's 1997 work, adds a separate cell state ct controlled by three gates. Each gate is a sigmoid layer whose outputs, between 0 and 1, act as valves:
- The forget gate ft sets how much of the old cell state to keep.
- The input gate it sets how much of a new candidate value c̃t, computed with tanh, to write into the cell.
- The output gate ot sets how much of the cell to expose as the hidden state: ht = ot ⊙ tanh(ct).
The cell update is ct = ft ⊙ ct-1 + it ⊙ c̃t, where ⊙ means element-by-element multiplication. The key symbol is the plus sign. When the forget gate stays near 1, information and gradient pass along the cell almost unchanged across many steps, instead of being squeezed through a tanh each time. That additive path is how an LSTM keeps long-range memory. It still reads tokens one after another, though, so its work cannot be spread across the positions of a sequence in parallel.
The Transformer (deep learning architecture), introduced by Vaswani and colleagues in 2017 in "Attention Is All You Need", drops recurrence. Each token becomes three vectors: a query, a key and a value. Self-attention lets each token look at all the others at once: Attention(Q, K, V) = softmax(QKT / √dk)V, where dk is the length of the key vectors. Read the formula in three steps:
- Score every pair of tokens by how well one token's query matches the other's key.
- Turn each row of scores into weights with softmax.
- Take the weighted average of the value vectors.
In Dana's note, "pain" can attend directly to "neck" and to "rear impact", however far apart they are. Processing order no longer tells the model the word order, so transformers add positional encodings to the token vectors. All positions are computed together, so training parallelizes well on graphics processing units (GPUs). That is a large part of why transformers became the basis of large language models. The cost is that attention compares every pair of tokens, so compute and memory grow with the square of the sequence length.
Compressing and generating: autoencoders and generative adversarial networks
The fraud team has 200,000 claims believed to be normal and only a handful of confirmed fraud cases (fictional figures). That is far too few positive labels to train a classifier.
An autoencoder is a network trained to reproduce its own input. An encoder compresses the input into a small bottleneck vector, called the latent code, and a decoder rebuilds the input from that code. The loss is reconstruction error, such as the mean squared error between input and output, so no labels are needed. The narrow bottleneck forces the network to keep only the structure that matters.
Dana trains an autoencoder on normal claims only. A new claim that reconstructs badly does not resemble anything the network learned, so reconstruction error becomes an anomaly score. She flags claims whose error is above the 99th percentile of errors on normal validation data. Two related facts are worth knowing. An autoencoder with only linear layers and squared-error loss learns the same subspace as principal component analysis (PCA); its non-linear activations are what let it capture curved structure that PCA misses. And there are variants: denoising autoencoders learn to restore corrupted inputs, and variational autoencoders learn a smooth latent distribution that can be sampled to generate new data.
A generative adversarial network (GAN; Goodfellow and colleagues, 2014) generates new data by setting two networks against each other. The generator G turns random noise z into a fake sample G(z). The discriminator D receives both real and fake samples and outputs the probability that its input is real. D is trained to tell real from fake, and G is trained to fool D. When training goes well, G's samples become hard to distinguish from real ones. Dana could use a GAN to create synthetic photos of a rare damage type and add them to the training data.
GANs have two common failures. In mode collapse, G produces only a few kinds of sample that reliably fool D. And training becomes unstable when one network overpowers the other. CS231n notes that removing pooling layers has mattered for training good generative models such as variational autoencoders and GANs.[3]
| Question | Autoencoder | GAN |
|---|---|---|
| Networks | Encoder and decoder, trained together | Generator and discriminator, trained against each other |
| Training signal | Reconstruction error | The discriminator's judgment of real versus fake |
| Needs labels? | No | No; it needs only real samples |
| Typical uses | Compression, denoising, anomaly detection | Synthetic images, data augmentation, image-to-image translation |
| Typical failure | Blurry reconstructions; simply copies the input if the bottleneck is too wide | Mode collapse; unstable training |
One-shot, few-shot and zero-shot learning
In June (still fictional), a hailstorm creates a new claim type, and Dana has three labeled photos of hail damage. Retraining a CNN on three images would overfit immediately. Three terms describe learning from this little data. They are defined by how many labeled examples of the new class exist:
- Few-shot learning uses a handful of labeled examples per new class. Benchmarks describe this as N-way K-shot. For example, 5-way 5-shot means five classes with five examples each.
- One-shot learning uses exactly one labeled example per class, the K = 1 case. The classic example is verifying a face against a single enrolled photo.
- Zero-shot learning uses no labeled examples of the class at all. The model relies on side information instead, such as a text description or a list of attributes, linked to what it learned from other classes.
All three depend on a model that already knows a lot. The usual approach takes a network pretrained on large data and uses it as an embedding function: a map from a photo to a vector, in which similar photos land close together. Here is a worked example with fictional two-dimensional embeddings. Real embeddings have hundreds of dimensions.
- Dana's three hail photos embed at (0.9, 0.2), (0.8, 0.3) and (1.0, 0.1). Their average, called the class prototype, is (0.9, 0.2).
- She also has three labeled flood photos, which embed at (0.0, 1.0), (0.2, 0.8) and (0.1, 0.9). Their prototype is (0.1, 0.9).
- A new photo embeds at (0.7, 0.4). Its distance to the hail prototype is √(0.22 + 0.22) = √0.08 ≈ 0.283. Its distance to the flood prototype is √(0.62 + 0.52) = √0.61 ≈ 0.781. The nearer prototype is hail, so the photo is labeled hail.
- Change the photo to (0.4, 0.7). The distances become √(0.25 + 0.25) ≈ 0.707 to hail and √(0.09 + 0.04) ≈ 0.361 to flood. Now it is labeled flood.
No weights changed. Adding a class meant adding a prototype. Siamese networks, which are trained to decide whether two inputs belong to the same class, rely on the same idea. Zero-shot learning replaces a prototype built from photos with one built from language. A model trained to place images and text in a shared embedding space can score a photo against the phrase "a car with hail dents" without ever seeing a labeled hail photo. Large language models use the terms the same way for prompts. A zero-shot prompt gives instructions only. A few-shot prompt includes a few worked examples.
Do not confuse these terms with transfer learning. Fine-tuning a pretrained CNN on 48,000 labeled photos is transfer learning, but it is not few-shot learning. "Shot" counts labeled examples of the target class, and 48,000 is not a few.
Worth holding on to: one-shot, few-shot and zero-shot learning are named for the number of labeled examples of the new class: one, a few, or none. All three lean on a pretrained representation, and zero-shot learning also needs side information such as a text description.
Frameworks and AutoML: PyTorch, TensorFlow/Keras and automated search
Everything above comes prebuilt in deep-learning frameworks: automatic differentiation, optimizers, schedulers and layers. Dive into Deep Learning notes that modern frameworks can automate nearly all of this work, while urging readers to build it by hand once so they understand it.[1]
| Question | PyTorch | TensorFlow/Keras | AutoML |
|---|---|---|---|
| What it is | A Python-first framework that runs operations immediately as code executes | TensorFlow is Google's framework; Keras is a high-level application programming interface (API) with compile, fit and callbacks | Automated search over models, hyperparameters and sometimes architectures |
| Training loop | Usually written by you, or by a helper library | Usually model.fit(), with callbacks for early stopping and schedules | Run by the tool |
| Strength | Flexible and easy to debug; widely used in research | Concise standard workflows; mature deployment tools | Saves expert time on routine problems |
| Watch for | More code to get right | Differences between Keras 2 and Keras 3 | Compute cost, opacity, and leakage if the validation design is wrong |
Here is an illustrative Keras sketch of a small classifier that uses dropout, Adam, a softmax output and early stopping. X_train and y_train stand for Dana's prepared data.
model = keras.Sequential([
keras.Input(shape=(20,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(3, activation='softmax'),
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3,
restore_best_weights=True)
model.fit(X_train, y_train, validation_split=0.2,
epochs=50, batch_size=256, callbacks=[stop])
Current releases of Keras, from Keras 3 on, can run on TensorFlow, JAX or PyTorch as the backend, so "Keras" no longer implies TensorFlow underneath. The exam's "TensorFlow/Keras" reflects the older pairing, in which Keras shipped inside TensorFlow as tf.keras.
Automated machine learning (AutoML) automates choices a data scientist would otherwise make by trial and error. These include the model family, hyperparameters such as learning rate, batch size or dropout rate, and, in neural architecture search, how many layers to use and of what kind. Both cloud platforms and open-source libraries offer it. It trades compute for expert time. It does not choose the business question, fix poor labels, or notice that a feature leaks the target. And if the validation split is wrong, AutoML will optimize carefully toward the wrong target.
Exam cues: matching a question stem to a concept
| If the question says... | Think... | Not to be confused with... |
|---|---|---|
| Single neuron, step output, only linearly separable data | Perceptron | Multilayer perceptron, which can solve XOR |
| Early layers barely change during training; deep sigmoid network | Vanishing gradients; switch to ReLU | Exploding gradients (loss swings wildly or becomes not a number, NaN) |
| Units output 0 for every input and never recover | Dead ReLU; lower the learning rate or use leaky ReLU | Dropout, which zeroes units randomly and temporarily |
| Probabilities across mutually exclusive classes that sum to 1 | Softmax output | One sigmoid per class, for multi-label outputs |
| Computes gradients with the chain rule | Backpropagation | The optimizer, which uses those gradients to update weights |
| Running averages of the gradient and the squared gradient, with bias correction | Adam | RMSprop (squared gradients only) and momentum (gradients only) |
| Lower the learning rate when validation loss plateaus | Scheduler (ReduceLROnPlateau) | Early stopping, which ends training instead |
| Randomly zero activations during training | Dropout | Pooling, which downsamples by a fixed rule |
| Normalize layer inputs per mini-batch with a learned scale and shift | Batch normalization | Scaling the raw input features before training |
| Shrink a feature map; no learned weights | Pooling layer | Convolutional layer, which has filters |
| Long sequences, gates, cell state | LSTM | Plain RNN, which forgets over long sequences |
| Self-attention, positional encoding, parallel over tokens | Transformer | RNN or LSTM, which read tokens in order |
| Generator versus discriminator | GAN | Autoencoder, trained on reconstruction |
| Bottleneck, reconstruction error, anomaly detection without labels | Autoencoder | PCA, its linear special case |
| No labeled examples, only a description of the class | Zero-shot learning | One-shot learning, which has exactly one example |
| Automated search over models and hyperparameters | AutoML | A scheduler, which only changes the learning rate |
Common misconceptions
- "Backpropagation is how a network learns." Backpropagation only computes gradients. The optimizer, whether SGD, momentum, RMSprop or Adam, uses them to change the weights. In PyTorch these are separate calls: loss.backward() and optimizer.step().
- "More layers always means a more powerful model." Without non-linear activations, any number of layers collapses into one linear layer. With saturating activations, extra depth can make gradients vanish so that the early layers stop learning.
- "Dropout stays on when the model is used." Dropout applies only during training. At inference every unit is present, and inverted dropout has already handled the scaling. Leaving dropout on makes predictions random.
- "Softmax and sigmoid outputs are interchangeable." Softmax makes classes compete for a total of 1, so it suits mutually exclusive labels. Independent sigmoids suit multi-label tasks, where several answers can be true at once.
- "Adam removes the need to tune the learning rate." Adam adapts step sizes per weight, but every step is still scaled by η, and schedulers and warmup are routinely used with it.
- "Zero-shot means the model saw no data." It means the model saw no labeled examples of the target class. It relies on extensive pretraining and on side information such as text descriptions.
Where this leaves us
- An artificial neuron computes z = w·x + b and outputs f(z). A perceptron uses a step function for f and cannot learn XOR, which needs at least one hidden layer.
- Without non-linear activations, stacked layers collapse into a single linear map, so hidden layers need ReLU, tanh or a similar function.
- ReLU has slope 1 when active, which helps against vanishing gradients, but a ReLU unit can die. Sigmoid's slope is at most 0.25. Tanh ranges from -1 to 1. Softmax turns logits into probabilities that sum to 1 and is unchanged when every logit shifts by the same constant.
- Backpropagation applies the chain rule from the loss backward, using stored forward-pass values. The optimizer then updates the weights.
- Mini-batch SGD averages gradients over B examples. Momentum can build velocity up to 1 / (1 - β) times the gradient. RMSprop divides each step by the root mean square of recent gradients. Adam combines both, with bias correction.
- Schedulers change the learning rate during training (step, exponential, cosine, plateau-based or warmup), and they step after the optimizer.
- Dropout zeroes units with probability p during training only. Batch normalization standardizes per mini-batch and uses running averages at inference. Early stopping halts after a patience of non-improving validation epochs and restores the best weights.
- CNNs use shared local filters and weightless pooling for images. LSTMs add a gated, additive cell state to RNNs. Transformers use self-attention and positional encodings. Autoencoders reconstruct their input through a bottleneck. GANs set a generator against a discriminator.
- One-shot, few-shot and zero-shot learning mean one, a few or no labeled examples of the new class. PyTorch, TensorFlow/Keras and AutoML automate the mechanics of training, but not the judgment behind it.
Sources
- Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola. (2021). Dive into Deep Learning. arXiv (d2l.ai). arxiv.org
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Stanford University. (n.d.). CS231n Convolutional Neural Networks for Visual Recognition: Convolutional Networks. cs231n.github.io
- Google for Developers. (n.d.). Neural networks. developers.google.com
- Google for Developers. (n.d.). Neural Networks: Training using backpropagation. developers.google.com
- PyTorch. (2024). torch.optim. docs.pytorch.org
- d2l.ai. (n.d.). Dive into Deep Learning: Dropout. ja.d2l.ai
- Key terms
- Artificial neuron
- The basic unit of a neural network: it computes a weighted sum of its inputs plus a bias, then passes the result through an activation function to produce its output.
- Activation function
- The function a neuron applies to its weighted sum, such as ReLU (rectified linear unit), sigmoid, tanh (hyperbolic tangent) or softmax. Non-linear activations are what let stacked layers represent non-linear patterns.
- Backpropagation
- The algorithm that computes the gradient of the loss with respect to every weight in a neural network by applying the chain rule backward from the loss, reusing values stored during the forward pass. It computes gradients but does not update weights.
- Mini-batch stochastic gradient descent
- An optimizer that updates weights using the gradient averaged over a small batch of training examples, trading the exactness of full-batch descent for speed and helpful noise.
- Adam optimizer
- An adaptive optimizer that keeps bias-corrected running averages of both the gradient and the squared gradient, combining momentum with per-weight step sizes in the style of RMSprop (root mean square propagation).
- Learning rate scheduler
- A rule that changes the global learning rate during training, for example by exponential or step decay, cosine annealing, warmup, or reduction when a validation measure stops improving.
- Dropout
- A regularization method for neural networks that randomly sets each unit's output to zero with probability p at each training step and is switched off at inference.
- Batch normalization
- A neural network layer that standardizes each unit's values using the mean and variance of the current mini-batch, then applies a learned scale and shift. At inference it uses running averages instead of batch statistics.
- Few-shot learning
- Learning to recognize a new class from only a handful of labeled examples, usually by building on a pretrained representation. One-shot learning is the case with exactly one example, and zero-shot learning is the case with none.
- Transformer
- A neural network architecture that uses self-attention to relate every token in a sequence to every other token in parallel, with positional encodings supplying word order.
Unsupervised Machine Learning
- Run k-means by hand, then choose k with the elbow method and the silhouette score, and recognize when each one misleads.
- Compare k-means, hierarchical clustering and DBSCAN by their assumptions, parameters, cluster shapes and handling of outliers.
- Explain how PCA, SVD, t-SNE and UMAP reduce dimensions, and what each output can and cannot be used for.
- Distinguish unsupervised nearest neighbor search from KNN classification and from k-means, and explain why neighbor search underlies other unsupervised methods.
Four true groups, and the score prefers two
The scikit-learn tutorial on silhouette analysis generates 500 points around four centers. It runs k-means for every cluster count from 2 to 6 and prints a score for each. The highest average silhouette score, 0.705, belongs to two clusters.[1] The true count of four scores only 0.651. The data were built that way on purpose: one group sits apart, and the other three are placed close together. From a distance, three touching groups look like one, and the metric reports exactly that.
This is the normal condition of working without labels. Unsupervised learning means fitting a model to the inputs alone, with no target column to score it against. Every method in this lesson will return groups or new coordinates whether or not real structure exists. What protects you is knowing the assumption each method makes, because its output always mixes the shape of the data with the shape of that assumption.
Exam objectives: DY0-001 objective 3.5, "Explain concepts related to unsupervised machine learning."[2] It names clustering (k-means with the silhouette score and elbow method, hierarchical clustering, and density-based spatial clustering analysis with noise, DBSCAN), dimensionality reduction (principal component analysis, PCA; t-distributed stochastic neighbor embedding, t-SNE; and uniform manifold approximation and projection, UMAP), k-nearest neighbors (KNN) and singular value decomposition (SVD).
These methods do two jobs. Cluster analysis, or clustering, assigns points to groups. Dimensionality reduction replaces many columns with a few new ones. KNN and SVD work underneath both: neighbor search drives DBSCAN, t-SNE and UMAP, and SVD is how PCA is usually computed. The table below maps the rest of the lesson.
| Method | Job | What you must choose | What comes out |
|---|---|---|---|
| k-means | Partition points into k groups around centroids | k and the starting centroids | One label per point, plus k centroids |
| Hierarchical (agglomerative) | Build a tree of nested merges | Distance, linkage, and where to cut the tree | A dendrogram, then labels after cutting |
| DBSCAN | Grow clusters from dense regions | eps and min_samples | Labels, plus a noise label for outliers |
| PCA | Rotate onto uncorrelated axes of maximum variance | Number of components | A linear projection that also works on new rows |
| SVD | Factor any matrix into U, Σ and VT | Rank to keep | Low-rank approximation and latent factors |
| t-SNE | Draw local neighborhoods in 2 or 3 dimensions | Perplexity | A picture of the rows you supplied |
| UMAP | Lay out a fuzzy neighbor graph in a few dimensions | n_neighbors and min_dist | An embedding; a fitted model can place new rows |
| KNN search | Find each point's k closest points | k and the distance metric | Neighbor lists and distances |
K-means clustering: Lloyd's algorithm worked by hand
K-means clustering divides n points into k groups, where you choose k in advance. Each group is summarized by its centroid, the mean of the points in it. The standard procedure, Lloyd's algorithm, picks k starting centroids and then loops over two steps. First, it assigns each sample to its nearest centroid. Second, it moves each centroid to the mean of the points just assigned to it. When the assignments stop changing, it stops.
The quantity k-means drives down is the within-cluster sum of squares, which scikit-learn calls inertia:
inertia = Σi ||xi - μc(i)||2
Read it like this. For each point xi, find the centroid μc(i) of the cluster it belongs to. Square the Euclidean distance between them. Add these up over all points. Both steps of the loop can only lower this sum or leave it unchanged. Moving a point to a closer centroid shrinks its own term. Replacing a centroid with the mean of its members also shrinks the total, because the mean is the single point with the smallest summed squared distance to a set of points. A quantity that never rises and cannot fall below zero must settle, so the loop always converges.
It converges to a local minimum, though, not necessarily the best partition. Different starting centroids can end in different answers. Implementations therefore run several starts and keep the one with the lowest inertia. scikit-learn's default starting rule, k-means++, spreads the initial centroids apart so that poor starts are less likely.
Here is a small fictional example you can check with a pencil. Six customers log 1, 2, 3, 10, 11 and 12 visits per month. Run k-means with k = 2, starting the centroids at 1 and 2.
| Step | Centroid A | Centroid B | Cluster A | Cluster B | Inertia |
|---|---|---|---|---|---|
| Start | 1 | 2 | not yet assigned | not yet assigned | - |
| Pass 1, assign | 1 | 2 | 1 | 2, 3, 10, 11, 12 | - |
| Pass 1, update | 1 | 7.6 | 1 | 2, 3, 10, 11, 12 | 89.2 |
| Pass 2, assign | 1 | 7.6 | 1, 2, 3 | 10, 11, 12 | - |
| Pass 2, update | 2 | 11 | 1, 2, 3 | 10, 11, 12 | 4.0 |
| Pass 3, assign | 2 | 11 | no change | no change | 4.0, stop |
Follow pass 2 closely. Point 2 is 1 away from centroid A and 5.6 from centroid B, so it moves to A. Point 3 is 2 from A and 4.6 from B, so it moves too. Point 10 is 9 from A and 2.4 from B, so it stays in B. The new centroids are (1 + 2 + 3)/3 = 2 and (10 + 11 + 12)/3 = 11. Inertia falls from 89.2 to 1 + 0 + 1 + 1 + 0 + 1 = 4.
Now change one input. Add a seventh customer with 40 visits and still ask for two clusters. k-means must put every point somewhere. The split {1, 2, 3} and {10, 11, 12, 40} has inertia 634.75, because 40 drags the second centroid to 18.25 and every member of that cluster pays for the distance. Isolating the outlier, as {1, 2, 3, 10, 11, 12} and {40}, has inertia only 125.5. So the lowest-inertia answer now spends one of your two clusters on a single customer and lumps the two real groups together. Squaring distances gives a far point enormous weight, and k-means has no way to say that a point belongs nowhere.
The same squared Euclidean distance brings three more assumptions. Clusters should be roughly round and of similar spread; the scikit-learn guide warns that k-means responds poorly to elongated clusters.[3] Features must be on comparable scales, or the widest column decides every distance. And you must supply k, which raises the question of the next section. In code, the usual loop looks like this:
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
X_std = StandardScaler().fit_transform(X)
for k in range(2, 7):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_std)
print(k, round(km.inertia_, 1), round(silhouette_score(X_std, km.labels_), 3))
The core of it: k-means alternates two steps, assigning each point to the nearest centroid and moving each centroid to the mean. Both steps can only lower inertia, so the loop converges, but only to a local minimum. It also assumes round, similar-sized clusters on scaled features, with every point assigned to some cluster.
Choosing k: the elbow method and the silhouette score
Inertia alone cannot pick k. Adding a cluster never raises the best achievable inertia, and with one cluster per point inertia reaches zero. scikit-learn notes that inertia is not a normalized metric: lower is better and zero is optimal, but there is no fixed scale that tells you when it is low enough.[3] Two heuristics turn it into a decision.
The elbow method plots the best inertia against k and looks for the bend where one more cluster stops buying much. For the six customers:
| k | Best inertia | Drop from previous k |
|---|---|---|
| 1 | 125.5 | - |
| 2 | 4.0 | 121.5 |
| 3 | 2.5 | 1.5 |
| 4 | 1.0 | 1.5 |
| 5 | 0.5 | 0.5 |
| 6 | 0.0 | 0.5 |
Going from one cluster to two removes 121.5 of the 125.5. A third cluster removes only 1.5 more. The bend is at k = 2. Real curves are rarely this sharp. When the curve bends gently, two analysts can read two different elbows from the same plot, and that subjectivity is the method's main weakness.
The silhouette coefficient scores each point by comparing its own cluster with the nearest alternative. For point i:
- a(i) is the mean distance from i to the other members of its own cluster.
- b(i) is the mean distance from i to the members of the nearest other cluster.
- s(i) = (b(i) - a(i)) / max(a(i), b(i)).
The value runs from -1 to +1. Near +1, the point is far from the neighboring clusters. A value near 0 means the point sits on or very close to the boundary between two clusters. Negative values mean the point is closer, on average, to another cluster, and it may have been assigned to the wrong one.[1] The silhouette score of a whole clustering is the mean of s(i) over all points, and you compare it across values of k. It needs at least two clusters, so it is not defined at k = 1.
Work it for the six customers at k = 2. Point 1: a = (1 + 2)/2 = 1.5 and b = (9 + 10 + 11)/3 = 10, so s = (10 - 1.5)/10 = 0.85. Point 2: a = (1 + 1)/2 = 1 and b = (8 + 9 + 10)/3 = 9, so s = 8/9 = 0.89. Point 3: a = (2 + 1)/2 = 1.5 and b = (7 + 8 + 9)/3 = 8, so s = 6.5/8 = 0.81. The other cluster mirrors these values, so the silhouette score is about 0.85: two tight, well separated groups.
Now return to the opening, where the result flipped. In the scikit-learn tutorial the silhouette score preferred two clusters over the true four. The tutorial's own reading of its per-cluster plots is more careful: it rejects 3, 5 and 6 as bad picks and says silhouette analysis is more ambivalent in deciding between 2 and 4.[1] The reason is mechanical. Silhouette rewards separation. When real groups sit close together, merging them raises each point's b, because the nearest other cluster is now far away, by more than it raises a. So the score prefers fewer, coarser groups.
| Question | Elbow method | Silhouette score |
|---|---|---|
| What it measures | Compactness only (inertia) | Compactness against separation |
| Behavior as k grows | Always falls | Rises and falls; look for the peak |
| How you read it | Find the bend; partly subjective | Pick the highest mean, then inspect per-cluster values |
| Defined for | Any k from 1 | k from 2 to n - 1 |
| Cost | Cheap: inertia comes free with each fit | Needs distances between all pairs of points |
| Misleads when | The curve bends smoothly | Real groups touch, or clusters are not round |
In practice you use both, plus a per-cluster silhouette plot, plus a check that the groups mean something to the business. If the elbow and the silhouette peak agree, you have reasonable support. If they disagree, say so, and let stability across random seeds and the usefulness of each segment decide.
The core of it: the elbow method looks for where inertia stops falling fast. The silhouette score, (b - a)/max(a, b), compares each point's own cluster with the nearest other one. Both are heuristics, and silhouette favors fewer clusters when true groups sit close together.
Hierarchical clustering: build the tree first, cut it later
Hierarchical clustering builds a nested family of clusterings instead of a single answer. The common form is agglomerative, or bottom-up. It starts with every point as its own cluster, then repeatedly merges the two closest clusters until only one remains. The divisive form works top-down, splitting one big cluster again and again, and is less common in practice. The record of merges is drawn as a dendrogram, a tree whose vertical axis shows the distance at which each merge happened. Cutting the tree at a chosen height gives the clusters.
The phrase "closest clusters" needs a definition, called the linkage. Each linkage rule measures the distance between two clusters differently:
| Linkage | Distance between clusters A and B | Tendency |
|---|---|---|
| Single | Smallest distance between any point in A and any point in B | Follows chains; finds long, thin shapes; one bridging point can join two groups |
| Complete | Largest distance between any point in A and any point in B | Compact groups of similar diameter |
| Average | Mean of all pairwise distances between A and B | Between single and complete |
| Ward | Increase in total within-cluster sum of squares caused by the merge | Round, similar-sized groups, much like k-means |
Single, average and complete linkage work with many distances, including Euclidean, Manhattan and cosine distance, or any precomputed distance matrix.[3] Ward linkage is defined through squared Euclidean error, so it is used with Euclidean distance. That flexibility is a real advantage. If you can define a sensible distance between two customers, two genes or two documents, agglomerative clustering can use it.
Run complete linkage on the six customers. Ties are broken in arbitrary order.
| Merge | Clusters joined | Complete-linkage distance | Clusters left |
|---|---|---|---|
| 1 | {1} + {2} | 1 | 5 |
| 2 | {10} + {11} | 1 | 4 |
| 3 | {1, 2} + {3} | 2 (from 3 to 1) | 3 |
| 4 | {10, 11} + {12} | 2 (from 12 to 10) | 2 |
| 5 | {1, 2, 3} + {10, 11, 12} | 11 (from 1 to 12) | 1 |
The dendrogram would show four short merges near the bottom and one tall merge at height 11. Cut anywhere between 2 and 11 and you get two clusters. A large jump in merge height is the tree's version of an elbow: a big gap before the final merge means the groups below it are well separated. You choose the number of clusters after seeing the tree, without refitting.
Now change one input. Switch to single linkage, where the final merge of the original six points happens at 7, the gap from 3 to 10. Then add a customer at 6. The new point is 3 from the left group and 4 from the right one. Under single linkage it joins the left group at height 3, and the two groups then merge at height 4, the gap from 6 to 10. One intermediate point has shrunk the separation from 7 to 4 by building a bridge. That is the chaining effect. It is why single linkage suits long, thin structures and suffers when stray points sit between groups.
Two costs come with the method. Plain implementations compare all pairs of clusters, so time and memory grow quickly with the number of rows; restricting merges to nearby points, called a connectivity constraint, is the usual way to scale it. And merges are greedy: a merge made early is never undone, even when it looks wrong later.
DBSCAN: clusters grown from dense cores
DBSCAN comes from a paper by M. Ester, H.-P. Kriegel, J. Sander and X. Xu. Its original name, which scikit-learn also uses, is density-based spatial clustering of applications with noise.[4] CompTIA's acronym list expands it as density-based spatial clustering analysis with noise. It is the same algorithm, so recognize either name.
DBSCAN views clusters as areas of high density separated by areas of low density.[3] Two parameters define what dense means:
- eps: the radius of the neighborhood around each point.
- min_samples: how many points must lie within eps for a point to count as dense. In scikit-learn this count includes the point itself.
Every point then gets one of three roles. A core sample has at least min_samples points within eps, so it sits in an area of high density. A border point is not core itself but lies within eps of a core point, so it joins that core point's cluster. A noise point is neither, and scikit-learn gives it the label -1. Clusters grow by linking core points that lie within eps of each other and then attaching their border points. The number of clusters is an output, not an input.
Take the six customers plus the one at 6, so the points are 1, 2, 3, 6, 10, 11 and 12. Set eps = 1.5 and min_samples = 3.
| Point | Points within 1.5 (including itself) | Count | Role |
|---|---|---|---|
| 1 | 1, 2 | 2 | Border (within 1.5 of core point 2) |
| 2 | 1, 2, 3 | 3 | Core |
| 3 | 2, 3 | 2 | Border |
| 6 | 6 | 1 | Noise |
| 10 | 10, 11 | 2 | Border |
| 11 | 10, 11, 12 | 3 | Core |
| 12 | 11, 12 | 2 | Border |
Result: two clusters, {1, 2, 3} and {10, 11, 12}, with customer 6 labeled noise. Compare k-means, which must assign 6 somewhere. With centroids at 2 and 11, point 6 is 4 from the first and 5 from the second, so k-means puts it in the left group and pulls that centroid to 3.
Now flip one input: raise eps to 4.5. Every point now has at least three points within reach, so every point is core. Point 6 reaches 2, 3 and 10, so it links the two groups. DBSCAN returns one cluster and no noise. A single parameter moved the answer from two groups and an anomaly to one group. That sensitivity is the price of not choosing k.
The scikit-learn demo shows the same workflow at scale. It standardizes 750 points drawn around three centers and fits DBSCAN with eps = 0.3 and min_samples = 10. The fit finds three clusters, and the demo prints "Estimated number of noise points: 18".[4] A common way to choose eps is a k-distance plot. For each point, compute the distance to its k-th nearest neighbor, with k set to min_samples. Sort those distances and pick eps near the bend where they shoot upward. Points beyond the bend live in sparse regions and become noise.
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.3, min_samples=10).fit(X_std)
labels = db.labels_ # -1 marks noise
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = list(labels).count(-1)
DBSCAN's strengths follow from its density view. Clusters can take any shape, because a chain of core points can curve around anything, and outliers are reported instead of absorbed. Its weakness is the single eps. The demo says the algorithm is good for data with clusters of similar density.[4] If one cluster is tight and another diffuse, any one radius either fragments the diffuse cluster or merges the tight one with its surroundings. HDBSCAN (hierarchical DBSCAN) addresses this by building a hierarchy across density levels. Its main settings in scikit-learn are a minimum cluster membership and a minimum number of point neighbors, not a radius.[3] Memory is the other caution. scikit-learn's DBSCAN can build a full pairwise similarity matrix when tree-based neighbor search cannot be used, as with sparse matrices.[3]
Three clustering families side by side
| Property | k-means | Agglomerative hierarchical | DBSCAN |
|---|---|---|---|
| Number of clusters | You choose k first | You choose a cut height or k after the tree is built | An output of eps and min_samples |
| Cluster shape it finds | Round (convex), similar size | Depends on linkage: chains (single) to compact (complete, Ward) | Any shape, if density is similar across clusters |
| Outliers | Forced into a cluster; they pull centroids | Merged late; can build chains under single linkage | Labeled noise (-1) |
| Distance | Squared Euclidean | Any pairwise distance for single, complete, average | Any metric the neighbor search supports |
| Many rows | Scales well | Limited by pairwise comparisons | Good with tree-based neighbor search; memory heavy otherwise |
| New points | Assign to the nearest centroid | Refit; labels only the fitted data | Refit; labels only the fitted data |
| Typical failure | Wrong k; elongated or uneven clusters | Early bad merges; cost | Clusters of different density |
scikit-learn's overview lists DBSCAN's best uses as non-flat geometry, uneven cluster sizes and outlier removal.[3] The same overview tags both DBSCAN and agglomerative clustering as transductive. Transductive means the method labels the data it was fitted on but offers no rule for a new point. If you need to score tomorrow's customers, either refit or train a classifier on the cluster labels.
Evaluating any of these is harder than evaluating a classifier. When the true labels are unknown, which is the normal case, you can judge a clustering only from its own output. For that case, the scikit-learn DBSCAN demo recommends the silhouette coefficient.[4] When you do have labels for a test set, external scores such as the adjusted Rand index compare the clusters with them. If such labels exist for the whole problem, ask whether you should be building a classifier instead.
The core of it: choose k-means for round groups at scale, especially when you need a centroid rule for new points. Choose hierarchical clustering when the nested structure or a custom distance matters. Choose DBSCAN when shapes are irregular and outliers should be flagged, as long as density is similar across clusters.
Why reduce dimensions: distance stops meaning much
Clustering and neighbor methods run on distances, and distances degrade as columns pile up. In very high-dimensional spaces Euclidean distances become inflated, an instance of the curse of dimensionality. scikit-learn suggests running a reduction such as PCA before k-means to ease the problem and speed up computation.[3] There are other reasons to reduce: to draw data in two dimensions, to remove noisy or redundant columns, to break up multicollinearity among predictors, and to make slow downstream models fast.
The methods fall into two families. Linear projections, PCA and SVD, rotate the axes and drop some of them, and the same matrix multiplication applies to new data. Manifold methods, t-SNE and UMAP, bend space to keep neighborhoods together. They reveal structure that straight lines miss, at the cost of distorting other things.
Principal component analysis, from covariance to scores
Principal component analysis decomposes a dataset into successive orthogonal components that explain a maximum amount of the variance.[5] Orthogonal means at right angles, so the new axes are uncorrelated. Successive means the first component captures as much variance as any single direction can. The second captures as much of the remaining variance as possible while staying orthogonal to the first, and so on.
The recipe has five steps:
- Center each column by subtracting its mean. Usually also divide by its standard deviation, which is called standardizing.
- Form the covariance matrix C of the columns.
- Find the eigenvectors and eigenvalues of C. Each eigenvector is a component direction, and its eigenvalue is the variance of the data along that direction.
- Sort the components by eigenvalue and keep the first k.
- Project. Each row's score on a component is the dot product of the centered row with that unit-length eigenvector.
Here is a worked example. Two centered columns have covariance matrix C = [[2, 1], [1, 2]]: each has variance 2, and their covariance is 1. The eigenvalues λ solve (2 - λ)2 - 1 = 0, so λ = 3 or λ = 1. For λ = 3 the eigenvector is (1, 1)/√2, the diagonal along which both columns rise together. For λ = 1 it is (1, -1)/√2. The explained variance ratio of each component is its eigenvalue divided by the total: 3/4 = 75 percent and 1/4 = 25 percent. A centered row (3, 1) scores (3 + 1)/√2 = 2.83 on the first component and (3 - 1)/√2 = 1.41 on the second.
Now flip one input: the units. scikit-learn's PCA centers the data but does not scale each feature before applying the SVD.[5] Suppose the two columns are annual income in dollars, with standard deviation 10,000, and age in years, with standard deviation 10, and their correlation is 0.5. Their covariance is 0.5 × 10,000 × 10 = 50,000, so the covariance matrix is [[100,000,000, 50,000], [50,000, 100]]. The first eigenvalue is about 100,000,025 and the second about 75. The first component claims more than 99.999 percent of the variance and points almost exactly along income. PCA has discovered nothing here; it has measured your units. Standardize first and the covariance matrix becomes the correlation matrix [[1, 0.5], [0.5, 1]]. Its eigenvalues are 1.5 and 0.5, a 75/25 split along the diagonal, just as in the first run.
To choose how many components to keep, look at the cumulative explained variance. One common rule keeps the smallest number of components that reaches a target such as 90 or 95 percent. Another reads the bend of a scree plot, which is the elbow idea applied to eigenvalues. In this fictional six-feature dataset, four components are needed to reach 90 percent:
| Component | Explained variance ratio | Cumulative |
|---|---|---|
| PC1 | 0.52 | 0.52 |
| PC2 | 0.21 | 0.73 |
| PC3 | 0.12 | 0.85 |
| PC4 | 0.08 | 0.93 |
| PC5 | 0.05 | 0.98 |
| PC6 | 0.02 | 1.00 |
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
pipe = make_pipeline(StandardScaler(), PCA())
pipe.fit(X_train) # fit on training rows only
ratios = pipe.named_steps["pca"].explained_variance_ratio_
print(ratios.cumsum().round(2)) # for example [0.52 0.73 0.85 0.93 0.98 1. ]
Know the limits. PCA finds linear directions only. scikit-learn's manifold guide notes that linear methods like it can be powerful but often miss important non-linear structure.[6] Components are blends of all the inputs, so "component 2" rarely has a business name. Outliers inflate variance and can capture a component on their own. PCA never looks at a target, so a low-variance direction you dropped may be the one that predicts the outcome. Standard PCA also processes all the data in one batch in memory; scikit-learn's IncrementalPCA exists for data too large for that. Finally, fit the scaler and the PCA on training rows only and then apply them to validation and test rows. Otherwise the components carry information from data the model should not have seen.
The core of it: PCA rotates centered data onto orthogonal axes ordered by variance, using the eigenvectors of the covariance matrix. Standardize first unless the units are already comparable, and keep enough components to reach the explained variance you need.
Singular value decomposition: the factorization under PCA
Singular value decomposition factors any n × p matrix X, square or not, into three pieces:
X = U Σ VT
- U is n × r with orthonormal columns. It gives one row of coordinates per observation.
- Σ is an r × r diagonal matrix of singular values σ1 ≥ σ2 ≥ ... ≥ σr > 0, where r is the rank of X.
- V is p × r with orthonormal columns. It gives one direction per factor, written in terms of the original columns.
Each singular value measures how much of the matrix lies along its pair of directions. The link to PCA is direct. If X is centered, the columns of V are the principal component directions, and each PCA eigenvalue equals σi2/(n - 1). Libraries compute PCA through the SVD because it is numerically more stable than forming the covariance matrix explicitly. Dropping the singular vectors tied to the smallest singular values projects the data onto a lower-dimensional space that keeps most of the variance.
A small check you can do by hand: the matrix [[2, 2], [1, 1]] has rank 1. Its SVD has one nonzero singular value, σ1 = √10 ≈ 3.16, with u1 = (2, 1)/√5 and v1 = (1, 1)/√2. Multiply back. Since √10 × (1/√5) × (1/√2) = 1, the product σ1u1v1T equals [[2, 2], [1, 1]] exactly. A rank-1 matrix is one pattern scaled up and down, and the SVD finds that pattern.
Keeping only the top k singular values gives a rank-k approximation. By the Eckart-Young theorem, no other rank-k matrix is closer to X in total squared error. The share of the matrix's squared size kept, often called energy, is the sum of the kept σ2 values divided by the sum of all of them. In a fictional ratings matrix with singular values 9, 4 and 1, the squares are 81, 16 and 1, a total of 98:
| Factor | σ | σ squared | Share of energy | Cumulative |
|---|---|---|---|---|
| 1 | 9 | 81 | 82.7% | 82.7% |
| 2 | 4 | 16 | 16.3% | 99.0% |
| 3 | 1 | 1 | 1.0% | 100% |
Two factors keep 99 percent of the energy, and the third is close to noise. SVD shows up well beyond PCA:
- Latent semantic analysis. scikit-learn's TruncatedSVD implements a variant of singular value decomposition that computes only the k largest singular values.[5] Because it does not center the data, it can work directly on a sparse document-term matrix, such as the term frequency inverse document frequency (TF-IDF) matrices used in natural language processing, the subject of Lesson 26. Centering would replace every zero with a nonzero value and destroy the sparsity, which is why plain PCA is the wrong tool there.
- Recommender systems. A users-by-items matrix factors into user tastes and item traits. Classical SVD needs a complete matrix, but most real ratings are missing, so production systems fit the factors on observed entries only, for example with alternating least squares (ALS).
- Compression and denoising. Images, sensor arrays and embeddings can be stored as a few singular vectors, and the small factors you discard often hold mostly noise.
The core of it: SVD writes any matrix as U Σ VT. PCA is the SVD of centered data, and truncated SVD keeps the top k factors of uncentered, often sparse, data.
t-SNE and UMAP: maps of neighborhoods
Picture a sheet of paper rolled into a spiral, the "Swiss roll" used in many demonstrations. Two points on adjacent layers of the roll are close in straight-line distance but far apart along the sheet. PCA, which only rotates and drops axes, flattens the roll by squashing its layers together. A manifold is a lower-dimensional surface like that sheet, curving through a higher-dimensional space. Manifold learning tries to generalize linear methods like PCA so that they become sensitive to that kind of non-linear structure.
T-distributed stochastic neighbor embedding (t-SNE), published by Laurens van der Maaten and Geoffrey Hinton in 2008, works in three moves. First, for each point it converts distances to the other points into probabilities with a Gaussian kernel, so near neighbors get high probability. The kernel's width is set separately for each point so that each point has a chosen effective number of neighbors, called the perplexity. Second, it places the points in two or three dimensions and computes similar probabilities there, using a Student t-distribution with one degree of freedom. Its heavy tails let moderately distant points spread apart instead of crowding into the middle.
Third, it moves the low-dimensional points by gradient descent to minimize the Kullback-Leibler (KL) divergence between the two sets of probabilities. KL divergence measures how far one probability distribution is from another. It is zero when they match, grows as they differ, and is not symmetric. For high-dimensional probabilities pij and low-dimensional ones qij, it is Σ pij log(pij/qij). Each term is weighted by pij, so drawing true neighbors far apart (large p, small q) costs a lot, while drawing non-neighbors close together (small p) costs little. That asymmetry is why t-SNE keeps local neighborhoods and treats the global layout as an afterthought.
The consequences are what the exam tests. The size of a cluster on a t-SNE plot says little about its spread in the original space. The gap between two clusters says little about how different they are. Different random seeds and perplexities give different pictures. And scikit-learn's TSNE has no transform step for new points: it lays out the rows you gave it, and a new row means a new run. Parametric variants of t-SNE, which train a network to perform the mapping, can embed new points, but that is not the standard method.
Uniform manifold approximation and projection (UMAP), developed by Leland McInnes and colleagues, is a dimension reduction algorithm based on manifold learning and ideas from topological data analysis.[7] It works in two stages. The first stage builds a weighted graph of the data. Each point connects to its k nearest neighbors, using a k-neighbor graph instead of balls of one fixed radius.[7] Each point also gets its own sense of distance: in the documentation's words, a unit ball about a point stretches to its k-th nearest neighbor.[7] A point in a sparse region and a point in a dense region therefore both see about k neighbors. The edges are fuzzy, not simply on or off. Each point is fully connected to its closest neighbor, and the connection strength then decays with distance beyond that first nearest neighbor.[7]
The second stage places the points in two or a few dimensions, builds the matching fuzzy graph there, and moves the points until the low-dimensional edge weights match the high-dimensional ones as closely as possible. The mismatch is scored with a cross-entropy between the two sets of edge weights. It penalizes both pulling true neighbors apart and pushing unrelated points together, and stochastic gradient descent minimizes it. That second penalty is one reason UMAP often keeps more of the global arrangement than t-SNE does.
The two main settings follow from this mechanism. n_neighbors is the k of the graph. A small value makes each point's view very local, so the embedding shows fine detail and may break real groups into fragments. A large value lets each point see further, so broader structure survives and fine detail blurs. min_dist controls how tightly points may pack together in the output. It changes how dense each island looks, not which points count as neighbors, so a small value gives tight clumps, useful before clustering, and a larger one spreads points out for a readable picture. A fitted UMAP model in the umap-learn library can place new rows into an existing embedding. Because both t-SNE and UMAP start from nearest neighbor search, put all features on the same scale first.
| Property | PCA | t-SNE | UMAP |
|---|---|---|---|
| Kind of mapping | Linear projection | Nonlinear embedding | Nonlinear embedding |
| What it keeps best | Directions of global variance | Local neighborhoods | Local neighborhoods, often with more of the global arrangement than t-SNE |
| Main settings | Number of components | Perplexity | n_neighbors, min_dist |
| New rows | The same projection applies | scikit-learn's TSNE: rerun; parametric variants can embed them | A fitted model can transform them |
| Repeat runs | Identical with the exact solver; randomized solvers can vary slightly unless seeded | Vary with the random seed | Vary with the seed unless it is fixed |
| Typical use | Preprocessing, compression, noise removal | 2D or 3D visualization | Visualization; also preprocessing for clustering |
| Distances between clusters | Meaningful along kept components | Not meaningful | Only loosely meaningful |
So what can you conclude from one of these pictures? Points drawn together were probably neighbors in the original space, and that much is reliable. Separate islands suggest groups worth investigating with a method that works in the original space. Cluster sizes, gaps between islands and the axes themselves carry no units, and they should not appear on a business slide as measurements.
The core of it: PCA is a linear projection you can reuse on new rows. t-SNE and UMAP build neighbor-based nonlinear maps for viewing structure, where closeness within an island is meaningful and sizes and gaps are not.
K-nearest neighbors: the search underneath everything else
The k-nearest neighbors algorithm starts from one idea: for a query point, find a fixed number k of stored points that are closest to it in distance. In scikit-learn, the NearestNeighbors class is an unsupervised learner for neighbor searches. It needs no labels. For each query it returns the indices of the k closest points and their distances, and its default number of neighbors for queries is 5. The documented example fits three points and asks which one is closest to (1, 1, 1):
>>> from sklearn.neighbors import NearestNeighbors
>>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
>>> neigh = NearestNeighbors(n_neighbors=1)
>>> neigh.fit(samples)
NearestNeighbors(n_neighbors=1)
>>> print(neigh.kneighbors([[1., 1., 1.]]))
(array([[0.5]]), array([[2]]))
The output says the nearest point is at distance 0.5 and is the third sample, index 2, because indexing starts at 0. You can confirm the distance by hand: (1, 1, 1) minus (1, 1, 0.5) is (0, 0, 0.5), whose length is 0.5. The default metric is Minkowski distance with p = 2, which is ordinary Euclidean distance.
Why does an unsupervised objective list KNN at all? Because neighbor search is the engine inside other methods. scikit-learn notes that many of its estimators rely on nearest neighbors, among them the KNN classifier and regressor, DBSCAN, spectral clustering, and the TSNE and Isomap embeddings.[8] DBSCAN counts neighbors within eps. t-SNE sets each point's kernel width from its neighbors. UMAP builds its graph from the k nearest neighbors. On its own, the search answers practical questions: which products resemble this one, which records might be duplicates, which missing values can be filled from similar rows (KNN imputation), and which points are anomalies because even their k-th neighbor is far away.
Supervised KNN adds one step: look up the labels of the k neighbors and let them vote (classification) or average them (regression). Nothing is learned in advance. That is why scikit-learn calls neighbors-based methods non-generalizing: they simply remember the training data, often stored in an index such as a KD tree or ball tree.[8] The work happens at query time, so prediction cost grows with the amount of stored data.
| Property | k in KNN | k in k-means | k in a k-distance plot |
|---|---|---|---|
| What it counts | Neighbors consulted per query | Clusters to form | The neighbor whose distance is plotted (set to min_samples) |
| Needs labels? | Search: no; classifier: yes | No | No |
| Output | A neighbor list, or a vote | A label per point and k centroids | A sorted curve for choosing DBSCAN's eps |
| Raising it | Smoother, more biased predictions | Lower inertia, finer segments | A larger suggested eps |
Two failure modes recur. Distances depend on scale, so a column in dollars swamps a column in years unless you standardize. And in many dimensions the nearest and farthest neighbors end up at similar distances, which is the curse of dimensionality again. Reducing dimensions first, often with PCA, restores some contrast between near and far.
Exam cues: matching the stem to the method
| Words in the question | Points to | Do not confuse with |
|---|---|---|
| "Specify the number of clusters in advance", "centroids", "minimize within-cluster sum of squares" | k-means | KNN, whose k counts neighbors, not clusters |
| "Plot inertia against k and look for the bend" | Elbow method | Scree plot, the same idea applied to PCA eigenvalues |
| "Compare distance to own cluster with nearest other cluster", "ranges from -1 to 1" | Silhouette score | Inertia, which measures compactness only |
| "Dendrogram", "nested", "linkage", "cut the tree" | Hierarchical (agglomerative) clustering | DBSCAN, which builds no tree in its basic form |
| "Arbitrary shapes", "label outliers as noise", "eps", "minimum points" | DBSCAN | k-means, which assigns every point to a cluster |
| "Clusters of varying density" | HDBSCAN | DBSCAN, which assumes similar density |
| "Orthogonal components", "maximum variance", "explained variance ratio", "linear" | PCA | t-SNE and UMAP, which are nonlinear |
| "Visualize high-dimensional data in 2D", "perplexity", "local structure" | t-SNE | PCA, which keeps global variance |
| "Transform new points", "n_neighbors and min_dist", "topological", "faster than t-SNE" | UMAP | t-SNE, whose scikit-learn version has no transform step |
| "Find the most similar records", "no labels", "k closest points" | Unsupervised nearest neighbor search (KNN) | KNN classification, which needs labels |
| "Singular values", "U Σ V transpose", "sparse term matrix", "latent factors", "low-rank approximation" | SVD (truncated SVD for sparse data) | PCA, which centers the data and so suits dense data |
Common misconceptions
- "The silhouette score finds the true number of clusters." It finds the best-separated number. In scikit-learn's own example it prefers two clusters for data generated from four, because three of the groups touch. Treat the peak as evidence, then check per-cluster silhouettes and business meaning.
- "The k in KNN and the k in k-means are the same setting." KNN's k is how many neighbors a query consults. The k in k-means is how many groups to form. A KNN search with k = 5 forms no clusters at all.
- "DBSCAN needs no tuning because it finds the number of clusters itself." It trades k for eps and min_samples, and the count it returns depends on them. In the seven-customer example, moving eps from 1.5 to 4.5 turned two clusters and one outlier into a single cluster.
- "Sizes and distances on a t-SNE plot are measurements." t-SNE keeps track of which points are neighbors. Island sizes and gaps change with perplexity and seed, and they do not reflect spread or difference in the original space.
- "PCA keeps the most important features." PCA keeps directions of high variance, which are blends of all features, and it never looks at a target. A column measured in large units can dominate for no reason other than its units, and a low-variance direction can be the one that predicts the outcome.
- "SVD and PCA are rival methods." PCA is usually computed as an SVD of centered data. The practical choice is between centering (PCA, for dense data) and not centering (truncated SVD, for sparse data).
Putting it together
- k-means alternates assigning each point to the nearest centroid and moving each centroid to its members' mean. Each step lowers inertia, so it converges, but only to a local minimum, and every point, outliers included, is forced into a cluster.
- Inertia always falls as k grows. The elbow method looks for the bend in that curve. The silhouette score, s = (b - a)/max(a, b), runs from -1 to +1 and compares own-cluster distance with nearest-other-cluster distance.
- A silhouette near 0 means a point sits on a boundary. A negative silhouette means it is closer to another cluster and may be misassigned.
- Agglomerative clustering merges the closest clusters under a linkage rule (single, complete, average or Ward). It records the merges in a dendrogram that you cut, after fitting, to get any number of clusters.
- DBSCAN uses eps and min_samples to label points as core, border or noise. It finds clusters of any shape, labels noise -1, and struggles when clusters differ in density, which HDBSCAN addresses.
- PCA projects centered data onto orthogonal directions of maximum variance. scikit-learn centers but does not scale, so standardize when units differ, and fit the scaler and PCA on training rows only.
- SVD factors any matrix as U Σ VT. For centered data, PCA eigenvalues equal σ2/(n - 1), and truncated SVD keeps the top k factors of uncentered sparse data such as TF-IDF matrices.
- t-SNE (set by perplexity, scored by KL divergence) and UMAP (set by n_neighbors and min_dist, built on a fuzzy k-neighbor graph) make nonlinear maps that keep local neighborhoods. scikit-learn's TSNE has no transform step, while a fitted UMAP model can place new rows, and neither map's cluster sizes or gaps are measurements.
- Unsupervised KNN search returns each point's k closest points and powers DBSCAN, t-SNE and UMAP. KNN classification adds a label vote, which makes it supervised.
Sources
- scikit-learn developers. (n.d.). Selecting the number of clusters with silhouette analysis on KMeans clustering. scikit-learn.org
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn developers. (n.d.). 2.3. Clustering. scikit-learn.org
- scikit-learn developers. (n.d.). Demo of DBSCAN clustering algorithm. scikit-learn.org
- scikit-learn developers. (n.d.). 2.5. Decomposing signals in components (matrix factorization problems). scikit-learn.org
- scikit-learn developers. (n.d.). 2.2. Manifold learning. scikit-learn.org
- Leland McInnes. (n.d.). How UMAP Works. umap-learn documentation (Read the Docs). umap-learn.readthedocs.io
- scikit-learn developers. (n.d.). 1.6. Nearest Neighbors. scikit-learn.org
- Key terms
- Inertia
- The within-cluster sum of squares that k-means minimizes: the sum, over all points, of the squared distance from each point to its cluster's centroid. Lower is better, but it always falls as the number of clusters grows.
- Elbow method
- A way to choose the number of k-means clusters by plotting the best inertia against k and picking the bend where adding another cluster stops reducing inertia much.
- Silhouette coefficient
- A per-point clustering score, (b - a) divided by the larger of a and b, where a is the mean distance to the point's own cluster and b the mean distance to the nearest other cluster. It runs from -1 (likely misassigned) through 0 (on a boundary) to +1 (well separated).
- Linkage
- The rule hierarchical clustering uses to measure the distance between two clusters: single (closest pair), complete (farthest pair), average (mean of all pairs) or Ward (increase in within-cluster sum of squares).
- Core sample
- In DBSCAN, a point with at least min_samples points within radius eps. Clusters grow by linking core samples; points near a core sample are border points, and the rest are labeled noise.
- Principal component
- A direction found by PCA: an eigenvector of the data's covariance matrix, orthogonal to the other components, ordered by the variance of the data along it.
- Explained variance ratio
- The share of a dataset's total variance captured by one principal component, equal to its eigenvalue divided by the sum of all eigenvalues. It is often summed cumulatively to decide how many components to keep.
- Singular value decomposition
- The factorization of any matrix X into U times a diagonal matrix of singular values times the transpose of V. Keeping the largest singular values gives the best low-rank approximation in squared error.
- Perplexity
- The main t-SNE setting: roughly the effective number of neighbors each point considers. It sets the width of each point's Gaussian kernel, and changing it changes the resulting picture.
- Nearest neighbor search
- An unsupervised procedure that returns, for a query point, the k stored points closest under a chosen distance, along with their distances. It needs no labels and underlies DBSCAN, t-SNE, UMAP and KNN classification.
Module 4: Operations and Processes
Data science across the business, obtaining, ingesting, storing and wrangling data, life cycle best practices, DevOps and MLOps, and deployment environments.
Data Science Across the Business
- Turn a vague business request into requirements, a measurable KPI and the most appropriate solution, including options that use no machine learning.
- Classify fields as PII, quasi-identifiers or proprietary data, and choose anonymization and obfuscation techniques by whether they can be reversed and whether joins still work.
- Explain how data use regulations such as the UK GDPR, HIPAA and FERPA limit what a data science project may do.
- Build a cost-benefit recommendation with break-even figures, and state the relevant range of application in which it holds.
A one-line request from the retention team
The email below is a fictional example. It comes from the vice president (VP) of retention at Fennel Box, an imaginary meal-kit subscription company with 120,000 active subscribers. Fennel Box has sold in the United States for three years and opened in the United Kingdom eight months ago. The email reaches the data science team on a Tuesday in March.
Subject: churn. We lost 4,812 subscribers last month. Can data science build us an AI model that predicts who is about to cancel? We would like it live before the summer promotion.
The VP is asking for an artificial intelligence (AI) model. The message does not say what anyone will do with a prediction, how success will be counted, what the project may cost or which data it may use. The subscriber tables hold names, home addresses, dates of birth, the last four digits of payment cards and free-text delivery notes such as \"nut allergy, leave by the side gate\". Each order row also carries the price Fennel Box pays its suppliers, a number its competitors would very much like to see. Before training any model, a senior data scientist has to turn this email into a decision that data can improve, and find out what the data may legally be used for.
We will follow this request from the inbox to a recommendation memo. The exam bullets come up in the order a working data scientist meets them. Requirements come first. Measures and indicators follow, then the data and the rules around it, and finally the choice of solution and whether it pays.
Exam objectives: 4.1 Explain the role of data science in various business functions.[1] The objective names three groups of ideas. The first is compliance, security and privacy: personally identifiable information (PII), proprietary data, anonymizing sensitive data, data obfuscation and data use regulations. The second is measures, metrics and key performance indicators (KPIs). The third is requirements gathering: making recommendations based on cost-benefit analyses, translating a business need to the most appropriate solution, and the relevant range of application.
Requirements gathering: from \"an AI model\" to a decision
Requirements gathering is the structured work of finding out what a project must do, for whom, under which constraints, and how its success will be judged. In data science it has one special job: connecting a prediction to an action. A churn score has no value of its own. It is worth something only when someone acts differently because of it, and only to the extent that the new action beats what they would have done anyway.
So the first meeting with the retention team is an interview, not a demo. Ask these questions, each for a reason:
- What decision will the output change? If no decision changes, the project produces a report nobody acts on.
- Who acts on it, and how often? Capacity caps the value. A list of 10,000 at-risk customers is useless to a team that can call 1,500.
- When must the output arrive? Timing sets the architecture. A weekly batch file costs far less to build and run than a real-time application programming interface (API).
- What does each kind of error cost? Calling a customer who was never going to leave wastes an offer. Missing one who leaves loses their future margin. These costs drive the threshold chosen later.
- How will we know it worked? Agree the measure before building, so nobody redefines success after seeing the results.
- What constraints apply? Law, contracts, explainability, budget, deadline and the systems the output must feed.
- What is out of scope? Writing down non-goals stops a churn project from quietly turning into a pricing project.
Requirements come in two kinds. Functional requirements say what the system must produce: here, a ranked list of subscribers with a reason code for each. Non-functional requirements set limits on speed, quality and conditions: refreshed weekly, explainable to a call-center agent, compliant with data protection law. Non-functional requirements often decide the solution more than functional ones. Here, \"weekly is fast enough\" rules out a streaming system before anyone has priced one.
The team holds two interviews, one with the retention team and one with finance, plus a short call with the company's privacy officer. It then writes the brief below. All values are fictional.
| Area | Question asked | What the business said |
|---|---|---|
| Decision | What will someone do differently? | Choose which subscribers get a retention call offering a $15 account credit |
| Actor and capacity | Who acts, and how often? | Two retention agents, about 1,500 calls a month |
| Timing | How early is useful? | At least 7 days before the subscriber's next billing date; a weekly list is enough |
| Error costs | What does each mistake cost? | A wasted call costs the $15 credit plus about $0.50 of agent time; a missed canceller costs about $180 of future margin |
| Success measure | How will we judge it? | Retention of called subscribers compared with a randomly held-back group of similar subscribers |
| Scope of first release | Which customers? | US subscribers first; the VP wants UK subscribers covered by year-end |
| Constraints | Law, explainability, systems | The UK General Data Protection Regulation (UK GDPR) will apply once UK subscribers' records are used; agents need a plain reason for each call; output feeds the call-center queue as a file |
| Non-goals | What is out of scope? | Changing prices; the new office-lunch product launched last month |
Three rows will matter later. The capacity of 1,500 calls decides which model metric matters. The UK extension decides which law the design must already satisfy. The office-lunch non-goal is the first hint of the relevant range of application: the population for which the model's answers can be trusted.
Bottom line: requirements gathering turns a request for a technique (\"an AI model\") into a decision, an actor, a capacity, a deadline, error costs and an agreed success measure. Without those, nobody can judge whether a later choice of model or metric was right.
Measures, metrics and key performance indicators
The VP's email contains a number, 4,812. It is a measure: a raw, quantified observation, here a count of cancellations in one month. On its own it says little. Is 4,812 a lot? That depends on how many subscribers there were.
A metric puts one or more measures into a form you can compare and act on. It is usually a ratio, a rate, or a value tracked over time against a target. Divide the cancellations by the subscribers active at the start of the month and you get a monthly churn rate:
monthly churn rate = cancellations during month / active subscribers at start of month
= 4,812 / 120,000
= 0.0401, or about 4.0 percent
The third term, Key performance indicator (KPI), names one of the few metrics an organization tracks because it maps directly to a strategic goal. A KPI has a named owner, a target and a regular reporting schedule. The National Institute of Standards and Technology (NIST) spells out the relationship in its 2024 measurement guide. Key risk indicators (KRIs) and KPIs are kinds of metrics, but not every metric is one of them.[2] A KRI warns that a risk is growing; a KPI shows whether a goal is being met.
Definitions decide the numbers. Suppose 1,212 of the 4,812 cancellations happened because a card payment failed and the account lapsed, not because the subscriber chose to leave. Then:
| Definition | Numerator | Denominator | Rate |
|---|---|---|---|
| All churn | 4,812 | 120,000 | 4.0% |
| Voluntary churn only | 3,600 | 120,000 | 3.0% |
| Involuntary (payment-failure) churn | 1,212 | 120,000 | 1.0% |
The two kinds of churn have different causes and different fixes, so a KPI that mixes them hides what is happening. Once you choose a definition, keep it stable: a metric calculated the same way month after month shows trends and normal ranges. If the churn definition changed in June, June's rate cannot be compared with May's.
The step from measure to KPI also separates model metrics from business indicators. Lesson 2 covered the area under the curve (AUC) of the receiver operating characteristic (ROC) curve, together with precision and recall. Those numbers tell you how well a model ranks or classifies. They are not KPIs for the retention team: a model can reach an AUC of 0.85 while the campaign built on it loses money. The KPI is the business result the team is trying to move. For Fennel Box the team writes one KPI card with a guardrail:
| Field | Value |
|---|---|
| Name | Retention lift among called subscribers |
| Definition | 60-day retention rate of called subscribers minus that of a randomly held-back group drawn from the same ranked list |
| Owner | VP of retention |
| Target | At least 10 percentage points |
| Cadence | Monthly, for each month's group of flagged subscribers |
| Guardrail metric | Credit cost per extra retained subscriber stays below $180, the margin one retained subscriber brings |
Why use a held-back group? Because a raw count of \"saves\" rewards the wrong behavior. If agents are scored on how many called customers stay, the easiest way to win is to call people who were never going to leave. A KPI measured against a random control shows what the calls actually caused. Pairing it with a cost guardrail stops the team from buying retention at any price. This is Goodhart's law in practice: once a measure becomes a target, it tends to stop measuring what it used to.
Metrics serve compliance and security as well as revenue. A privacy team might track the mean time taken to correct or delete inaccurate personal data, and a security team the cost per incident. A note on currency: many study materials still cite the older NIST guide, SP 800-55 Revision 1 from 2008. NIST withdrew it on 4 December 2024 and replaced it with the two-volume SP 800-55.[3]
Bottom line: a measure is a raw count, a metric puts measures in comparable form, and a KPI is one of a few metrics tied to a strategic goal, with an owner and a target. Define each precisely, keep the definition stable, and judge business outcomes against a control group, not by model scores.
What is in the warehouse: PII, quasi-identifiers and proprietary data
Before any modeling, the team builds a data inventory. It lists every field the project might use and gives each a classification. The inventory decides what may be copied into an analytics environment, and in what form.
| Field | Example value | Classification | Reason |
|---|---|---|---|
| full_name | Dana Whitfield | PII, direct identifier | Identifies a person on its own |
| dana.w@example.com | PII, direct identifier | Identifies a person on its own | |
| customer_id | C-0048213 | PII, linkable identifier | Anyone with the customer table can look the person up |
| birth_date | 1987-04-12 | Quasi-identifier | Identifying in combination with other fields |
| postcode | 02139 | Quasi-identifier | Identifying in combination with other fields |
| card_last4 | 1111 | Payment data, PII when linked | Partial card data; the full number stays with the payment processor |
| delivery_notes | Nut allergy, leave by the side gate | Sensitive free text | Can reveal health conditions, religion and household details |
| skips_last_90d | 3 | PII while linked to an account | Describes the behavior of a subscriber who can be identified through the linked account |
| supplier_unit_cost | 2.14 | Proprietary | Commercially confidential; describes no individual |
| churn_model_v3 (file) | Trained model weights | Proprietary | Company intellectual property |
Personally identifiable information (PII) has several official definitions. One in NIST's online glossary, drawn from NIST SP 800-88 Revision 2, describes PII as any data that can distinguish or trace a person's identity, either alone or in combination with other information.[4] The second half of that definition is the part people miss. A name identifies directly. A birth date, a postcode and a sex identify indirectly, and often just as well.
That gives two kinds of identifying field. A direct identifier points to one person by itself: a name, an email address, an account number, a national identity number. A quasi-identifier is harmless alone but identifying in combination: a birth date, a postcode, sex, a job title, the date of an unusual event. Most re-identification happens through quasi-identifiers, because those are the fields people leave in when they \"remove the PII\".
PII also reaches data that is merely attached to an identity. Other definitions in the same glossary cover information combined with other information that is linked or linkable to a specific individual.[4] A subscriber's skip history names nobody. But while it sits on a row with her customer identifier (ID), it is linked to her, so it counts as PII for as long as that link exists. Break the link properly and it stops being PII.
Laws often use a different term. The European Union (EU) General Data Protection Regulation (GDPR), and the UK GDPR that the United Kingdom kept after leaving the EU, speak of personal data. NIST's de-identification report quotes an International Organization for Standardization (ISO) definition of personal data: any information relating to an identified or identifiable natural person.[5] That framing does not start from a list of identifier types. It asks only whether the information relates to someone who can be identified, directly or indirectly, so in practice it tends to reach at least as far as the US definitions, which are often built around named examples such as social security numbers.
Proprietary data is a different kind of thing. It is information the organization owns or licenses and keeps confidential for business reasons. Examples include supplier prices, margins, source code, feature definitions, trained model weights and data bought from third parties. It is protected by contracts, trade-secret and intellectual-property law, and internal classification policies, not by privacy law. It may contain no personal information at all. The two categories can overlap: Fennel Box's customer list is both personal data and a proprietary asset.
Licensed third-party data needs special care, because the license, not your judgment, sets what you may do with it. Suppose a demographics file was bought \"for internal analytics only, delete after 12 months\". It cannot be used to train a model sold to partners, and it cannot be kept in a feature store forever.
The everyday risks to proprietary data in data science are mundane. An analyst pastes supplier costs into a public chat tool to tidy a table. A model trained on licensed data is shared with a partner. A notebook showing real margins is pushed to a public code repository. Each leaks value with no personal data involved.
Bottom line: PII includes anything that can identify a person alone or in combination, plus data linked to an identity, so quasi-identifiers and linked behavior records count. Proprietary data is protected because the business owns or licenses it, not because it describes a person, and a single dataset can be both.
Data use regulations: what the rules let the project do
Data use regulations are the laws, sector rules and binding agreements that govern how data may be collected, processed, shared, kept and deleted. Which ones apply depends on four things: whose data it is, where those people live, what kind of data it is, and what kind of organization holds it. The data scientist's job is not to give legal advice. It is to recognize when a rule applies, design within it, and bring in the privacy officer or legal counsel early.
| Rule | Whose data | What it governs | Effect on analytics |
|---|---|---|---|
| GDPR (EU) and UK GDPR | People in the EU or UK | All processing of personal data, under seven principles | Purpose, minimisation, retention and accountability shape every dataset |
| Health Insurance Portability and Accountability Act (HIPAA), US | Health information held by health plans, health care providers, clearinghouses and their business associates | Use and disclosure of protected health information | Properly de-identified data falls outside the Privacy Rule |
| Family Educational Rights and Privacy Act (FERPA), US | Student education records | Disclosure of records by schools and universities | De-identified records can be released without consent |
| California Consumer Privacy Act (CCPA), US state law | California residents | Collection, sale and sharing of personal information | Rights to know, delete and opt out affect training data |
| Payment Card Industry Data Security Standard (PCI DSS) | Payment card data | An industry standard enforced by contract, not a statute | Tokenizing card numbers shrinks the set of systems in scope |
| Contracts and data licenses | Whatever the agreement covers | Permitted uses, sharing, retention | Can forbid uses that the law would allow |
Fennel Box's first release trains and scores on US subscribers only. The VP, though, wants UK subscribers covered by the end of the year. The moment UK subscribers' records enter a training extract or a scoring run, the UK GDPR governs that processing, so the team checks the design against it now rather than rebuilding the pipeline later. Article 5 of the UK GDPR sets out seven key principles: lawfulness, fairness and transparency; purpose limitation; data minimisation; accuracy; storage limitation; integrity and confidentiality; and accountability.[6] Four of them change what the team does next.
- Purpose limitation. Personal data must be collected for specified, explicit and legitimate purposes, and not further processed in a way incompatible with them.[6] Addresses were collected to deliver food. Building a churn model from them is a new purpose, so the team must confirm with the privacy officer that it is compatible, or find another lawful basis. The same article treats further processing for statistical purposes as not incompatible. A model that picks individuals for marketing calls, though, does more than produce statistics.
- Data minimisation. Data must be adequate, relevant and limited to what the purpose needs.[6] The delivery notes (\"nut allergy\") add almost nothing to a churn prediction and can reveal health information, which the GDPR places in a special category with extra protection. They stay out, for US and UK subscribers alike: one pipeline, one standard.
- Storage limitation. Data that identifies people must be kept no longer than the purpose needs. Training snapshots need a deletion date.
- Accountability. The organization in charge of the data (the controller) must be responsible for compliance and able to demonstrate it. In practice that means a written record of the purpose, the fields used, the de-identification applied and who approved it.
The stakes are real. The Information Commissioner's Office (ICO), the UK data protection regulator, notes that breaches of these principles fall in the highest tier of fines. That tier reaches £17.5 million or 4% of total worldwide annual turnover, whichever is higher.[6] The rules also change. The ICO updated its purpose-limitation guidance on 23 March 2026 to reflect amendments made by the Data (Use and Access) Act.[6] Check the current text, not last year's slides.
US sector laws work differently. They mostly attach rules to particular kinds of data and particular holders, and several of them release properly de-identified data from their requirements. NIST's de-identification report says HIPAA's privacy and security requirements do not apply to de-identified health information. The condition is that there is \"no reasonable basis to believe that the information can be used to identify an individual\".[5] The report also records the US Department of Education's position that FERPA's restrictions do not apply to de-identified student records.[5]
Card data follows a similar logic. Replacing card numbers with tokens shrinks the set of systems that ever handle real card numbers, and so shrinks the part of the business that PCI DSS covers. De-identification is therefore a business tool as well as an ethical one: it changes which rules apply and how much of the system they cover.
Anonymizing sensitive data: why deleting the name column is not enough
Three terms get used loosely, and the exam expects you to keep them apart.
- De-identification is the umbrella term: any process that removes or transforms identifying information so the data is less closely linked to individuals. It lowers the privacy risk of using, archiving, sharing and publishing personal data.
- Anonymization is de-identification taken far enough that nobody can reasonably re-identify individuals, including the organization that did it. It is meant to be irreversible. Under the GDPR, truly anonymous data is no longer personal data.
- Pseudonymization replaces identifiers with substitutes (pseudonyms or tokens) while keeping a way to link records, and often a way to reverse the substitution. Under the GDPR, pseudonymized data is still personal data, because whoever holds the key or the lookup table can re-identify it.
The threat that separates these terms is the linkage attack. An attacker joins a \"de-identified\" dataset to another dataset that shares its quasi-identifiers, such as a voter roll, a social media profile or a leaked customer file. Here is a small worked example of how the attack works and how to measure the risk.
The team extracts six rows (fictional), removes the names and checks what is left.
| Row | Postcode | Birth year | Sex | Cancelled |
|---|---|---|---|---|
| 1 | 02139 | 1987 | F | Yes |
| 2 | 02139 | 1991 | M | No |
| 3 | 02141 | 1985 | F | No |
| 4 | 02142 | 1964 | M | Yes |
| 5 | 02139 | 1993 | M | No |
| 6 | 02141 | 1962 | M | Yes |
Every combination of postcode, birth year and sex is unique. Anyone who knows that their neighbor Dana is a woman born in 1987 who lives in 02139 can find her row and learn that she cancelled. The table has lost the names but not the identities.
A standard way to measure this risk is k-anonymity. Group the rows by their quasi-identifier values; the size of the smallest group is k. In a table with k of at least 2, every record shares its quasi-identifier values with at least k minus 1 other records. That means nobody can be narrowed down below a crowd of k. Here every group has one row, so k equals 1: no protection at all.
The usual fix is generalization, which makes values coarser until groups merge. Truncate the postcode to its first three digits and replace the birth year with its decade.
| Row | Postcode | Birth decade | Sex | Cancelled |
|---|---|---|---|---|
| 1 | 021** | 1980s | F | Yes |
| 2 | 021** | 1990s | M | No |
| 3 | 021** | 1980s | F | No |
| 4 | 021** | 1960s | M | Yes |
| 5 | 021** | 1990s | M | No |
| 6 | 021** | 1960s | M | Yes |
Count again. The group (021**, 1980s, F) holds rows 1 and 3. The group (021**, 1990s, M) holds rows 2 and 5. The group (021**, 1960s, M) holds rows 4 and 6. The smallest group has two rows, so k equals 2. Dana is now hidden among two people, and the attacker cannot tell which row is hers. Her group contains one Yes and one No, so the attacker learns nothing certain about whether she cancelled.
Now look at a different person, and the protection fails. Both rows in the 1960s group say Yes. Suppose the attacker targets a man born in 1964 who lives in 021**. They cannot tell whether he is row 4 or row 6, but they do not need to: both rows cancelled. This is called attribute disclosure, and k-anonymity alone does not prevent it. That weakness led Machanavajjhala and colleagues to propose l-diversity in 2006, as a privacy guarantee that goes beyond k-anonymity; NIST's report cites their paper.[5] l-diversity requires each group to contain at least l well-represented values of the sensitive attribute. Fixing this table might mean merging the 1960s men with another group or suppressing their rows, at the cost of detail.
That cost is the central trade-off of anonymization. Every generalization step lowers the risk of re-identification and also lowers the data's usefulness. Birth decade predicts churn less well than birth year. The skill lies in choosing the coarsest values the analysis can tolerate, and in measuring the risk rather than assuming it is gone.
Regulated sectors offer formal routes. HIPAA allows two methods for de-identifying health data. The Safe Harbor method removes a specified list of identifier types. The Expert Determination method has a qualified expert judge that the remaining re-identification risk is very small. De-identifying early also lowers the stakes of any later breach: a dataset that identifies nobody does far less harm if it leaks, and it needs fewer controls while it is stored.
Bottom line: removing direct identifiers starts anonymization; it does not finish it. Quasi-identifiers make linkage attacks possible, and k-anonymity measures the size of the crowd each record hides in. Even a k-anonymous table can leak a sensitive value when everyone in a group shares it.
Data obfuscation: masking, tokens, hashing and noise
Data obfuscation is the family of techniques that disguise data values. People and systems that do not need the real values cannot read them, but the data stays usable for its job. Some of these techniques can be reversed and some cannot. Anonymization is a goal. Obfuscation techniques are tools you use toward that goal, and also toward smaller ones, such as hiding phone numbers from support staff.
The simplest techniques remove or overwrite. Redaction deletes the sensitive content and puts nothing in its place. Masking replaces it with fixed characters. Encryption replaces it with an encrypted string, which may or may not be reversible. Google's transformation reference for its Sensitive Data Protection service shows masking at work: in its example sentence, the email address becomes a row of hash marks while the person's name stays readable, because only the email address was set up to be masked.[7] Masking covers only what you told the tool to find.
| Technique | What it does | Example | Reversible? | Joins still work? | Typical use |
|---|---|---|---|---|---|
| Redaction (suppression) | Deletes the value | Delivery notes become (dropped) | No | No | Fields the analysis does not need |
| Masking | Replaces characters with a fixed symbol | 617-555-0142 becomes ***-***-0142 | No | No | Showing staff just enough to verify a customer |
| Generalization (bucketing) | Replaces a value with a range or category | 1987-04-12 becomes 1980s; 02139 becomes 021** | No | Only on the coarse value | Quasi-identifiers in analytic data |
| Two-way tokenization (deterministic encryption) | Replaces the value with a token made with a key; the key reverses it | C-0048213 becomes 7Q2M-91XA-KD04 | Yes, with the key | Yes | Joining tables while hiding identifiers; letting an authorized system recover the original |
| Format-preserving encryption | Encrypts while keeping the length and character set | A 16-digit card number in a payment system becomes another 16-digit number | Yes, with the key | Yes | Older systems that validate field formats |
| Keyed hashing (HMAC) | Computes a one-way digest using a secret key | A phone number becomes a fixed-length base64 string | No | Yes | Linking records for statistics without ever recovering the value |
| Perturbation (noise) | Adds random noise to values or results | An age of 37 is released as 39 | No | No | Releasing aggregates; the basis of differential privacy |
| Synthetic data | Generates artificial records with similar statistics (Lesson 3) | A fake subscriber with realistic patterns | No | No | Development, testing and sharing |
The perturbation row mentions Differential privacy. It is a formal guarantee, achieved by adding carefully calibrated random noise to query results, that any released output changes very little whether or not one particular person's record is in the data. It protects aggregates, such as counts and averages, rather than individual rows.
For analytics that must join tables, the workhorse is tokenization, which is pseudonymization by another name; it is also called surrogate replacement. Tokens are either one-way or two-way. A one-way token cannot be turned back into the original value; a two-way token can. In Google's documentation, two-way tokens are made with symmetric encryption, so the same key that creates a token can also reverse it.[8] That puts the whole privacy guarantee on key management: whoever holds the key holds the identities. Keep the key in a key management service, outside the analytics environment. Let only the system that genuinely needs reversal use it, such as the call-center queue that must dial the real customer.
Deterministic tokens have a property analysts value. Google's documentation calls it referential integrity: given the same key, the same input value always becomes the same encrypted value.[8] Customer C-0048213 gets the same token in the orders table, the support table and the campaign log, so the team can still join and aggregate. The price is that repeats stay visible. Suppose one token appears in 400 orders, all shipped to the same rare postcode. The token has become a stable nickname for one household, and anyone who learns who lives there has re-identified every one of those orders.
Hashing needs its own warning. A plain hash of a phone number, such as one made with Secure Hash Algorithm 256 (SHA-256), is not anonymous. A US phone number has ten digits, so there are at most ten billion possible inputs. An attacker can hash every one of them and look up the match. That is why tokenization services use a keyed hash such as HMAC-SHA-256, where HMAC stands for hash-based message authentication code. The digest depends on a secret key as well as the input, and the result is usually encoded in base64 so it can be stored as text. Without the key, the attacker cannot build the lookup table. If the key leaks, they can.
Here is one fictional record as it sits in Fennel Box's production database, and as it arrives in the analytics environment after the pipeline the team designs:
PRODUCTION (fictional record)
customer_id C-0048213
full_name Dana Whitfield
email dana.w@example.com
birth_date 1987-04-12
postcode 02139
card_last4 1111
delivery_notes Nut allergy. Leave by the side gate.
skips_last_90d 3
ANALYTICS COPY
customer_token 7Q2M-91XA-KD04 two-way deterministic token; key held in key service
full_name (dropped) redaction
email (dropped) redaction
birth_decade 1980s generalization
postcode_area 021** generalization
card_last4 (dropped) redaction; the model does not need it
delivery_notes (dropped) redaction; data minimisation
skips_last_90d 3 kept; a needed feature
Look at what drove each choice. Fields the model does not need were dropped, not masked: the safest copy of a value is no copy at all. Quasi-identifiers that carry useful signal were generalized. The customer ID became a two-way token, because the call-center system must eventually reach the real person. Every technique used is one the team can explain to the privacy officer.
Bottom line: obfuscation techniques differ on two questions: can the value be recovered, and do joins still work? Choose a technique field by field, drop what the model does not need, and remember that deterministic tokens and unkeyed hashes can still be linked back to people.
Security around the data science workflow
Security and privacy overlap, but they are not the same. Information security protects data against unauthorized access, alteration and loss. Privacy asks whether even authorized processing is appropriate for the people the data describes. A perfectly secured warehouse can still be used for a purpose its customers never agreed to. And a privacy-respecting design is wasted if the analytics copy sits in an unprotected storage bucket.
Good security practice for a data science workflow comes down to a handful of habits:
- Least privilege. The NIST Privacy Framework expects access permissions to follow the principles of least privilege and separation of duties.[9] The analyst who builds features does not need the key that reverses tokens.
- Encryption at rest and in transit. Protect both the training snapshot on disk and the file sent to the call-center queue.
- Realistic but safe test data. Copy production data into development environments only with tokenized or synthetic fields, so developers test against realistic structures without seeing real customer records.
- No secrets or raw data in code. The most common data science leaks are notebooks with printed customer rows, credentials written into scripts, and data files committed to Git. Keep data out of repositories and keys in a secrets manager.
- Logging and deletion. Record who accessed or re-identified what, and delete snapshots on schedule.
Why should a business care, beyond the fines? The Privacy Framework traces how a privacy problem for individuals becomes a problem for the organization, through customer abandonment, noncompliance costs and harm to reputation.[9] For a subscription business, customer abandonment is churn. A leak from the churn project would cause the very thing the project exists to reduce. Atlas's Security+ course covers these controls in depth.
Translating the business need to the most appropriate solution
The VP asked for \"an AI model\". The requirements brief says what is actually needed: a weekly, explainable list of up to 1,500 subscribers worth calling. Exploratory data analysis (Lesson 6) adds a fact the email left out. A quarter of all cancellations, 1,212 of 4,812, were payment failures. No call list fixes an expired card.
Translating the business need means matching that need to the cheapest approach that meets the requirements. That approach may or may not be machine learning. Line the options up against the brief:
| Option | What it is | Meets the need? | Build effort |
|---|---|---|---|
| Process fix | Automatic card-update reminders and payment retries before an account lapses | Yes for the 1,212 involuntary cancellations; no for voluntary ones | Low |
| Business rule | Call anyone who skipped two or more of their last four deliveries | Partly: simple and explainable, but ranks poorly | Very low |
| Dashboard | Weekly churn by segment for managers | No: informs strategy but picks no one to call | Low |
| Churn propensity model | A supervised classifier (for example gradient-boosted trees, Lesson 15) scored weekly, with reason codes | Yes, if it ranks well and the offer works | Medium |
| Uplift model | Predicts how much a call changes each subscriber's chance of staying | Best fit in principle, but needs data from randomized campaigns that does not exist yet | High |
| Real-time scoring API | Scores subscribers the moment they open the cancel page | Overbuilt: the brief says weekly is enough | High |
The table teaches three things. First, part of the problem is not a prediction problem at all, and the cheapest fix should come first. Second, the uplift row exposes a subtle mismatch. A churn model predicts who will leave, but the business needs to know whose decision a call can change. A subscriber who is moving abroad has a high churn score and will not respond at all to a $15 credit. Ranking by churn risk is a reasonable first step only if the offer's effect is measured. Third, sophistication beyond the requirements is cost without benefit: the real-time option answers a question nobody asked.
Bottom line: start from the decision and the constraints, not from the technique named in the request. Fix non-predictive causes with process changes, prefer the simplest option that meets the requirements, and check that the thing being predicted is what the decision depends on.
Cost-benefit analysis, worked twice
A recommendation needs a number behind it. A Cost-benefit analysis compares an option's expected benefits with its costs, in the same units and over the same period. It compares them against the best alternative, which is sometimes doing nothing. For a call campaign, the core arithmetic works per contact. Define four quantities:
- p: the precision of the call list, meaning the share of called subscribers who would otherwise cancel (Lesson 2's precision, measured at the top of the ranked list);
- s: the save rate, the share of would-be cancellers that a call actually keeps, measured against a held-back control group;
- V: the margin a saved subscriber brings, here $180 (six more months at $30 a month);
- c: the cost of one call, here $15.50 (the $15 credit plus $0.50 of agent time).
expected value per call = p x s x V - c
break-even precision p* = c / (s x V)
The first line says a call earns money only when three things happen together. It reaches someone who would have left (probability p). It keeps that person (probability s). And the margin saved (V) outweighs what every call costs (c). The second line comes from setting the first line to zero and solving for p.
Run 1: the skip rule. The team tests the \"two skips in four weeks\" rule on last quarter's data. Among the 1,500 subscribers it would have flagged each month, 30% went on to cancel, so p = 0.30. For now, assume s = 0.20.
value per call = 0.30 x 0.20 x 180 - 15.50
= 10.80 - 15.50
= -4.70 dollars
monthly result = -4.70 x 1,500 calls = -7,050 dollars
The rule loses money. It is cheap to build, but it calls too many people who were going to stay anyway.
Run 2: change one input. A gradient-boosted model is validated on a held-out time period. Of the 1,500 subscribers it ranks highest, 65% are true cancellers, so p = 0.65. Everything else stays the same.
value per call = 0.65 x 0.20 x 180 - 15.50
= 23.40 - 15.50
= 7.90 dollars
monthly result = 7.90 x 1,500 calls = 11,850 dollars
The result flips from a loss to a gain. The break-even precision shows why:
p* = 15.50 / (0.20 x 180) = 15.50 / 36 = 0.43
Any call list with precision above about 43% pays for its calls. The rule sits below that line and the model sits above it. This also shows which of Lesson 2's metrics matters here. With a fixed capacity of 1,500 calls, overall accuracy and even ROC-AUC come second. The money depends on precision among the top 1,500.
A full analysis adds the costs that do not grow with each call. Suppose building and validating the model takes $40,000 of staff time, and running, monitoring and retraining it costs $1,500 a month.
monthly net after running cost = 11,850 - 1,500 = 10,350 dollars
payback period = 40,000 / 10,350 = about 3.9 months
Now test the weakest assumption. Nobody at Fennel Box has measured s; the 0.20 came from a vendor's case study. What happens if the true save rate is 0.12?
| Scenario | p | s | Value per call (p x s x V) | Net per call | Net per month, 1,500 calls |
|---|---|---|---|---|---|
| Skip rule | 0.30 | 0.20 | $10.80 | -$4.70 | -$7,050 |
| Model | 0.65 | 0.20 | $23.40 | $7.90 | $11,850 |
| Model, weaker offer | 0.65 | 0.12 | $14.04 | -$1.46 | -$2,190 |
With s = 0.12, even the good model loses money. Solve for the break-even save rate at p = 0.65: s* = 15.50 / (0.65 x 180) = 15.50 / 117, which is about 0.13. The whole recommendation therefore depends on whether a call keeps more than about 13% of would-be cancellers. Only a randomized holdout (Lesson 10) can measure that. The cost-benefit analysis has done its most useful job: it has found the assumption to test before anyone spends $40,000.
Not every cost is in dollars. Calls annoy some customers. A privacy incident has costs a spreadsheet cannot price. Agents' time has other uses. The NIST Privacy Framework describes privacy risk assessment as producing the information an organization needs to weigh the benefits of data processing against its risks, a judgment it calls proportionality.[9] Data science supplies the numbers. The recommendation must say which costs those numbers include and which they leave out.
Relevant range of application
Every number in that analysis holds only within limits. The relevant range of application is the span of conditions (volume, population, input values and time period) over which a model's outputs, or a cost-benefit analysis's assumptions, stay valid. The phrase has two working meanings that the exam objective groups together, and a senior data scientist checks both.
The cost range. In managerial accounting, the relevant range is the band of activity over which cost behavior holds: fixed costs stay fixed, and variable costs stay constant per unit. The $15.50 per call holds while two agents can handle the calls. At 3,000 calls a month, Fennel Box needs a third agent, which is a step jump in cost. Precision changes too. Calls 1,501 to 3,000 come from further down the ranked list, where p is lower than 0.65. So you cannot multiply \"the model earns $7.90 per call\" by any volume you like. That figure holds for roughly the top 1,500.
The model range. A model can be trusted for the population and input values its training data represents. Fennel Box's first model was trained on US subscribers from 2024 to 2026 with tenures of 1 to 36 months. Three requests in the next quarter fall outside that range:
- Scoring UK subscribers, the planned extension. They have only eight months of history and different delivery patterns, none of their records were in the training data, and using them also triggers the UK GDPR review.
- Scoring a 60-month subscriber, an input value beyond anything in the training data. Tree models (Lesson 15) predict a flat value beyond their last split, and linear models extend a slope that may not hold.
- Scoring office-lunch customers, who use a different product that the requirements brief listed as a non-goal.
None of these uses is forbidden, but each needs its own validation first. The range also shifts over time. A price rise or a new competitor can move today's subscribers outside the conditions the model learned from; this is the drift problem from Lesson 13. State the range explicitly, in the recommendation and in the model's documentation, so that whoever reuses the model later knows where it stops.
The recommendation memo
All of this ends in a short document a busy executive can act on. Here is the team's memo, in fictional form:
TO: VP of Retention FROM: Data Science RE: Churn request
1. Fix payment-failure churn first. 1,212 of 4,812 cancellations last
month were lapsed cards. Card-update reminders need no model.
2. Pilot the churn model on US subscribers for 8 weeks before full
rollout. Each week, randomly hold back 20% of the top-ranked list
as a control. Go/no-go: proceed if the measured save rate exceeds
13% (break-even at 65% precision, $15.50 per call, $180 margin).
3. Expected value if the save rate is 20%: about $11,850 a month before
$1,500 running cost; the $40,000 build pays back in about 4 months.
4. Privacy: delivery notes excluded (data minimisation). Customer IDs
tokenized; reversal key held by the call-center system only. The
planned UK extension brings in the UK GDPR: privacy officer to
confirm the new purpose before any UK records are used.
5. Scope (relevant range): US subscribers, tenure 1-36 months, up to
about 1,500 calls a month. UK subscribers need their own validation;
the office-lunch product is out of scope.
Every part of objective 4.1 appears in those five points. The memo states requirements, a cost-benefit case with its key assumption exposed, the most appropriate solution (including the fix that needs no model), the privacy and compliance controls, and the relevant range. The VP asked for a model; the memo gives a decision, a test and a limit.
Reading the exam's cues
| The stem says | Points to | Often confused with |
|---|---|---|
| Names and IDs removed, but postcode, birth date and sex remain | Still PII: quasi-identifiers allow linkage | Anonymized data |
| Supplier pricing, source code, trained model weights, licensed dataset | Proprietary data | PII |
| Join tables on customer ID without analysts seeing the real ID | Deterministic tokenization (pseudonymization) | Masking, which breaks joins |
| An authorized system must recover the original value | Two-way token or encryption with a managed key | One-way hash |
| Show only the last four digits; replace characters with # | Masking | Encryption |
| Irreversible; nobody can re-identify individuals | Anonymization (suppression, generalization, aggregation) | Pseudonymization |
| Age 37 becomes 35-39; postcode truncated | Generalization (bucketing) | Perturbation (noise) |
| Collected for delivery, now wanted for marketing | Purpose limitation | Data minimisation |
| A field not needed for the stated purpose | Data minimisation | Storage limitation |
| A raw count, versus a rate tied to a goal with owner and target | Measure, versus KPI | Metric (the general category) |
| Stakeholder asks for AI; the cause is a broken process | Translate the need: a process fix | Build the model anyway |
| Benefits minus costs, break-even, payback period | Cost-benefit analysis | Model accuracy |
| Applying a model to a new region, product or input values beyond the training data | Outside the relevant range of application | Data drift (a related change over time) |
Common misconceptions
- \"Removing names and email addresses makes a dataset anonymous.\" Quasi-identifiers such as postcode, birth date and sex can be linked to outside data. Measure k, and check whether any group shares a sensitive value, before calling data anonymous.
- \"Tokenized data is anonymous data.\" Tokenization is pseudonymization. The key, or patterns in the tokens, can lead back to people, so under the GDPR the result is still personal data.
- \"Hashing an identifier anonymizes it.\" An unkeyed hash of a value from a small set, such as phone numbers, can be reversed by hashing every possible input. Even a keyed hash produces a stable pseudonym, not anonymity.
- \"A strong model metric means the project succeeded.\" AUC is not a KPI. A well-ranked list can still lose money if precision at capacity falls below break-even or the offer changes nothing; measure the business result against a control.
- \"If data contains no personal information, the team can use it freely.\" Proprietary and licensed data carry contractual and intellectual-property limits that can be stricter than privacy law.
- \"A secure system is automatically privacy-compliant.\" Security controls who can reach data. Privacy also governs the purpose and the amount of processing, even for authorized users.
Pulling it together
- Requirements gathering pins down the decision, the actor, capacity, timing, error costs, the success measure, constraints and non-goals. Non-functional requirements such as \"weekly is enough\" often decide the architecture.
- A measure is a raw count, a metric puts measures in comparable form, and a KPI is a metric tied to a strategic goal with an owner and a target. NIST treats KPIs and KRIs as kinds of metrics, and not every metric is one of them.
- PII is information that can distinguish or trace a person's identity alone or in combination, and it reaches information linked or linkable to a person, so quasi-identifiers and linked behavior records count.
- Proprietary data is protected by ownership, contracts and intellectual-property law rather than privacy law, and one dataset can be both proprietary and personal.
- Pseudonymization (tokenization) keeps records linkable and often reversible with a key, so it remains personal data under the GDPR. Anonymization aims to make re-identification impossible by any reasonable means.
- k is the size of the smallest group of records sharing the same quasi-identifier values. A k-anonymous group in which every record has the same sensitive value still discloses that value, which is the weakness l-diversity addresses.
- Redaction removes, masking replaces with fixed characters, generalization coarsens, two-way tokens can be reversed with a key, and keyed hashes cannot be reversed. Deterministic tokens keep joins working, but repeated patterns raise re-identification risk.
- The UK GDPR sets out seven principles, including purpose limitation and data minimisation, with top-tier fines of up to £17.5 million or 4% of worldwide annual turnover. HIPAA and FERPA requirements do not apply to properly de-identified data.
- Break-even precision for a contact campaign is c / (s x V). Cost and model figures hold only within their relevant range of volume, population, input values and time.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- NIST. (2024). Measurement Guide for Information Security: Volume 1, Identifying and Selecting Measures (SP 800-55 Vol. 1). nvlpubs.nist.gov
- NIST. (2008). Performance Measurement Guide for Information Security (SP 800-55 Rev. 1). csrc.nist.gov
- NIST CSRC. (n.d.). Personally Identifiable Information (PII), CSRC Glossary. csrc.nist.gov
- Simson L. Garfinkel. (2015). De-Identification of Personal Information (NISTIR 8053). NIST. nvlpubs.nist.gov
- Information Commissioner's Office (UK). (n.d.). A guide to the data protection principles. ico.org.uk
- Google Cloud. (n.d.). Transformation reference (Sensitive Data Protection). docs.cloud.google.com
- Google Cloud. (n.d.). Pseudonymization (Sensitive Data Protection). docs.cloud.google.com
- NIST. (2020). NIST Privacy Framework: A Tool for Improving Privacy through Enterprise Risk Management, Version 1.0. nvlpubs.nist.gov
- Key terms
- Personally identifiable information (PII)
- Information that can distinguish or trace a person's identity, either on its own or when combined with other information that is linked or linkable to that person.
- Quasi-identifier
- A field such as birth date, postcode or sex that does not identify a person alone but can do so in combination with other fields or outside datasets.
- Proprietary data
- Information an organization owns or licenses and keeps confidential for business reasons, such as prices, source code or model weights, protected by contracts and intellectual-property law rather than privacy law.
- Anonymization
- De-identification carried far enough that nobody can reasonably re-identify individuals; it is intended to be irreversible, and truly anonymous data is no longer personal data under the GDPR.
- Pseudonymization
- Replacing identifiers with tokens or pseudonyms while keeping the ability to link records, and often to reverse the replacement with a key; the result is still personal data.
- Data masking
- An obfuscation technique that replaces some or all characters of a value with a fixed symbol, such as showing only the last four digits of a phone or card number.
- k-anonymity
- A property of a dataset in which every record shares its combination of quasi-identifier values with at least k minus 1 other records.
- Key performance indicator (KPI)
- One of a small set of metrics tied directly to a strategic goal, with a defined calculation, a named owner, a target and a regular reporting schedule.
- Break-even precision
- In a contact campaign, the minimum share of contacted people who would otherwise leave needed for benefits to equal costs: cost per contact divided by the product of save rate and value per save.
- Relevant range of application
- The span of volumes, populations, input values and time periods over which a model's outputs or an analysis's cost assumptions remain valid.
Obtaining Data: Types, Sources and Purposes
- Explain how survey, administrative, sensor, transactional and experimental data are produced, and trace each source's data-generating process to the questions it can and cannot answer.
- Describe how synthetic data are created and sampled, and judge when their benefits outweigh their limitations for a given purpose.
- Evaluate commercial and public datasets for cost, availability, licensing and restrictions before they enter a pipeline.
- Apply a five-step sourcing procedure to choose data for a modeling question, and rerun it when the purpose changes.
Four Census questions answered without asking anyone
The U.S. Census Bureau once tested a shortcut on the American Community Survey (ACS), the large household survey it runs every year. For four housing questions, it tried filling in the values from administrative records instead of asking the household. Administrative records are files that agencies and companies already keep for running programs. The records could replace survey responses for between 37.5 and 53.5 percent of responding housing units.[1] That is a real cut in the burden on the public. Yet many of the estimates simulated from the records were significantly different from the published survey estimates.[1]
That study shows the core trade-off of reusing data that already exists. It is cheap and fast, but someone made it for their own purpose, and its gaps follow that purpose. The other routes to data carry trade-offs of their own. Data you collect yourself, through a survey or an experiment, fits your question, but you pay for every row. Data you buy or download arrives with someone else's rules attached. Data you synthesize is only as good as the model that produced it. The exam expects you to reason from the question to the source.
Exam objectives: 4.2 Explain the process of and purpose for obtaining different types of data.[2] The objective lists three families. Generated data covers survey, administrative, sensor, transactional and experimental data, plus the data-generating process behind them. Synthetic data covers costs and benefits, creation process, limitations, sampling and rationale. Commercial/public data covers costs and benefits, availability, licensing and restrictions.
The data-generating process: how did this row come to exist?
Before you judge any dataset, ask one question: what chain of events put each row into this table? That chain is the data-generating process (DGP). It has three parts, and each one can break an analysis on its own. Behind all three sits a fourth question, about the purpose of the collection.
- The mechanism. This is the real-world process you care about: how customers decide to buy, how pipes corrode, how a disease progresses. In model terms, Y = f(X) + ε, where f is the systematic relationship between inputs X and outcome Y, and ε is the variation f does not explain.
- The measurement. What gets stored is a measured version, Y* = m(Y) + δ. The function m stands for the instrument, form or system field that records the value, and δ is measurement error. A thermometer reading, a self-reported income and a billing code are all measured versions of something underneath.
- The selection. A case enters your table only when some selection indicator S equals 1. Someone answered the survey, a customer made a purchase, a sensor was installed and working, a loan was approved.
Put the three together. A model trained on stored data learns about P(X, Y* | S = 1): the joint distribution of measured values among selected cases. What you usually want is P(X, Y): the relationship in the whole population, measured truly. The two match only when measurement error is small and selection does not depend on the outcome or on things related to it. The missing-not-at-random (MNAR) pattern from Lesson 7 is one version of this failure: whether a value is missing depends on the value itself.
Here is a worked case. A bank wants a default model and pulls five years of loan records. Every row has an outcome, repaid or defaulted. But a loan reached the table only if the old credit policy approved it. Rejected applicants have no outcome at all, because they never received a loan. So S depends on X (the old policy looked at income and credit history), and the riskiest part of the applicant population is almost absent. A model trained on these rows can score well on a held-out slice of approved loans and still misjudge new applicants that the old policy would have rejected. Nothing in the rows reveals this. Only the DGP does.
| Part or question | What to ask | What goes wrong if you skip it |
|---|---|---|
| Mechanism | Does the data contain variation in the thing I want to learn about? | Prices never changed during the history, so no model can learn price sensitivity from it |
| Measurement | What instrument, form or system field produced the value, and how large is its error? | A billing system writes an estimated reading when a meter fails, and the model treats estimates as measurements |
| Selection | Who or what could not have appeared in this table? | Approved loans only, survey nonrespondents missing, customers who left before logging started |
| Purpose (the extra question) | Why was this collected, and by whom? | A code defined for paying insurance claims is reused as if it were a clinical diagnosis |
Key idea: the data-generating process, not the size of the table, decides which questions a dataset can answer. Trace the mechanism, the measurement and the selection, and ask why the data were collected, before you trust a pattern.
Generated data: five sources side by side
In the objectives, generated data means data produced by a real process involving people, organizations or devices. Synthetic data, by contrast, are produced by a model. The five generated types differ mainly in who controls the process and why it was run. Read the table by column: the "why" column predicts the weakness column almost every time.
| Type | Who produces it, and why | Main strength | Typical weakness | Cost to the analyst |
|---|---|---|---|---|
| Survey | A researcher asks a sample of people questions, for a statistical purpose | Measures attitudes, intentions and facts no system records | Nonresponse, self-report error, question wording, small n | High per row: design, fielding, follow-up |
| Administrative | A government or organization, to run a program or deliver a service | Broad coverage, already paid for | Definitions fit the program, not your question; access rules | Low collection cost; real cost in access, linkage and cleaning |
| Sensor | A device measuring a physical quantity on a schedule | High frequency, objective, continuous | Drift, gaps, clock errors, saturation; no intent or context | Hardware up front, then storage and processing |
| Transactional | A business system recording events such as sales or clicks | Exact amounts and timestamps for every event it handles | Covers only people who transacted; shaped by prices, rules and system changes | Low, already captured; needs schema knowledge |
| Experimental | The analyst, who assigns treatments on purpose | Supports causal claims through randomization | Slow, costly, limited to the factors and ranges tested | Highest per question: design, run time, exposure |
Survey data: designed for statistics, limited by who answers
Survey data are collected by asking people questions, usually a sample rather than everyone. Surveys and experiments are the two generated types designed from the start around a question. Administrative, sensor and transactional data are by-products of running a program, a device or a business. Of the two designed types, surveys are the one that can measure what no system records: satisfaction, intended purchases, household composition, why someone stopped using a product.
The process runs in a fixed order. You define the target population. You build a sampling frame, the actual list you draw from, such as an address file or a customer list. Anyone missing from the frame can never be sampled. Then you choose a sample design.
- A simple random sample gives every unit on the frame the same chance of selection. The standard-error formula below assumes this design.
- Stratified sampling splits the frame into groups called strata, such as regions or customer tiers, and draws a separate random sample from each. It guarantees that every stratum is represented, and it usually lowers the standard error when the strata differ from one another. Small strata can be oversampled on purpose and weighted back down later.
- Cluster sampling first draws whole groups, such as neighborhoods or stores, and then surveys units inside them. It cuts travel and listing costs. But people in the same cluster tend to resemble each other, so the standard error is larger than a simple random sample of the same size would give.
After choosing the design, you write and pretest questions, field the survey, follow up with nonrespondents, and finally weight the responses so the sample matches known population totals.
Sampling error has a formula. For an estimated proportion p from a simple random sample of n people, the standard error is SE = √(p(1 - p)/n). Work it through for p = 0.30 and n = 400. First, p(1 - p) = 0.30 × 0.70 = 0.21. Next, 0.21/400 = 0.000525. The square root is about 0.0229. A 95 percent margin of error is about 1.96 × 0.0229 ≈ 0.045, or 4.5 percentage points. Quadruple the sample to 1,600 and the standard error halves, to about 0.0115, so the margin falls to about 2.2 points. Because n sits under a square root, halving the error costs four times the interviews.
Now change one input. Suppose only 20 percent of the people you contacted responded, and responders differ from nonresponders. More interviews shrink the sampling error, but they do nothing to the bias, because you are drawing more people from the same skewed group. That is why serious survey budgets go into follow-up and weighting, not only into larger n. Self-report adds its own errors on top: people round incomes, forget dates and give socially approved replies.
Administrative data: someone else's records, reused
Administrative data are records kept to run programs and deliver services, not to produce statistics. The Census Bureau describes such files as maintained by governments and commercial entities for the purpose of administering programs and providing services, and treats them as distinct from information collected only for statistical purposes.[1] Tax filings, benefit claims, school enrollment, vehicle registrations, hospital billing and property records are all examples.
The benefit is cost. The program has already paid for the collection, so reusing the records is cheap compared with fielding a new survey. Coverage can also be close to complete for the program's population: everyone who files taxes appears in tax records. In a 2011 review, the U.S. Government Accountability Office (GAO) concluded that administrative data have greater potential to supplement rather than replace survey data.[3] The ACS test at the top of this lesson found the same thing in practice.
The weaknesses trace back to purpose. Different agencies may use different systems, definitions and time frames when they collect administrative data.[3] Combining records across states or years therefore takes real work. Because each field was defined for the program, the field you need may be missing or loosely defined. Linking records to individuals also raises consent. When survey respondents are asked for permission to link their answers to records, some refuse, which can substantially cut the number of people eligible for linkage and so affect the quality of the linked data.[3]
The Census Bureau's guiding principles for judging a record source make a good checklist for any reuse. They begin with authorization and availability: is there a formal agreement to use the source, and are the data available for every year? A further principle asks whether the administrative data correspond to the concept the survey intends to measure.[1] Alignment in time matters too. A tax year that does not match the survey's reference period looks like a small mismatch, but it can become a large error in a model.
Sensor data: the instrument is part of the process
Sensor data come from devices that measure a physical quantity: smart meters, accelerometers, temperature probes, GPS units, cameras and machine telemetry. Collection is automatic and usually frequent, so volume is high, and once the hardware is in place each extra reading costs almost nothing. Sensors record what happened, not why. A flow meter reports water running at 3 a.m.; it cannot tell a leak from a filling pool.
The instrument sits squarely inside the DGP. Its sampling rate sets the fastest event you can see. Its resolution sets the smallest change you can detect. Calibration drifts, batteries fade, clocks on different devices disagree, and readings saturate at the top of the range. Below is a fictional extract from an hourly water-meter feed, the kind of file the worked procedure later in this lesson uses.
meter_id,timestamp_utc,liters_cumulative,battery_v,status
M-10442,2026-03-02T01:00:00Z,184220,3.61,OK
M-10442,2026-03-02T02:00:00Z,184231,3.61,OK
M-10442,2026-03-02T03:00:00Z,184242,3.60,OK
M-10442,2026-03-02T04:00:00Z,,3.60,NO_READ
M-10442,2026-03-02T05:00:00Z,184264,3.60,OK
M-10442,2026-03-02T06:00:00Z,000118,3.70,OKRead it the way the meter writes it. The value is cumulative, so hourly use is the difference between consecutive rows: 11 liters per hour from 1 a.m. to 3 a.m. Steady flow through the night is a leak signal, because households rarely use water evenly at that hour. The 4 a.m. row is a gap. The 5 a.m. value of 184264 shows 22 liters over two hours, so the gap loses no total volume, only the hourly split. At 6 a.m. the total drops to 118 and the battery voltage jumps: the meter was replaced. A naive difference would record minus 184,146 liters. Every one of these is a DGP fact, and none of them is visible to a model that sees only a column of numbers.
Transactional data: complete for events, silent about non-events
Transactional data record business events as they happen: a sale at a till, a payment, a click, an insurance claim, a shipment. They are a by-product of running the business, so they cost little to obtain and are exact about amounts and times.
Their selection is built in, because a transaction exists only when someone transacts. A retailer's loyalty-card data describe what members bought in its stores. They say nothing about what those members bought elsewhere, or about people who never joined. The system also shapes the record. A promotion shifts purchases between weeks. A website redesign changes what gets clicked. A new point-of-sale system can change the meaning of a field overnight. When you use transactional data to study behavior, ask three questions: what did the system make easy, what did it make impossible, and what changed in the system during your window?
Experimental data: the analyst controls assignment
Experimental data come from a study in which you decide who or what receives each treatment. That control is the whole point. If you randomize assignment, the treated and untreated groups differ only by chance in everything else, so a difference in outcomes larger than chance can be attributed to the treatment. Survey, administrative, sensor and transactional data are all observational: they record what happened without your intervention, so they cannot give that guarantee without strong extra assumptions.
The NIST/SEMATECH e-Handbook of Statistical Methods, an engineering statistics reference from the National Institute of Standards and Technology (NIST), has a section on choosing an experimental design. Its contents list the topics in this order: set objectives, select process variables and levels, then select the experimental design.[4] Three basic designs are worth knowing by name.
- A completely randomized design assigns units to treatments purely at random.
- A randomized block design first groups similar units, for example stores of similar size, and randomizes within each group. That removes the grouping variable as a source of noise in the comparison.
- A full factorial design tests every combination of the levels of several factors, so it can estimate interactions between them.
The costs are real. Experiments take time to run, expose some units to a possibly worse treatment, and only tell you about the factors and ranges you actually varied. A pricing test between 9 and 11 dollars says little about a price of 20. Lesson 10 covers analyzing such tests. The point here is when to obtain them: whenever the question asks what causes an outcome, or a decision depends on what would happen if you changed something.
Key idea: survey, administrative, sensor and transactional data record the world as it happened; only experimental data let you change one thing on purpose, which is why causal questions push you toward experiments despite their cost.
Synthetic data: the creation process and three families of generator
Synthetic data are artificially generated records designed to resemble real data in their statistical properties. No row is a real person, purchase or machine. For generators built from real data, NIST describes the creation process in two steps: build a probabilistic model of the underlying population from which the original data were sampled, then use that model to generate new rows.[5] If the fitted model represents the population well, the new rows keep the population's properties while each one describes someone who does not exist.
Not every generator fits its model to real data, though. Emiliano De Cristofaro of the University of California, Riverside, writing in 2023, sorts generators into three families, following a classification by Derek Snow of the Alan Turing Institute. Every family ends by sampling from some model. What differs is where the model comes from.
| Family | Where the model comes from | Good for | Watch out for |
|---|---|---|---|
| Hand-engineered | An expert specifies distributions and rules, informed by real data | Test data, edge cases, scarce real data | Only as realistic as the expert's beliefs |
| Agent-based | Prescribed rules for how simulated agents interact | Systems driven by interaction: traffic, epidemics, markets | Wrong rules give wrong data; calibration is hard |
| Generative model | An algorithm fits the data distribution from real records | Realistic copies of complex real data | Needs real data to train; can memorize real rows |
In De Cristofaro's account, hand-engineered methods identify an underlying distribution from real data using expert opinion and seek to imitate it.[6] Agent-based models set up known agents and let them interact according to prescribed rules, in the hope that the result looks like the original data.[6] Here the rules, not a distribution fitted to records, drive the output. Generative models learn how a dataset is generated using a probabilistic model, then create synthetic data by sampling from the learned distribution.[6] A well-known generative architecture is the Generative adversarial network (GAN), which sets two neural networks against each other: a generator produces realistic-looking examples while a discriminator tries to tell real from fake.[6] In the idealized description, training ends when the discriminator can no longer tell them apart.
Worked example: why sampling columns separately breaks a model
The simplest data-driven generator uses marginal distributions. A one-way marginal is the distribution of a single column on its own. NIST illustrates it with coffee-shop sales: to generate a fake purchase, pick a drink at random, weighted by the observed shares. In its example, 60.8% of the generated purchases should be pumpkin spice lattes, 24.1% lattes and 15.0% regular coffees.[5] NIST also names the catch: the major challenge of this approach is preserving correlations between data attributes.[5]
Work through why with fictional numbers. A café has 1,000 real purchases, split evenly by age group.
| Age group | Pumpkin spice latte | Latte | Coffee | Total |
|---|---|---|---|---|
| Under 30 | 400 | 70 | 30 | 500 |
| 30 and over | 200 | 170 | 130 | 500 |
| Total | 600 | 240 | 160 | 1,000 |
In the real data, P(pumpkin spice | under 30) = 400/500 = 0.80, and P(pumpkin spice | 30 and over) = 200/500 = 0.40. Age matters a great deal.
Now generate each column from its own one-way marginal: age is 50/50, drink is 60/24/16, and the two are drawn independently. Under independence, P(pumpkin spice | under 30) = P(pumpkin spice) = 0.60, and the same holds for 30 and over. The synthetic table will show about 300 pumpkin spice lattes in each age group. Every one-column summary matches the original, so a quick comparison of histograms looks perfect. But a classifier trained on the synthetic rows will learn that age carries no information, which is false. The chi-squared test of independence from Lesson 1 would find a strong association in the real table and essentially none in the synthetic one.
The fix is to sample from the two-way marginal, which is the joint table itself. That preserves this pair of columns. The trouble is scale. With k columns of c categories each, the full joint table has ck cells. Twenty columns of 10 categories give 1020 cells, vastly more than any dataset has rows, so most cells would be empty or estimated from one or two records. Practical generators therefore choose which marginals to keep, chain conditional distributions (a Bayesian network does this), or learn the joint distribution with a neural network.
Sampling rows from a fitted generator
Once a generator is fitted, sampling is the step that produces rows. The fictional pseudocode below draws from the joint table above, with each cell's probability equal to its count divided by 1,000.
# Fictional pseudocode: weighted sampling from a fitted joint distribution
joint = {
("under30", "psl"): 0.40, ("under30", "latte"): 0.07, ("under30", "coffee"): 0.03,
("30plus", "psl"): 0.20, ("30plus", "latte"): 0.17, ("30plus", "coffee"): 0.13
}
rng = random_generator(seed = 2026) # a fixed seed makes the sample reproducible
synthetic = []
repeat n_synthetic times:
cell = rng.weighted_choice(keys(joint), weights = values(joint))
synthetic.append(cell)Four decisions live in or around that loop, and each can appear in an exam scenario.
- How many rows. You can set n_synthetic to a million, but that creates no information. The generator was fitted to 1,000 real rows, so its probabilities carry the uncertainty of 1,000 rows plus the model's own error. A confidence interval computed on a million synthetic rows will be far too narrow. Report uncertainty based on the real sample, or use inference methods designed for synthetic data.
- Stratified or conditional draws. You do not have to sample from the whole distribution in proportion. You can fix how many rows to draw for each stratum, exactly as a stratified survey does, so that a small group such as a rare region gets enough rows for testing. Or you can sample from a conditional distribution, for example P(features | class = fraud), to generate extra cases of a rare class. SMOTE (Synthetic Minority Oversampling Technique) from Lesson 8 serves the same goal differently: it creates new minority-class rows by interpolating between real neighbors rather than sampling a fitted model. Either way, every new rare-class row is still a variation on the few real ones.
- Resampling is not synthesis. A bootstrap draws real rows with replacement. It is useful for estimating uncertainty, but every row it returns is a real record, so it offers no privacy and no new combinations.
- Which constraints to enforce. Generators can produce impossible combinations, such as a refund larger than its purchase or a discharge date before an admission date. Check sampled rows against business rules, and expect rare combinations in the tails to be underrepresented.
Synthetic data: rationale, costs, benefits and limitations
Why bother? The usual rationale is that real data cannot go where they are needed. Companies are often unable to legally use production data for testing purposes,[6] so synthetic copies let developers build and test pipelines without touching real customers. Synthetic data can also fill gaps: rare events, scenarios that have not happened yet, or a balanced training set. Rough fidelity is enough when the job is testing code or sketching trends; it is not enough when the job is learning relationships.
Privacy is the most cited rationale, and the most oversold. Deleting names does not make a dataset anonymous, and a generative model that overfits can memorize and reproduce real rows. The strong version is Differential privacy, a mathematical guarantee that limits how much any one person's record can change the output. When synthetic data are differentially private, NIST explains, they may be analyzed, shared and combined with other datasets with no additional risk to privacy.[5] That guarantee holds only if the software implements it correctly. NIST warns that buggy differentially private programs do not crash; instead they silently violate privacy in ways that can be hard to detect.[5] More broadly, De Cristofaro thinks it unlikely that synthetic data will be a silver bullet for sanitizing sensitive data or safely sharing confidential information across the board, and expects them to help in specific use cases instead.[6]
Accuracy is the other trade. Privacy protection works by adding noise or limiting detail, so a differentially private generator gives up some fidelity, and the stronger the guarantee, the more it gives up.
| Benefit | Matching cost or limitation |
|---|---|
| Shareable with vendors and testers without exposing real records | Privacy is only as strong as the method and its implementation; without differential privacy, memorized rows can leak |
| Unlimited rows on demand | No more information than the real data used to fit the generator |
| Can create rare or future scenarios | Patterns absent from the source data, or from the expert's rules, cannot appear |
| Cheap once the generator exists | Building and validating a good generator takes skilled time |
| Can rebalance classes | Inherits, and can amplify, the source data's biases |
The practical test of fidelity is called train on synthetic, test on real. Fit your model on the synthetic rows, score it on a held-out set of real rows, and compare with a model trained on real rows. A large gap means the generator lost structure the model needs.
Key idea: synthetic data copy the structure the generator captured and nothing more; judge them by whether that structure is enough for the job, not by whether the column summaries match.
Public data: availability, costs and open licenses
Open data are published for anyone to access and reuse. Typical sources are national statistical agencies, city and county open-data portals, research data repositories and international bodies. In the United States, the OPEN Government Data Act of 2018 requires federal agencies to make their data publicly available in open, machine-readable formats and to apply open licenses.[7] Data and content that U.S. government employees create within the scope of their employment are not subject to domestic copyright protection, so they default to the U.S. public domain.[7] Note the word domestic: that status does not settle the question in other countries, and state, city and foreign governments set their own terms.
The benefits of public data are easy to see. It costs nothing to download, it often comes in machine-readable formats with metadata, and many other users have already worked with it and reported its quirks. The costs are less visible, and most of them are the costs of not controlling the collection.
- Definitions and coverage. The publisher chose the concepts, categories and population, and the documentation may be thin. Much public data is administrative data published openly, so everything in the administrative section applies.
- Revisions. Published series are revised as late reports arrive or methods change, so a figure downloaded in March may differ from the same figure downloaded in June. Record the download date and the version.
- Update schedule. Release frequency ranges from near real-time feeds to annual tables. The slowest source sets the freshest data your model can use when it scores.
- Availability over time. Portals reorganize, files change format, and series stop. A dataset that is free today is not guaranteed next year.
For federal open-data policy, an open license is any legally binding instrument that grants permission to access, re-use and redistribute a work with few or no restrictions.[7] Federal dataset metadata includes a license field that records the license or non-license (public domain) status under which the dataset was published, so that field is the first place to look.[7] Open does not mean free of conditions, though. The common licenses differ in what they ask of you.
| License | Attribution required? | Share-alike? | What it means for your derived dataset |
|---|---|---|---|
| Creative Commons Zero (CC0) or Open Data Commons Public Domain Dedication and Licence (PDDL) | No | No | Use freely; crediting the source is still good practice |
| Creative Commons Attribution (CC BY) or Open Data Commons Attribution License (ODC-By) | Yes | No | Credit the source; you may license your own work as you choose |
| Creative Commons Attribution-ShareAlike (CC BY-SA) | Yes | Yes | Adaptations you share must carry the same license |
| Open Data Commons Open Database License (ODbL) | Yes | Yes, for derived databases used publicly | A derived database you make public must be offered under ODbL; produced works such as charts need attribution |
The share-alike clause is the one that bites in practice. Joining a share-alike dataset into a table that you then publish can oblige you to release that table under the same terms. Check before the join, not after the launch.
Commercial data: costs, benefits, availability and restrictions
Commercial data are bought or licensed from a vendor: credit bureau files, consumer demographics, foot-traffic panels, market prices, satellite imagery. The benefits are speed and coverage. Someone else has already collected, cleaned and joined the data, often at a scale no single company could reach. The costs go beyond the invoice: integration work, refresh fees, staff time to learn the vendor's definitions, and the risk of building a model on a source you do not control.
The Census Bureau's own experience with vendor data spells out that risk. It noted risks such as another vendor winning the contract later, or the current vendor going out of business.[1] It also stressed checking whether the chosen vendor really offers the most comprehensive data. Availability is a time-series question as much as a yes-or-no one: if a feature disappears next year, the model that depends on it breaks.
Restrictions come from three directions, and you have to clear all three.
- Contract. A license may limit use to internal analysis, forbid redistribution of raw or derived rows, forbid training machine learning models, cap the number of users, or require deletion when the contract ends. A production model trained under a license that later lapses is a governance problem.
- Law. Personally identifiable information (PII) brings privacy and data-protection law with it, such as the Health Insurance Portability and Accountability Act (HIPAA) in the U.S., the General Data Protection Regulation (GDPR) in the EU and the California Consumer Privacy Act (CCPA). Statutes can also restrict how government agencies share records with each other or with you.
- Technical terms. An application programming interface (API) usually comes with rate limits and terms of service, and a page being publicly visible does not license you to scrape or reuse it.
| Question | Why it matters |
|---|---|
| Is it available for every period the model needs, including next year? | A feature that stops arriving breaks retraining and scoring |
| Does the provider's definition match my concept? | "Household income" from a vendor may be modeled, not reported |
| May I train and deploy models on it? | Some licenses allow analysis but forbid model training or commercial use |
| May I share outputs derived from it? | Share-alike terms and no-redistribution clauses limit publication |
| What happens to my models if the contract ends? | Deletion clauses can reach derived data and trained models |
| Does it contain PII, and on what legal basis do I hold it? | Privacy law follows the data into every copy |
Key idea: public describes who can see data, not what you may do with it; read the license and the contract for model training, redistribution and share-alike before the data enters a pipeline.
The sourcing procedure, run one: Harbor Valley's leak model
Now put the pieces together. Harbor Valley Water is a fictional utility with 60,000 metered homes. Its operations manager wants a weekly ranked list of the 500 homes most likely to have a continuous leak, so crews can knock on doors. The data team follows five steps.
- State the question and the decision. This is prediction, not cause: rank homes by leak probability. The decision it feeds is where crews go.
- Trace the DGP of the target. Confirmed leaks come from crew work orders. Crews have only visited homes that complained or that an old threshold rule flagged, so the labels are selected: S depends on how visible the leak was. A home with no work order is not confirmed leak-free.
- List candidate sources by type. The register below shows them.
- Score each on fit, cost, availability and rights.
- Decide and record. The register becomes part of the project's documentation.
| Source | Type | DGP note | Cost and availability | Rights | Decision |
|---|---|---|---|---|---|
| Hourly meter reads | Sensor | Gaps, meter replacements | Internal, 3 years, every home | Internal | Use; repair replacements first |
| Billing and payments | Transactional | Bills are estimated when a read fails | Internal, monthly | Internal | Use as a monthly baseline; flag estimated bills |
| Crew work orders | Administrative | Only flagged homes were visited | Internal, 2,300 confirmed leaks | Internal | Use as labels; add a small random audit |
| County parcel records (year built, lot size) | Administrative, published as open data | Kept for property tax, updated yearly | Free, county open-data portal | CC BY 4.0 | Use; attribute the county |
| Daily weather | Public | One station for the whole service area | Free | U.S. public domain | Use; irrigation drives summer night flow |
| 2024 appliance survey | Survey | 1,200 volunteer respondents of 60,000 homes | Already done | Internal; consented for research | Not a feature (covers 2 percent of homes); use as a sanity check |
| Vendor property attributes (pool, irrigation system) | Commercial | Vendor infers them from imagery | Annual fee; renewal uncertain | Internal use only, no redistribution | Pilot only; avoid a model that breaks if the contract lapses |
| Copy for the contractor writing ingestion code | Synthetic | Fitted to real meter and billing data | About a day to build | No real customer rows leave the utility | Independent marginals plus injected edge cases |
Two decisions deserve explanation. First, the work-order labels are biased by the old flagging rule, the same selection problem as the approved-only loans. The cheapest repair is to obtain a little experimental data: send crews to a random sample of, say, 200 unflagged homes. That gives an unbiased estimate of the leak rate where the old rule never looked, and a clean check on the model's recall there.
Second, the synthetic row. The contractor is writing code that parses files, handles gaps and loads tables. That job needs the right columns, data types, value ranges and messy cases such as NO_READ rows and meter resets. It does not need the true relationship between night-time flow and building age. Independent marginals plus deliberately injected edge cases are cheap and safe, and rough accuracy is enough for the purpose.
Run two: one changed input flips the synthetic decision
Change one input. Six months later the utility asks the same contractor to train and tune the leak model itself, and the contractor still may not receive real customer data. Everything else in the register stays the same.
Rerun step 4 for the synthetic row. The purpose is now learning relationships: steady night flow matters more in older homes, summer irrigation masks leaks, and so on. Those are exactly the correlations that independent marginal sampling destroys, as the café table showed. A model trained on such data would learn noise. The team checks with a train-on-synthetic, test-on-real comparison. The results below are fictional.
| Training data | ROC-AUC on real holdout |
|---|---|
| Real data (internal benchmark) | 0.86 |
| Synthetic, independent one-way marginals | 0.53 |
| Synthetic, generator fitted to the joint distribution | 0.81 |
The receiver operating characteristic area under the curve (ROC-AUC) from Lesson 2 is the probability that the model ranks a random leaking home above a random non-leaking one. A value of 0.53 is barely better than the 0.5 of random ranking. The decision flips: marginal-based synthetic data are no longer fit for purpose. Two options remain. One is a generator that models the joint distribution, validated as above and checked for memorized rows. The other is a secure environment where the contractor works on real data under a data-sharing agreement without taking a copy away. Which wins depends on cost and on how strong a privacy guarantee the utility needs.
A third variation shows the same procedure pointing to a different data type. Suppose the question changes from "which homes leak?" to "does a text-message alert make customers fix leaks faster?" Customers who opted into texts may be more attentive anyway, so the existing records confound the alert with the kind of customer who receives it. Step 1 now asks about cause, so step 3 now needs experimental data: randomly assign leak-flagged homes to receive the alert or not, and compare repair times.
Key idea: the same source can be right for one purpose and wrong for the next; rerun the procedure whenever the question, the user of the data or the decision changes.
Exam cues: reading the stem
| The stem says | Points to | Commonly confused with |
|---|---|---|
| "cause", "effect of changing", "what would happen if we" | Experimental data with randomized assignment | More observational transactional data |
| "attitudes", "intentions", "why customers" | Survey data | Transactional data |
| "every region must be represented" | Stratified sampling | Cluster sampling |
| "sample whole neighborhoods to cut travel cost" | Cluster sampling | Stratified sampling |
| "collected to run a program", "tax records", "benefit claims", "already exists at low cost" | Administrative data | Survey data |
| "readings every second", "telemetry", "calibration", "drift" | Sensor data | Transactional data |
| "point of sale", "purchases", "clicks", "orders" | Transactional data | Sensor data |
| "cannot use production data for testing", "share without real records" | Synthetic data | A copy with names deleted |
| "columns match but relationships are lost" | Independent marginal sampling | Bad source data |
| "million synthetic rows, very narrow interval" | Synthetic rows add no information | A larger sample reduces uncertainty |
| "attribution only" | CC BY or ODC-By | CC BY-SA |
| "derived work must keep the same license" | Share-alike: CC BY-SA or ODbL | CC BY |
| "figures changed since last download", "series discontinued" | Revision and availability costs of public data | Licensing |
| "vendor may go out of business", "not available next year" | Availability risk of commercial data | Licensing |
| "who could not appear in the data", "how was it produced" | Data-generating process, selection | Data quality alone |
Common misconceptions
- "A bigger dataset fixes any problem." More rows shrink sampling error, roughly with the square root of n, but they leave selection bias, nonresponse bias and measurement error exactly where they were.
- "Synthetic data are automatically private." A generator that overfits can reproduce real records. Strong privacy claims need a method such as differential privacy, implemented correctly, and even then accuracy is traded away.
- "If every column's distribution matches, the synthetic set is good." Independent marginal sampling matches every column and destroys every relationship between columns. Test fidelity by training on synthetic data and scoring on real data.
- "Public data can be used any way you like." Visibility is not permission. Attribution and share-alike clauses, terms of service, and privacy law all still apply, and U.S. public-domain status for federal works does not extend to other governments.
- "Administrative records can simply replace a survey." They were built to run programs, so their concepts, time frames and coverage often differ from what you want to measure; in practice they work best supplementing surveys.
- "An experiment is always the best data." Experiments answer causal questions, but they are slow and costly. A pure prediction task usually needs representative observational data, not a randomized trial.
What you now know
- A data-generating process has three parts: the mechanism, the measurement and the selection, with the purpose of collection as a fourth question. A model trained on stored data learns P(X, Y* | S = 1), which equals the population relationship only when measurement and selection do not distort it.
- For a survey proportion from a simple random sample, SE = √(p(1 - p)/n). Quadrupling n halves the standard error, but no increase in n removes nonresponse bias. Stratified sampling guarantees each group is represented; cluster sampling saves cost but raises the standard error.
- Administrative data are kept to run programs and provide services. Their collection cost is already paid, their definitions and time frames vary by agency, and they work best supplementing surveys rather than replacing them.
- Sensor data put the instrument inside the DGP (gaps, resets, drift, saturation). Transactional data cover only people who transacted and change when the business system changes.
- Only experimental data, with randomized assignment, support causal claims without strong assumptions. Choosing a design starts with setting objectives and selecting process variables and levels.
- Every synthetic generator samples from a model. Generative models, including GANs, fit that model to real data; hand-engineered methods encode expert beliefs, and agent-based models encode interaction rules.
- Sampling columns independently from one-way marginals preserves each column and erases correlations. Generating more synthetic rows adds no information beyond the real data used to fit the generator.
- Correctly implemented differentially private synthetic data can be shared and combined without additional privacy risk, but implementation bugs break the guarantee silently, and synthetic data are not a general-purpose way to sanitize sensitive data.
- U.S. federal employees' works default to the U.S. public domain. CC BY and ODC-By require attribution only; CC BY-SA and ODbL add share-alike. Public data bring revision and availability costs; commercial data add vendor, contract and continuity risks.
Sources
- U.S. Census Bureau. (n.d.). Administrative Records in the American Community Survey. census.gov
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- U.S. Government Accountability Office. (2011). GAO-12-54: Federal Statistical System, Administrative Data. gao.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook: 5.3 Choosing an experimental design. itl.nist.gov
- NIST. (n.d.). NIST synthetic data explainer (Privacy Engineering / Differential Privacy Synthetic Data). nist.gov
- arXiv (academic preprint). (2023). Synthetic Data: Methods, Use Cases, and Risks. arxiv.org
- U.S. General Services Administration (Data.gov). (n.d.). Open Licenses. resources.data.gov
- Key terms
- Data-generating process (DGP)
- The full chain that produces each recorded value: the real-world mechanism, the way values are measured, and the selection rule that decides which cases are recorded at all.
- Sampling frame
- The actual list or source from which a survey sample is drawn, such as an address file or customer list; people missing from it can never be sampled.
- Stratified sampling
- A sample design that divides the population into groups called strata and draws a separate random sample from each, guaranteeing every group is represented.
- Administrative data
- Records that governments or organizations keep to run programs or provide services, later reused for analysis even though their definitions were set for the program.
- Sensor data
- Measurements recorded automatically by a device, such as a meter or accelerometer, whose sampling rate, calibration, gaps and resets form part of how the data were produced.
- Transactional data
- Records of business events such as sales, payments or clicks, captured by operational systems and covering only the events and people that actually transacted.
- Experimental data
- Data from a study in which the analyst assigns treatments, ideally at random, so that differences in outcomes can be attributed to the treatment.
- Synthetic data
- Artificial records sampled from a model of real data, whether fitted to records or written as expert rules, designed to share its statistical properties without any row describing a real individual.
- Open license
- A legally binding grant that lets anyone access, reuse and redistribute a work with few or no restrictions, sometimes with conditions such as attribution.
- Share-alike
- A license condition, found in CC BY-SA and ODbL, requiring that adaptations shared or published carry the same license as the original.
Ingesting and Storing Data
- Compare CSV, JSON, Parquet and compressed formats, and choose one for a given read and write pattern.
- Match structured, semi-structured and unstructured data to suitable storage, and choose batch or streaming ingestion from the latency of the decision being made.
- Explain how pipeline design, orchestration, persistence, refresh cycles, archiving and data lineage keep data correct, recoverable and auditable.
- Estimate memory requirements and choose between CPU, GPU and TPU for a workload.
A format nobody wrote down until 2005
In October 2005 the Internet Engineering Task Force (IETF) published Request for Comments (RFC) 4180, a short memo about the comma-separated values format.[1] The memo documented the format and registered a media type, text/csv, for files that use it.[1] Spreadsheet programs had been exchanging these files for years by then. Even so, the memo's introduction says the format had never been formally documented.[1] Its interoperability notes add that because there is no single specification, implementations differ considerably.[1]
This is what those differences look like when a file reaches your pipeline. The file below is a fictional export from an order system.
order_id,customer,city,amount
1001,Ana Ruiz,Lisbon,42.50
1002,"Okafor, Chidi",Lagos,18.00
1003,Lee Min-jun,Seoul,1,250.00
Row 1002 is correct. The customer name contains a comma, so the writer wrapped it in double quotes, and a careful reader keeps "Okafor, Chidi" as one field. Row 1003 is broken. The exporting program wrote a thousands separator into the amount without quoting it, so a reader finds five fields where the header promises four. One parser will stop with an error. Another will put 1 in the amount column, discard 250.00 and give no warning, leaving the Seoul revenue total wrong by a factor of 1,250.
The decisions in this lesson are meant to keep failures like this away from your models. You will choose how the bytes are laid out, where data of each shape is stored, when data moves and what coordinates the moving. You will also decide what must survive a crash, how often data is refreshed, where old data goes, how a number is traced back to its source and what hardware runs the work.
Exam objectives: 4.3 Explain data ingestion and storage concepts, in Domain 4.0, Operations and Processes.[2] The objective covers infrastructure requirements (resource sizing, the graphics processing unit or GPU, and the Tensor Processing Unit or TPU) and data formats (comma-separated values or CSV, JavaScript Object Notation or JSON, Parquet, and compressed formats). It also covers structured, semi-structured and unstructured storage, streaming, batching, pipeline implementation, orchestration and automation, persistence, refresh cycles, archiving and data lineage.
It helps to read the objective as a list of decisions. The table below names each one, and the rest of the lesson compares the options.
| Objective item | The decision it represents | Typical options |
|---|---|---|
| Data formats | How the bytes are laid out | CSV (text, one row per line), JSON (text, nested records), Parquet (binary, stored by column), plus compression |
| Structured, semi-structured and unstructured storage | Where data of each shape lives | Relational database or warehouse; document store or data lake; object storage with a metadata table |
| Streaming and batching | When data moves | Continuously, one event at a time; or on a schedule, in chunks |
| Pipeline implementation | Which steps run, and in what order | Extract, transform, load (ETL); extract, load, transform (ELT); or loading without transformation |
| Orchestration and automation | What starts the steps and coordinates them | A scheduler running a directed acyclic graph (DAG) of tasks, with retries and alerts |
| Persistence | What survives a crash or restart | Memory compared with durable, replicated storage and checkpoints |
| Refresh cycles | How often data, features and models are updated | Full or incremental refresh, at a pace set by the decision the data supports |
| Archiving | Where old data goes and how long it stays | Cheaper, slower storage tiers governed by a retention rule |
| Data lineage | Whether a number can be traced to its sources | Lineage records at table level or column level |
| Infrastructure requirements | What hardware runs the work | Memory, cores, storage and network; central processing unit (CPU), GPU or TPU |
Comma-separated values: rows of text held together by convention
A comma-separated values file stores one record per line. Commas separate the fields, and an optional first line, the header, names them. RFC 4180 records the conventions that careful writers follow. Every line should have the same number of fields. Spaces are part of a field, so a reader should not trim them away.[1] The last field on a line has no comma after it. A field that contains a comma, a double quote or a line break must be enclosed in double quotes. A double quote inside such a field is written twice, so the text She said "hi" is stored as "She said ""hi""".
Two facts about the RFC matter in practice. First, its status is informational. It states that it does not specify an Internet standard.[1] A program that ignores it is breaking a convention, not a rule. Second, it describes syntax only. A CSV file never states what type a field holds.
Most of the damage CSV does in data science comes from that missing type information:
- Leading zeros disappear. A reader that guesses types turns the postal code 02134 into the integer 2134. Product codes and account numbers are damaged in the same way.
- Dates are ambiguous. 03/04/2026 means 4 March in the United States and 3 April in most of Europe.
- Missing values have no standard spelling. One system leaves the field empty, while others write NA, null, a hyphen or 0. A 0 that really means "unknown" lowers every average it enters.
- Regional settings change the delimiter. In countries where the comma is the decimal separator, spreadsheet exports often put semicolons between fields, and a reader expecting commas sees each line as one long field.
- The character encoding is not recorded. If a file written in an old Windows code page is read as UTF-8, the most common encoding for Unicode text, accented names become unreadable characters.
The defense is to stop the reader from guessing. Declare the schema when you load the file. In pandas, for example, pd.read_csv("orders.csv", dtype={"postal_code": "string"}) keeps postal codes as text. Check that every line has the expected number of fields. Send failing rows to a quarantine file so they can be inspected, instead of letting them disappear.
JavaScript Object Notation: nested records with a few types
JSON (JavaScript Object Notation) is a lightweight, text-based format for exchanging data that does not depend on any one programming language. RFC 8259, published in December 2017, defines it.[3] Unlike CSV, JSON carries some type information. It has four primitive types (strings, numbers, booleans and null) and two structured types (objects and arrays).[3] An object is an unordered set of name/value pairs. A value can be another object or an array, and that is how JSON nests one structure inside another.[3] An array is an ordered list, and its elements do not have to share a type.[3]
The fictional event below, from a shopping app, shows why application developers like JSON.
{
"event_id": "e-77812",
"ts": "2026-11-02T14:03:11Z",
"user": {"id": 5521, "plan": "pro"},
"items": [
{"sku": "A-100", "qty": 2},
{"sku": "B-220", "qty": 1}
],
"coupon": null
}
The user is a nested object, the items form an array of objects, and the coupon is explicitly null instead of an empty string. That richness is what makes JSON awkward for modeling, because most models expect a flat table. Ingestion therefore has to flatten each record. The nested user.id becomes a user_id column. The two-item array becomes either two rows, one per item with the event fields repeated, or summary columns such as item_count = 2 and total_qty = 3. Each choice sets a different grain, meaning what one row of the table represents. If you mix grains, for example by joining item-level rows to an order total, revenue is counted twice in the training set.
JSON also has gaps of its own. It has no date type, so timestamps travel as strings, and their format is whatever the sender and receiver agree on. It has no schema, so a field present in one record can be missing from the next. Many systems store one JSON object per line, a convention usually called JSON Lines or newline-delimited JSON. A reader can then process a very large file one line at a time, and a writer can append one event at a time. That convention is not part of RFC 8259.
Apache Parquet: values stored by column, with the schema inside the file
Apache Parquet is an open-source, column-oriented file format designed for efficient storage and retrieval.[4] Its documentation emphasizes compression and encoding schemes for handling large volumes of complex data, and support in many programming languages and analytics tools.[4]
Column orientation is the key idea. A CSV or JSON Lines file stores record 1, then record 2, then record 3. Parquet stores all the values of the first column for a block of rows, then all the values of the second column, and so on. A Parquet file is divided into row groups, which are blocks of rows. Inside each row group, every column has its own column chunk, and each chunk is split into pages, the unit that is encoded and compressed. A footer at the end of the file records the schema, the location of each chunk, and summary statistics such as each chunk's minimum and maximum values. This layout lets a reader do two inexpensive things:
- Column pruning (also called projection) means reading only the column chunks a query needs and leaving the others untouched.
- Row-group skipping (also called predicate pushdown) means comparing a filter, such as order_date within October 2026, with each row group's minimum and maximum, then skipping groups that cannot contain matching rows.
Because the schema is stored in the file, the postal code that CSV damaged stays a string and a timestamp stays a timestamp. Parquet also has costs. It is a binary format, so you cannot read it in a text editor. Files are written as a whole, so adding a single row means writing a new file, and thousands of tiny files slow down every reader. The Parquet project also warns that implementations do not all support the same features, so test a file written by one engine in the engine that will read it.[4]
CSV, JSON and Parquet side by side
| Property | CSV | JSON | Parquet |
|---|---|---|---|
| Encoding | Text | Text | Binary |
| Layout | One record per line | Records, often one per line (JSON Lines) | Values grouped by column within each row group |
| Types | None: every field is text | String, number, boolean, null | Typed schema stored in the file footer |
| Nesting | None | Objects and arrays | Supported |
| Readable by a person | Yes | Yes | No: needs a tool |
| Reading 3 of 40 columns | Every line is parsed in full | Every record is parsed in full | Only those 3 column chunks are read |
| Adding one record | Append a line | Append a line | Write a new file |
| Typical role | Exports, spreadsheets, simple exchange | Application programming interface (API) responses, event logs, configuration | Analytical storage in lakes and warehouses |
The point: CSV and JSON are good for exchanging data between systems, and Parquet is good for storing data you will analyze many times. A common design keeps data in the format the source produced when it first lands, then converts it to a typed, columnar format for analysis.
Worked example: one query against two layouts
Take a fictional orders table with 50,000,000 rows and 40 columns. For illustration, assume a field averages 12 bytes when written as text. The analyst asks for "average order amount by city for October 2026". That query needs three columns: order_date, city and amount. The table covers 24 months of orders, spread evenly across them.
Run 1, stored as CSV.
- File size: 50,000,000 rows × 40 fields × 12 bytes = 24,000,000,000 bytes, or about 24 GB.
- To find the city field on a line, the parser must read every byte before it. To find the start of the next line, it must read every byte after it. Nothing in the file says where a column begins, so the reader has to scan and parse all 24 GB.
- Bytes read: about 24 GB. Every number also has to be converted from text, which costs CPU time on top of the time spent reading from disk.
Run 1 again, stored as Parquet.
- Column pruning: 3 of 40 columns is 7.5 percent of the data. Before compression, that is 24 GB × 3 ÷ 40 = 1.8 GB.
- Compression: assume an illustrative 4:1 ratio for these columns. Real ratios depend entirely on the data. 1.8 GB ÷ 4 = 0.45 GB.
- Row-group skipping: October is 1 month out of 24. If the file was written in date order, the minimum and maximum dates rule out about 23 of every 24 row groups. 0.45 GB ÷ 24 ≈ 0.019 GB, or about 19 MB.
For the same table and the same query, the reader handles roughly 24 GB in one layout and roughly 19 MB in the other. The numbers are illustrative, but the mechanism is real: storing by column and keeping statistics turns a full scan into a targeted read. Step 3 depended on the rows being sorted or partitioned by date. If the rows had been written in random order, every row group would cover the whole date range and none could be skipped.
Run 2: change the workload. Now the same orders feed a customer-service screen. An agent types an order_id and sees all 40 fields of that single order, and agents do this thousands of times an hour. Here the columnar layout works against you. The reader must open 40 separate column chunks and take one value from each to rebuild the row. Without an index, it may also have to search many row groups to find the order_id. A relational database that stores whole rows and keeps an index on order_id returns the record after reading only a few pages.
Change the workload once more. A sensor sends one reading per second. Writing each reading to its own Parquet file would create 86,400 tiny files a day. The usual pattern writes readings to a format that is easy to append to, such as JSON Lines or a message log. A batch job then compacts them into Parquet, perhaps once an hour.
The point: choose the layout from the access pattern. Columnar formats are better when queries read a few columns across many rows. Row-oriented storage is better when you read or write whole records one at a time.
Compressed formats: spending CPU to save bytes
The objective lists compressed formats separately because compression happens in two different places, and the two behave differently.
- Whole-file compression wraps an entire file in a general-purpose codec. orders.csv.gz, for example, is a CSV file compressed with gzip. The reader has to decompress the data from the start before it can parse a single row.
- Format-internal compression is part of the file format. Parquet encodes and compresses each page of each column chunk on its own. Before compressing, it applies encodings that take advantage of the structure of a column.
Columns compress better than rows because compression works by finding repetition. A row mixes an ID, a name, a date and a price, which have nothing in common. A column holds the same kind of value many times, and often the same few values over and over.
Here is a worked example of that mechanism. A country column holds 50,000,000 values but only 30 distinct countries, and each country name averages 8 bytes of text.
- As plain text the column takes 50,000,000 × 8 bytes = 400 MB.
- Dictionary encoding stores the 30 country names once and replaces each value with a short code. Codes 0 to 29 fit in 5 bits, because 25 = 32, which is at least 30. The codes take 50,000,000 × 5 bits = 250,000,000 bits = 31.25 MB, plus a dictionary of a few hundred bytes.
- If the rows are sorted by country, run-length encoding shrinks the column further. It stores "code 7, repeated 1,000,000 times" instead of storing the same code a million times, so 30 runs describe the whole column.
- A general-purpose codec can then compress whatever remains.
Those steps take the column from 400 MB to tens of megabytes before the codec even runs. That is why columnar files are often much smaller than the CSV they came from. The smaller size also makes queries faster, because reading bytes from disk or over a network usually takes more time than the CPU needs to decompress them.
Codecs trade size against speed. As a general pattern, gzip and Zstandard produce smaller output but use more CPU, while Snappy and LZ4 compress less and decompress very quickly. Parquet writers let you choose the codec. For large data, one property often matters more than the compression ratio: splittability, meaning whether several workers can read parts of one file in parallel. A single large .csv.gz file must be decompressed from its first byte, so one worker reads all of it while the rest of the cluster waits. Because Parquet compresses page by page inside each row group, every row group can be read and decompressed independently, and many workers can read different row groups of the same file at once. If you have to deliver compressed CSV, deliver many moderately sized files rather than one huge file.
| Option | Size on disk | Cost of reading | Parallel reading |
|---|---|---|---|
| Uncompressed CSV | Largest | Every byte read and parsed | Yes, split at line breaks (unless quoted fields contain line breaks) |
| One gzip-compressed CSV | Smaller | Decompress, then parse everything | No: one worker per file |
| Parquet with Snappy | Small | Fast decompression of only the pages needed | Yes, by row group |
| Parquet with gzip or Zstandard | Smaller | More CPU for each page read | Yes, by row group |
Every format in this objective uses lossless compression: decompressing returns exactly the original bytes. Images and audio often arrive in lossy formats, such as the JPEG photo format or the MP3 audio format, which throw away detail to save space. If you re-save training images in a lossy format at every pipeline step, quality drops a little each time. Store the original once and create derived versions from it.
Structured, semi-structured and unstructured storage
The storage categories follow the shape of the data. Structured data fits a schema defined in advance, with fixed columns and fixed types, and is often loaded into a relational database or a data warehouse.[5] Semi-structured data labels its own fields but has no fixed schema. Extensible Markup Language (XML) and JSON files are the standard examples.[5] Microsoft's data-lake guidance adds log files to the semi-structured group. It gives images, audio and video as examples of unstructured data, which has no fields a database can index directly.[6] If these categories are new to you, the Atlas Data+ course introduces them.
| Category | What defines it | Examples | Typical store | How you query it | Common failure |
|---|---|---|---|---|---|
| Structured | Fixed columns and types, defined before loading | Orders, customers, ledger entries | Relational database, data warehouse | Structured Query Language (SQL) on columns | The load fails or drops data when the source adds a column |
| Semi-structured | Fields label themselves; the schema varies from record to record | JSON events, XML feeds, application logs | Document database, files in a data lake | Parse and flatten, then query | A field is renamed and quietly becomes nulls (schema drift) |
| Unstructured | No field structure to index | Images, audio, video, PDFs, free text | Object storage plus a metadata table | Query the metadata; process the content with models | Files nobody can find because their metadata was never recorded |
The larger architectural question is when structure is applied. A data lake keeps data in its original, untransformed form and transforms it only when someone needs it. This approach is called schema-on-read.[6] A data warehouse enforces structure and transforms data as it ingests it. This approach is called schema-on-write.[6] Schema-on-write stops bad data at the door, but it rejects anything that does not fit. Schema-on-read accepts everything and keeps the raw record so it can be reprocessed later, but problems surface only when someone queries the data. Many organizations now use both, in a lakehouse arrangement that pairs raw storage with fast structured queries.[6] Managed warehouses can be very large: Amazon describes Redshift as a petabyte-scale cloud data warehouse service.[7]
Unstructured data needs one practical habit. You almost never query the pixels themselves. You query a metadata table that points to the files. Here is a fictional example from a project that detects defects in manufactured parts; the file paths point into object storage:
| file_uri | captured_at | camera_id | label | sha256 (shortened) | bytes |
|---|---|---|---|---|---|
| s3://plant-images/2026/10/31/cam07/000184.jpg | 2026-10-31T08:14:02Z | cam07 | scratch | 9f2c...a1 | 412,880 |
| s3://plant-images/2026/10/31/cam07/000185.jpg | 2026-10-31T08:14:04Z | cam07 | ok | 03bd...7e | 398,112 |
| s3://plant-images/2026/10/31/cam11/000009.jpg | 2026-10-31T08:15:40Z | cam11 | dent | c41a...0f | 420,664 |
The checksum (sha256) lets you detect a file that has been corrupted or quietly replaced. The label and capture time let you build a training set with an ordinary SQL query.
Batching and streaming: when the data moves
Streaming data is produced continuously, a piece at a time and in high volume, and it often needs to be processed with little delay.[8] Batch processing is the older pattern, in which computers periodically run large, repetitive jobs over data collected during a period of time.[8] The two mechanisms differ. Stream processing updates its results a little at a time as each record arrives, while a batch job computes over everything it has collected at once.[8] AWS gives monthly accounting as an example of the occasional, high-volume tasks that batch pipelines suit.[5] A batch pipeline runs each step over the whole batch and loads the result into a warehouse or similar store once every transformation has finished.[5]
| Property | Batching | Streaming |
|---|---|---|
| Trigger | A schedule (such as 02:00 daily) or a size threshold | Each arriving event |
| Unit of work | Everything collected during the interval | One record, or a small window of records |
| Typical delay | Minutes to days | Milliseconds to seconds |
| Completeness | The batch is complete when the job runs, unless files arrive late | Results are provisional, and late events can change them |
| Cost profile | Compute runs only while the job runs | Consumers run all the time |
| Hard parts | Long reruns, backfills, late files | Ordering, duplicates, lost events, lag, saved state |
| Typical uses | Reports, model retraining, monthly billing | Fraud scoring, sensor alerts, live dashboards |
Streaming has the harder list of problems for good reason. AWS names low latency and high fault tolerance as requirements.[5] It also says a streaming pipeline should keep working when some data is lost or arrives out of order.[5] Three ideas deal with those problems:
- Event time compared with processing time. Event time is the timestamp the device wrote when the event happened. Processing time is when the server received it. A phone that loses signal in a tunnel sends its events late. If you group events by processing time, a burst appears at 08:15 for activity that really happened at 08:05. Group by event time.
- Time windows. A stream never ends, so aggregates are computed over windows of time. A tumbling window covers fixed intervals that do not overlap, such as each minute. A sliding window covers the most recent N minutes and is recomputed as it moves forward.
- Late data, gaps and lag. The system decides how long to wait for late events before closing a window. When a source cannot resend data, AWS notes, systems leave gaps in the history and backfill them if the data arrives later.[8] When traffic spikes and consumers fall behind producers, the difference between them, called lag, has to be monitored and planned for.[8]
The two modes are often combined. Many organizations run a real-time layer for immediate results alongside a batch layer for complete, corrected history.[8] Micro-batching is a middle ground that processes small batches every few seconds or minutes.
Worked decision. A bank has two models. A churn model predicts which customers will close their accounts within 90 days, and the retention team phones the top 500 each Monday. A fraud model decides whether to approve a card payment while the customer waits at the checkout.
- Churn: the decision is made once a week. A score computed on Sunday night is as useful on Monday morning as one computed a second ago, so a weekly or nightly batch job is the right choice.
- Fraud: the decision has to be made during card authorization, in under a second. A score from last night's batch knows nothing about the three payments made in different countries over the last ten minutes. This model needs streaming, with features such as "transactions in the last 10 minutes" updated as each event arrives.
Change one input. Suppose the fraud model does not approve or decline anything. It only produces a list that investigators review at 09:00 the next day. The decision is now made daily, and a nightly batch job does the same work at a fraction of the cost and complexity. The speed of the decision, not the speed of the data source, determines how the data should be ingested.
Pipeline implementation: ETL, ELT and load-only
A data pipeline is a series of processing steps that prepares data for analysis.[5] Its endpoint, which may be a warehouse, a lake or another store, is sometimes called the data sink.[5] The main design choice is where the transformation happens.
- Extract, transform, load (ETL). Tools copy raw data from the sources into a temporary staging area, transform it there, and then load the result into the warehouse or lake.[5] Only cleaned data reaches the destination.
- Extract, load, transform (ELT). Raw data, including unstructured data, is loaded straight into a lake, and transformations run later, shortly before analysis needs them.[5] The destination's own engine does the transforming, and the raw copy stays available if the logic has to change and the data must be reprocessed.
- Load-only. Some pipelines copy data from a source to a destination without any transformation.[5] A nightly copy of a production table is an example.
Whatever the pattern, each step of a dependable pipeline has a check that fails loudly instead of letting bad data through quietly. The fictional daily orders pipeline below shows the idea. Its thresholds are examples, not standards.
| Stage | What it does | Check that stops the run if it fails |
|---|---|---|
| Extract | Pulls yesterday's orders from the source API as JSON | The record count matches the total the API reports |
| Validate | Parses records, enforces the schema, sends bad rows to quarantine | Quarantined rows are under 0.5 percent, or the run stops |
| Transform | Flattens items, converts currency, removes duplicate order_id values | No order_id appears twice after this step |
| Load | Overwrites the partition for yesterday's order_date in Parquet | The loaded row count equals the validated row count |
| Publish | Updates the feature table and records lineage | The freshness timestamp has advanced |
Three design habits appear in that table. Validate data when it enters the pipeline. Quarantine bad rows instead of dropping them. Partition the output by the field people filter on, which here is order_date, so later reads can skip the partitions they do not need.
Orchestration and automation: the scheduler and the DAG
Automation means a step runs without a person starting it. Orchestration means coordinating many automated steps: running them in the right order, passing results between them, retrying failures and raising alerts. Microsoft's data-lake guidance notes that as data volume and variety grow, transformation and query workloads can introduce latency, which calls for careful pipeline design and workload orchestration.[6]
Orchestrators such as Apache Airflow describe a pipeline as a directed acyclic graph (DAG). Each task is a node. Each dependency is a directed edge from the task that must finish first to the task that waits for it. Acyclic means no path through the graph leads back to its starting point, which guarantees that a valid running order exists. A cycle such as "features waits for training, and training waits for features" has no order in which either task can start.
# Illustrative pseudocode in the style of an orchestrator DAG (not an exact API)
pipeline daily_orders:
schedule = "0 2 * * *" # minute 0 of hour 2, every day
retries = 3
retry_delay = 10 minutes
timeout = 60 minutes
on_failure = alert("data-oncall")
extract = fetch_orders(date = run_date)
validate = check_schema(extract)
transform = flatten_and_dedupe(validate)
load = overwrite_partition("orders", order_date = run_date)
features = rebuild_features(load)
extract >> validate >> transform >> load >> features
The schedule string is a cron expression with five fields: minute, hour, day of month, month and day of week. An asterisk means "every", so 0 2 * * * means minute 0 of hour 2 on every day, which is 02:00 daily. Besides time-based schedules, orchestrators can start a run when an event occurs, such as a file arriving. They also provide retries, timeouts, alerts and backfills, which are runs of the pipeline for past dates, for example after a bug fix.
Retries and backfills are safe only when tasks are idempotent, meaning a task run twice for the same date leaves the same result as running it once. The following worked example shows why.
- On 3 March there are 120,000 orders. The load task appends rows to the orders table.
- The task writes 70,000 rows and then crashes. The orchestrator retries it, and the retry appends all 120,000.
- The table now holds 190,000 rows for 3 March. Revenue for that day is overstated by 70,000 ÷ 120,000 ≈ 58 percent, and no error was raised.
- Now change the load so that it overwrites the 3 March partition. The retry replaces whatever the failed attempt wrote, and the partition holds exactly 120,000 rows.
The point: an orchestrator decides when tasks run and in what order, but only idempotent tasks make its retries and backfills safe. Write each task so that running it again for the same date replaces its output instead of adding to it.
Persistence: what survives a restart
Persistence means writing data to storage that outlives the process that created it. A pandas DataFrame or the running counts of a stream processor live in memory, and a restart erases them. AWS describes a common pattern in which a stream is processed for real-time insights and then persisted to an object store such as Amazon Simple Storage Service (Amazon S3) for later batch use.[8] Three persistence decisions come up again and again.
- Keep a raw landing copy. Persist the input before transforming it. If the transformation logic turns out to be wrong, you can reprocess from the raw copy instead of asking the source to send the data again, which may be impossible. This is one of the main reasons ELT keeps raw data.
- Checkpoint streaming state. A stream processor periodically writes its state, such as running counts and its position in the stream, to durable storage. After a crash it resumes from the last checkpoint instead of starting over or skipping events. AWS notes that durability in streaming usually requires fault tolerance in the pipeline, replication across the stream's broker nodes, and monitoring of the whole system.[8]
- Persist intermediate results inside a job. In Apache Spark, calling persist() or cache() on a dataset keeps a computed result in memory or on disk so later steps can reuse it instead of recomputing it. That copy belongs to the running application and disappears when the application ends, so it is not a substitute for writing results to storage.
Persistence and durability are different properties. Persistence means data outlives the process that wrote it. Durability means data survives the failure of the disk, machine or site that holds it, which usually requires copies on several devices or in several locations. A file on one disk is persistent but not durable, which is why the AWS guidance mentions replication.
Refresh cycles: full versus incremental
A refresh cycle is how often a dataset, feature table, dashboard or model is brought up to date. Two questions are involved: how often to refresh (the cadence) and how (the method). Set the cadence from the decision the data supports, not from habit. A call list used every Monday needs a weekly refresh, while daily stock replenishment needs a daily one. Each extra refresh costs compute and adds another chance for something to fail.
There are two methods. A full refresh rebuilds the whole table from the source. An incremental refresh copies only the rows that changed since the last successful run, usually found through a watermark, such as the latest updated_at value already loaded.
Worked example. A customer table has 40,000,000 rows, and about 200,000 of them change each day.
- A full refresh copies 40,000,000 rows every night.
- An incremental refresh selects only rows with updated_at later than the stored watermark, for example
WHERE updated_at > '2026-11-16 02:00:00'. That is about 200,000 rows, or 0.5 percent of the work. - Store the new watermark only after the load succeeds. If you advance it first and the load then fails, the next run starts from the new watermark and a whole day of changes is lost.
Change one input. Suppose the source application updates email addresses with a bulk tool that does not touch updated_at, and it hard-deletes closed accounts instead of flagging them. The incremental refresh never sees those changes or deletions, so the copy drifts away from the source with no error. The fixes are to capture changes from the database's own change log (change data capture) or to run a periodic full refresh, such as weekly, that reconciles the copy with the source and compares row counts.
| Asset (fictional) | Cadence | Method | Reason |
|---|---|---|---|
| Orders table | Hourly | Incremental on order_id and updated_at | The dashboard shows today's sales |
| Customer table | Incremental nightly, full weekly | Watermark plus reconciliation | The source misses some updates |
| Churn features | Weekly | Full rebuild | They feed the Monday call list |
| Churn model | Monthly, or when a drift alert fires | Retrain on the latest 24 months | Customer behavior changes slowly |
Archiving: cheaper and slower, but still findable
Archiving moves data that is rarely read to cheaper, slower storage while keeping it retrievable. Microsoft lists data archiving among the standard data-lake use cases, together with ingestion, big data processing, analytics and machine learning, and reporting.[6] Storage is usually arranged in tiers, as in the table below. The costs are relative, and the exact prices and retrieval times depend on the provider.
| Tier | How often it is read | Relative cost per GB | Retrieval | Example contents |
|---|---|---|---|---|
| Hot | Daily | Highest | Immediate | This year's events, live feature tables |
| Warm or cool | Monthly | Lower | Immediate or nearly so | The last two or three years, kept for retraining |
| Cold or archive | Rarely: audits, legal requests | Lowest | Can take minutes to hours | Raw files older than the retraining window, frozen training snapshots |
For data science, six archiving rules matter most:
- Archive every training snapshot. Keep the exact training data of each deployed model with its code version, so its results can be reproduced.
- Use an open, self-describing format. A compressed format that carries its own schema, such as Parquet, can still be read years later without the original software.
- Write a retention policy. State how long each class of data is kept and when it is deleted.
- Keep privacy obligations attached. Archived personal data is still subject to privacy law, so moving it to a cold tier does not exempt it from a deletion requirement.
- Test restores. An archive that has never been restored has not been shown to work.
- Catalog what you archive. Record what each archive holds and where, so it can be found when an audit or a retraining job needs it.
An archive is different from a backup. A backup is an extra copy kept so you can recover from loss. An archive is often the only remaining copy of old data, moved there to save cost while meeting a retention rule.
Data lineage: tracing a number back to its source
Data lineage is the record of where data came from, what happened to it, and where it went. Apache Airflow's documentation describes its lineage feature in those terms.[9] It lists audit trails, data governance and debugging of data flows as the benefits.[9] Airflow records lineage through each task's inlets, the data the task reads, and outlets, the data it writes.[9] The 2.5.3 documentation marks this feature as very experimental and subject to change.[9] Lineage tooling is still settling, which is why open specifications such as OpenLineage exist to let different tools share lineage records.
| Dataset (fictional) | Produced by task | Inputs | Run | Code version |
|---|---|---|---|---|
| features.churn_weekly, 2026-11-16 | rebuild_features | warehouse.orders, warehouse.customers, lake.support_tickets | 2026-11-16T02:00Z | git 4e1a9c2 |
| Training set for churn_v14 | snapshot_training | features.churn_weekly, 2026-10-05 to 2026-11-16 | 2026-11-16T05:30Z | git 4e1a9c2 |
Table-level lineage, like the example above, records which datasets feed which. Column-level lineage goes further and records that, for example, features.avg_basket is computed from orders.amount and orders.items_count. Lineage supports four kinds of work:
- Debugging. A feature suddenly becomes all nulls. Walking upstream through the lineage shows that a source column was renamed.
- Impact analysis. Before you change a source column, walking downstream shows which dashboards and models will break.
- Audit and privacy. You can show a regulator which sources fed a model, and find every table that a field containing personally identifiable information (PII) reached.
- Reproducibility. Lineage, archived inputs and a recorded code version together let you rebuild a training set exactly.
Resource sizing: do the arithmetic before you buy
Infrastructure requirements begin with four quantities: memory, compute (CPU cores or accelerators), storage and network bandwidth. Sizing means estimating each one from the data and the workload, then adding spare capacity, called headroom.
Worked example: memory for a feature table. The table has 200,000,000 rows and 40 numeric columns stored as 64-bit floats, which take 8 bytes each.
- Raw size: 200,000,000 × 40 × 8 bytes = 64,000,000,000 bytes, or 64 GB.
- Transformations make copies. A join or a sort can briefly hold both its input and its output, so peak memory is a multiple of 64 GB. A machine with 64 GB of memory will fail.
- Reduce the size. Store values as 32-bit floats (4 bytes) where the precision is enough, and load only the 12 columns the model uses: 200,000,000 × 12 × 4 = 9,600,000,000 bytes, or 9.6 GB. A 64 GB workstation now has plenty of headroom.
Change one input. If the table grows to 2,000,000,000 rows next year, even the reduced version is 2,000,000,000 × 12 × 4 bytes = 96 GB. At that point it makes sense to stop buying a bigger machine and spread the work across several machines instead. Traditional ETL pipelines often scale vertically on one host, which reaches its limits quickly.[6] Distributed systems scale horizontally by adding compute and storage nodes as needed.[6] Serverless services change the cost side of the calculation. Amazon says Redshift Serverless does not charge while the warehouse is idle, so you pay only for what you use.[7] That suits workloads that come in bursts. A workload that runs around the clock may cost less on capacity provisioned in advance.
Worked example: memory for training a model. A model has 1,000,000,000 parameters stored as 32-bit floats. The weights alone take 1,000,000,000 × 4 bytes = 4 GB. Training with the Adam optimizer, a widely used variant of gradient descent, keeps more than the weights. Each parameter also has a gradient (the slope of the loss with respect to that parameter) and two running averages of past gradients that Adam maintains, called moment estimates. That makes four copies: 4 × 4 GB = 16 GB. On top of that come the activations, the intermediate outputs of each layer that are saved during the forward pass so gradients can be computed, and they grow with batch size. A GPU with 16 GB of memory cannot train this model as it stands. You need a larger card, mixed precision (storing and computing some values as 16-bit floats instead of 32-bit, which halves their memory), or a method that splits the model state across several devices.
Storage and network need the same kind of arithmetic. Storage equals daily volume × retention days × the number of copies kept. Network time equals bytes × 8 ÷ link speed in bits per second. Moving 10 TB over a link of 1 gigabit per second (Gbps) takes 10,000,000,000,000 × 8 ÷ 1,000,000,000 = 80,000 seconds, about 22 hours, before any protocol overhead.
CPU, GPU or TPU: matching the hardware to the math
A central processing unit (CPU) has a modest number of powerful cores that handle branching, varied logic well. A graphics processing unit (GPU) has thousands of simpler cores that apply the same operation to many values at once, which is exactly what matrix multiplication in neural networks needs. A Tensor Processing Unit (TPU) is an application-specific integrated circuit (ASIC), a chip built for one kind of job, that Google designed to speed up machine learning workloads.[10] A tensor is a multi-dimensional array of numbers, such as a batch of images stored as examples × height × width × channels. TPUs are built for the large matrix operations common in machine learning.[10] Code that runs on a TPU has to be compiled by the XLA (Accelerated Linear Algebra) compiler.[10]
Google's guidance on choosing hardware leans on two more terms. The batch size is the number of examples processed in one training step. The effective batch size is the number of examples processed per optimizer step across all devices, so 8 devices each handling 128 examples give an effective batch size of 1,024.
| Hardware | Suits, per Google's Cloud TPU guidance | Avoid when |
|---|---|---|
| CPU | Fast prototyping that needs maximum flexibility; simple models that train quickly; small models with small effective batch sizes; models limited by the host's input/output or network bandwidth | Large neural networks trained for days |
| GPU | Models with many custom PyTorch or JAX operations that must run at least partly on the CPU; medium to large models with fairly large effective batch sizes | Small tabular jobs where the cost of moving data to the device outweighs the speedup |
| TPU | Models dominated by matrix computation; no custom operations in the main training loop; training that lasts weeks or months; large models with large effective batch sizes | Frequent branching or many element-wise operations; high-precision arithmetic; tensor shapes that change between batches |
The table follows Google's guidance. That guidance recommends CPUs for fast prototyping where flexibility matters most.[10] It points to GPUs for models with many custom PyTorch or JAX operations that must run at least partly on a CPU.[10] GPUs also suit medium to large models with fairly large effective batch sizes.[10] TPUs suit, among other cases, models trained for weeks or months.[10] The same guidance says TPUs are a poor fit for linear-algebra programs that branch often or rely heavily on element-wise operations.[10]
The reasons come from how the TPU works. XLA compiles the model graph when the first batch arrives. If a later batch has a different shape, the graph has to be recompiled, which is slow, so models whose tensors change shape are poorly suited to TPUs.[10] The TPU's matrix unit is a 128 × 128 systolic array, a grid of cells that pass partial results to their neighbors.[10] To keep that unit busy, XLA uses either the batch size or the feature dimension, so at least one of the two should be a multiple of 128.[10] If neither is, the compiler pads one of them up to 128 with zeros.[10] Ideally, both the batch size and the feature dimension are also multiples of 8, which lets the memory subsystem perform well.[10] Padding has two costs. Zero-padded tensors leave the TPU cores underused.[10] Padding also increases the on-chip memory a tensor needs, and in the worst case it causes an out-of-memory error.[10] The practical rule: choose a batch size or feature dimension that is a multiple of 128, and keep both multiples of 8.
For a tree-based model on tabular data, a CPU is usually enough. Gradient-boosting libraries such as XGBoost (Extreme Gradient Boosting) also offer GPU training when the data is large.
The point: size memory as rows × columns × bytes per value, plus headroom for copies. Then choose hardware by the kind of math: varied logic and small jobs go to a CPU, flexible deep learning to a GPU, and long, matrix-heavy training with fixed tensor shapes to a TPU.
Exam cues: what the question says and what it points to
| The question says | It points to | Do not confuse with |
|---|---|---|
| "Reads only a few columns", "analytical queries", "columnar" | Parquet | Gzip-compressed CSV: smaller, but still read and parsed in full |
| "Nested", "arrays", "API response", "optional fields" | JSON; semi-structured storage | Structured storage, which needs a fixed schema |
| "Spreadsheet export", "readable by a person", "no types" | CSV | JSON, which carries types and nesting |
| "Images, audio, video, PDFs" | Unstructured storage with a metadata table | Semi-structured data, which has labeled fields |
| "Real time", "each event", "milliseconds" | Streaming | Micro-batching, a short-interval middle ground |
| "Nightly", "monthly", "large volume, not urgent" | Batching | Streaming, which costs more for no gain here |
| "Staging area", "transform before loading" | ETL | ELT: load raw data first, transform in the destination |
| "Dependencies", "retries", "schedule", "DAG" | Orchestration | Lineage, which records data flow but runs nothing |
| "The rerun produced duplicate rows" | A task that is not idempotent | Missing persistence |
| "Survives a restart", "checkpoint" | Persistence | Archiving, which is about cost and retention |
| "Only changed rows", "watermark" | Incremental refresh | Full refresh |
| "Keep for 7 years", "rarely accessed", "cold tier" | Archiving | Backup, an extra copy kept for recovery |
| "Which sources fed this model", "audit trail", "impact of changing a column" | Data lineage | Orchestration logs |
| "Matrix-heavy", "fixed shapes", "weeks of training" | TPU | GPU, the better choice for custom operations and changing shapes |
| "Out of memory", "how many GB" | Resource sizing: rows × columns × bytes per value | Size on disk, which is compressed |
Common misconceptions
- "Parquet is always faster than CSV." It is faster for analytical reads of a few columns across many rows. Looking up single whole records and appending one tiny record at a time favor row-oriented storage.
- "Gzipping a CSV gets you most of Parquet's benefits." Gzip shrinks the file, but every query still decompresses and parses every column. A single gzip file cannot be read in parallel, and the data still has no types.
- "Streaming is the modern replacement for batch." The right choice depends on how quickly the decision must be made. Streaming costs more to build and run, and many systems combine a real-time layer with a batch layer.
- "JSON is unstructured data." JSON fields carry their own labels, which makes JSON semi-structured. Unstructured data, such as images, audio and free text, has no fields to label.
- "Archived data is outside privacy rules." Retention and deletion obligations still apply to data in a cold tier.
- "A TPU is just a faster GPU." A TPU is an ASIC built for matrix operations. It requires XLA compilation and works poorly with changing tensor shapes and custom operations in the training loop, which GPUs handle well.
The takeaway
- RFC 4180 (October 2005) is informational, not an Internet standard. CSV has quoting conventions but no types, so declare a schema when you read a CSV file.
- JSON has four primitive types (string, number, boolean, null) and two structured types (object, array). It is semi-structured, and flattening it means choosing the grain of the resulting table.
- Parquet stores values by column and keeps the schema and per-row-group minimum and maximum statistics in its footer, so readers skip unneeded columns and row groups. It compresses page by page inside each row group, so one file can be read in parallel, while one gzip-compressed CSV must be decompressed from the start by a single worker.
- A warehouse applies structure as data is loaded (schema-on-write), typically after ETL has transformed it in a staging area. A data lake keeps raw data (schema-on-read), typically loaded by ELT and transformed later in the destination, so it can be reprocessed.
- Choose batch or streaming from how quickly the decision must be made. Streaming must cope with events that arrive late, out of order, duplicated or not at all, and must monitor consumer lag.
- Reruns are safe only by design: an idempotent load overwrites its date partition instead of appending, and an incremental refresh advances its watermark only after the load succeeds.
- Memory for a table is rows × columns × bytes per value, plus headroom for the copies that joins and sorts make. Training with Adam in 32-bit floats needs about four copies of the parameters before activations are counted.
- TPUs suit long, matrix-heavy training with fixed tensor shapes, ideally with a batch size or feature dimension that is a multiple of 128. GPUs suit custom operations and changing shapes, and CPUs suit prototypes and small or tabular jobs.
- Data lineage records each task's inputs and outputs, so a number can be traced to its sources for debugging, impact analysis, audit and reproducibility.
Sources
- Y. Shafranovich. (2005). Common Format and MIME Type for Comma-Separated Values (CSV) Files (RFC 4180). IETF. datatracker.ietf.org
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- T. Bray, Ed. (2017). The JavaScript Object Notation (JSON) Data Interchange Format (RFC 8259). IETF. datatracker.ietf.org
- Apache Software Foundation. (n.d.). Apache Parquet Documentation: Overview. parquet.apache.org
- Amazon Web Services. (n.d.). What is a Data Pipeline? aws.amazon.com
- Microsoft Learn. (n.d.). Data lakes. learn.microsoft.com
- Amazon Web Services. (n.d.). Data processing - Data Warehousing on AWS. docs.aws.amazon.com
- Amazon Web Services. (n.d.). What is Streaming Data? aws.amazon.com
- Apache Airflow Documentation. (2023). Lineage. airflow.apache.org
- Google Cloud. (n.d.). Introduction to Cloud TPU. docs.cloud.google.com
- Key terms
- Apache Parquet
- An open-source binary file format that stores data by column, in row groups whose column chunks are split into compressed pages, with a typed schema and per-chunk statistics, so readers can load only the columns and row groups a query needs.
- Schema-on-read
- Keeping data in its raw form and applying structure only when it is queried, as a data lake does; the opposite of schema-on-write, where a warehouse enforces structure as data is loaded.
- Streaming ingestion
- Moving and processing data continuously, one event or small window at a time, so results update within milliseconds to seconds of each event.
- Batch processing
- Running a scheduled job over all the data collected during an interval, such as a nightly or monthly run, so results are complete but delayed.
- ELT (extract, load, transform)
- A pipeline pattern that loads raw data into the destination first and transforms it there later, keeping the raw copy available for reprocessing.
- Directed acyclic graph (DAG)
- A set of tasks joined by one-way dependency edges with no cycles, which guarantees a valid order in which an orchestrator can run them.
- Idempotent task
- A pipeline task that leaves the same result whether it runs once or several times for the same input, for example by overwriting a date partition instead of appending to it.
- Incremental refresh
- Updating a copy of a dataset with only the rows changed since the last successful run, usually found by comparing a timestamp column with a stored watermark.
- Data lineage
- A record of where a dataset came from, which transformations produced it and where it went, used for debugging, impact analysis, audit and reproducibility.
- Tensor Processing Unit (TPU)
- A Google-designed application-specific chip for machine learning that runs large matrix operations through code compiled by the XLA compiler, and works best with fixed tensor shapes.
Data Wrangling in Practice
- Diagnose a broken merge by defining keys and cardinality, choosing the right join type, and tracking observations through each step.
- Standardize dates, units, text patterns and missing codes, and tell systematic errors from idiosyncratic ones.
- Identify outliers with fences and modified z-scores, decide whether a flagged value is an error or valid, and apply winsorization correctly.
- Choose an imputation method, flatten JSON and XML at the correct grain, and check the quality of ground truth labels.
A revenue total 27 percent too high
This case is fictional but typical. An analyst at Harbor Outfitters, an imaginary outdoor retailer, joins the 2025 orders table to the customer table to report revenue by region. Her dashboard says 5,227,320.00 dollars. The finance ledger for the same year says 4,103,550.00. No price changed and no formula was mistyped. Every line of her code ran without an error.
The gap is 1,123,770 dollars, 27.4 percent of the true figure. Two wrangling defects push the total up: repeated customer keys, and amounts that one source system recorded in cents. A third defect, orders silently dropped by the join, pushes it down and partly hides the other two. This lesson takes the broken result apart one step at a time, and each defect turns out to be a technique on the exam's list. Once the case is closed, the lesson covers the techniques the case did not need: data matching, dates, regular expressions, missing codes, outliers, imputation, flattening nested files and ground truth labels.
Exam objectives: 4.4 Given a scenario, implement common data-wrangling techniques.[1] The objective lists merging and combining (defining keys, data matching with match rates and fuzzy joins, observation tracking, union, intersection, types of joins); cleaning (date and time standardization, regular expressions, deduplication, unit conversion and standardization, missing codes); data errors (idiosyncratic and systematic); ground truth labeling; outliers (identification, winsorization and cut points, error versus valid data point); data flattening of Extensible Markup Language (XML) and JavaScript Object Notation (JSON); and imputation types.
First clue: a join that created rows
The quickest way into a broken join is to count rows before and after it. Here is the analyst's pipeline rerun with a row count and a total printed at each step (fictional output):
orders.shape # (48210, 6)
orders['amount'].sum() # 4511430.0
merged = orders.merge(customers, on='customer_id', how='inner')
merged.shape # (56950, 11)
merged['amount'].sum() # 5227320.0
Two numbers are wrong before anyone opens the data. The raw orders table already sums to 4,511,430, not the ledger figure, so at least one problem lives inside the orders table itself. And the join turned 48,210 orders into 56,950 rows. Joining orders to customers should attach customer attributes to each order. It should never manufacture orders.
The pandas merge() function combines two tables with SQL-style joining, meaning it follows the join rules of Structured Query Language (SQL), the standard language of relational databases.[2] Like any SQL join, it pairs each left row with every right row whose key matches. So if customer C-5521 appears twice in the customer table, each of that customer's orders matches twice and appears twice in the output. The pandas documentation warns that merging on duplicate keys significantly increases the dimensions of the result.[2] At Harbor, a migration between two customer relationship management (CRM) systems had left 1,412 customers with two rows each. Their 9,880 orders came out of the join as 19,760 rows, and their 812,300 dollars of revenue was counted twice.
The row arithmetic exposes a second problem. If duplication were the only defect, the joined table would hold 48,210 + 9,880 = 58,090 rows. It holds 1,140 fewer. Those 1,140 orders, mostly guest checkouts, carry either a null customer_id or a guest ID such as G-20931 that has no partner in the customer table. In SQL a null key never matches anything, not even another null. pandas differs here: merge() pairs null keys with each other, which is one more reason to deal with null keys before any join. Harbor's customer table has no null keys, so both kinds of guest order fall out of the inner join without a word. They were worth 96,410 dollars, which pulled the total down and made the overall error look smaller than it was.
| Effect on the dashboard total | Rows | Dollars |
|---|---|---|
| Raw orders table | 48,210 | 4,511,430 |
| Guest orders dropped by the inner join | -1,140 | -96,410 |
| Orders duplicated by repeated customer keys | +9,880 | +812,300 |
| Dashboard result | 56,950 | 5,227,320 |
The remaining defect, the cents problem inside the raw orders table, comes later. First, the key.
Defining keys: unique at a stated grain
A key is the column, or set of columns, whose value identifies exactly one row at the table's grain. The grain is what one row represents: one customer, one order, one order line, one sensor reading per minute. A primary key is unique and never null within its own table. A foreign key is a column in another table that points to it, as orders.customer_id points to customers.customer_id.
Keys come in a few kinds, and the kind predicts the trouble it causes.
- Natural keys come from the real world: an email address, a tax number, a product barcode. They change (people change email), get reused, and get typed differently in different systems.
- Surrogate keys are assigned by a system, such as an auto-incrementing integer or a globally unique identifier (GUID). They are stable inside one system but mean nothing to another, which is how two merged CRMs can give one person two keys.
- Composite keys use several columns together, such as store_id plus register_id plus receipt_number. Joining on only part of a composite key is a classic way to duplicate rows.
Defining a key for a join means stating three things: which columns, at what grain, and with what expected cardinality. Cardinality is how many rows on each side can share one key value.
| Cardinality | Example | Rows after a left join | pandas check |
|---|---|---|---|
| One-to-one | Customer to loyalty account | Equal to the left table | validate='one_to_one' |
| Many-to-one | Orders to customers | Equal to the left table | validate='many_to_one' |
| One-to-many | Customers to orders | Grows; the result now has order grain | validate='one_to_many' |
| Many-to-many | Orders to promotions joined only on region | Can multiply; usually a key-definition bug | 'many_to_many' runs no check; inspect key counts |
The validate argument tests key uniqueness before the merge runs, which the pandas guide notes can protect against memory overflows and unexpected key duplication.[2] Had the analyst written the join with the cardinality she believed in, pandas would have stopped her:
orders.merge(customers, on='customer_id', how='left',
validate='many_to_one')
# raises MergeError: merge keys are not unique in the right dataset
The documented message for a failed one-to-one check reads "Merge keys are not unique in right dataset; not a one-to-one merge".[2] The many-to-one check fails the same way whenever the right side repeats a key. SQL has no such argument, so run the check yourself: SELECT customer_id, COUNT(*) FROM customers GROUP BY customer_id HAVING COUNT(*) > 1 should return no rows.
Keys also fail when two values look equal to a person but not to a computer. The text "00123" and the integer 123 do not match. Nor do "C-5521" and "c-5521 " with a trailing space. Before joining, cast both key columns to the same type, trim whitespace, and fix the case of text keys.
What matters here: before a join, write down the expected cardinality, test uniqueness on the side that should be unique, and compare row counts afterward. A left join to a table whose key is unique cannot change the number of rows.
Deduplicating the customer table
Deduplication removes repeated records of the same entity. It comes in three strengths.
- Exact duplicates: every column identical, usually from loading the same file twice. Dropping all but one copy loses nothing.
- Key duplicates: same key, different attribute values. Harbor's 1,412 pairs look like this: one row says region "West", the other "West Coast"; one has a phone number and the other does not.
- Near duplicates: different keys for one real customer, such as "Jon Smith" and "John Smith" at the same address. Finding these is data matching, covered below.
Key duplicates need a survivorship rule: a stated policy for which values survive. Typical rules keep the most recently updated row, prefer the source system known to be authoritative for each field, or fill a survivor's blanks from its duplicate. pandas has a direct tool for that last rule: combine_first() updates missing values with non-missing values from the same location in another table.[2]
# keep the newest row per customer, then fill its gaps from the older row
customers = customers.sort_values('updated_at')
newest = customers.drop_duplicates('customer_id', keep='last').set_index('customer_id')
oldest = customers.drop_duplicates('customer_id', keep='first').set_index('customer_id')
clean = newest.combine_first(oldest).reset_index()
Two points about order of operations. Standardize before you deduplicate, or "West" and "West Coast" survive as two values for one region. And when near duplicates with different keys are merged into one, keep a crosswalk table that maps each retired key to its survivor. Orders that point at a retired key can then be re-pointed instead of orphaned.
Types of joins and what each one silently drops
The inner join explains the missing guest orders. PostgreSQL's tutorial makes the same point with weather data: a weather row for Hayward has no matching city, so the join ignores the unmatched rows in the weather table.[3] Every join type is a decision about which unmatched rows to keep. If SQL joins are new to you, the Atlas Data+ course introduces them at a gentler pace.
| Join | Keys kept | Unmatched left rows | Unmatched right rows | Typical use |
|---|---|---|---|---|
| Inner | Intersection of keys | Dropped | Dropped | Only records present in both sources |
| Left outer | All left keys | Kept, right columns null | Dropped | Enrich a primary table without losing any of it |
| Right outer | All right keys | Dropped | Kept, left columns null | A left join with the tables swapped |
| Full outer | Union of keys | Kept | Kept | Reconciling two sources to see what each lacks |
| Cross | Every pairing | Not applicable | Not applicable | Building a grid, such as every store by every day |
| Anti (left) | Left keys with no match | Only these are kept | Dropped | Finding orphans, such as orders with no customer |
The pandas guide maps its options onto SQL the same way: an inner merge uses the intersection of keys from both frames, and an outer merge uses their union.[2] In a left outer join, PostgreSQL substitutes nulls for the right-table columns when a left row has no match.[3] Those nulls are information. A null region after a left join means "no customer record", which is a different fact from "customer whose region is unknown", and no later imputation step should blur the two.
A self join joins a table to itself, for example to compare each employee row with the row of that employee's manager in the same table. It needs a different alias for each copy. When two tables share column names, qualify every column with its table name or alias. pandas resolves name collisions by appending suffixes such as _x and _y, and a column called region_y in a finished report is a sign that nobody checked.
The fix for Harbor is a left join from orders to the deduplicated customers. All 48,210 orders survive. The 1,140 guest orders, whether their customer_id is null or an unmatched guest ID, arrive with null customer attributes, and the report shows them as a separate "No customer record" line instead of losing them.
What matters here: choose the join by asking which unmatched rows the question needs. "Every order" means a left join from orders; "only customers who bought" means an inner join; "what does each system have that the other lacks" means a full outer join.
Second clue: a source that recorded cents
With the join repaired, the report total equals the raw orders total, 4,511,430 dollars. That is still 407,880 above the ledger. Grouping amounts by source system finds the cause quickly:
| source_system | Orders | Median amount | Total amount |
|---|---|---|---|
| web | 39,604 | 58.40 | 3,402,915.00 |
| store_pos | 8,294 | 71.25 | 696,515.00 |
| legacy_pos | 312 | 1,295.00 | 412,000.00 |
The legacy point-of-sale terminals in three outlet stores still write amounts in cents. Their median of 1,295 is suspicious on its own; divided by 100 it becomes 12.95, a plausible price for a clearance item. Dividing all 312 values by 100 turns 412,000.00 into 4,120.00, and the total becomes 3,402,915 + 696,515 + 4,120 = 4,103,550. That matches the ledger to the cent.
Unit conversion and standardization means putting every value of a variable into one unit and one representation before it is compared, summed or modeled. The conversion is keyed to the cause, not guessed row by row: here, every legacy_pos row and only those rows. Common cases:
- Scale factors: cents to dollars, grams to kilograms, pounds to kilograms (1 lb = 0.45359237 kg exactly).
- Offsets: Celsius to Fahrenheit is F = C × 9/5 + 32. Multiplying alone is wrong. Because of the offset, a temperature difference of 10 Celsius degrees converts to 18 Fahrenheit degrees, not to 50.
- Time-varying rates: currency is converted at the rate for the transaction date, and the rate source is recorded.
- Representations: "CA", "Calif." and "California" become one code; "Y", "yes", "1" and "TRUE" become one Boolean value.
In this objective, standardization means consistent units and codes. Do not confuse it with z-score standardization, the feature-scaling step that subtracts the mean and divides by the standard deviation before modeling. Both are called standardization, but only z-scoring deliberately removes the original unit.
Idiosyncratic and systematic errors
The cents bug is a systematic error: one cause, applied the same way to a whole group of records, pushing every one of them in the same direction. The duplicate customers were systematic too, produced by one migration. An idiosyncratic error is a one-off: a cashier keys 1,500 instead of 15.00 once, or a respondent types a birth year of 1898 instead of 1989.
| Feature | Idiosyncratic error | Systematic error |
|---|---|---|
| Cause | An individual slip, random noise, one bad record | A process: a device, form default, software version, unit convention or time zone |
| Pattern | Scattered, with no shared direction | Concentrated in a group, with a consistent direction or size |
| Effect on averages | Adds noise that partly cancels in large samples | Adds bias that never cancels, however large the sample |
| How you find it | Range checks, validation rules, outlier screens | Group by source, device, date or version and compare distributions |
| How you fix it | Correct or set to missing, record by record | Apply one rule to every affected record and fix the upstream cause |
The distinction decides the fix. Treat a systematic error as a scatter of outliers and you will remove a few extreme rows while leaving hundreds of slightly wrong ones. A temperature sensor that reads 1.8 degrees high after a firmware update produces no outliers at all, only a shifted distribution. It is found by comparing that sensor with its neighbors, not by an outlier test.
What matters here: when an error has a shared cause, find the group it lives in and correct the whole group by rule; when it has no shared cause, handle the records one at a time.
Observation tracking: the log that closed the case
Observation tracking means being able to say, for every record, where it came from, what happened to it and where it went. In practice it has four parts: a stable record identifier carried through every step; row counts and control totals logged after each step; a match-status flag after each join; and a source column on anything combined from several inputs. pandas adds the match flag for you: merge(..., indicator=True) creates a column marking each row left_only, right_only or both.
Harbor's repaired pipeline, logged step by step:
| Step | Rows | Total amount | Note |
|---|---|---|---|
| Load orders | 48,210 | 4,511,430.00 | Raw extract |
| Convert legacy_pos cents to dollars | 48,210 | 4,103,550.00 | 312 rows changed |
| Deduplicate customers (separate table) | 1,412 rows removed | Not applicable | Survivor rule: newest row, gaps filled |
| Left join orders to customers, validated many-to-one | 48,210 | 4,103,550.00 | Row count unchanged, as required |
| Match status: both | 47,070 | 4,007,140.00 | Reported by region |
| Match status: left_only | 1,140 | 96,410.00 | Null or unmatched guest IDs; reported as "No customer record" |
The last two rows add back to the reconciled total, and that total equals the ledger. Reconciling to an independent control figure is the strongest check available. A log like this one, run on day one, would have caught all three defects before the dashboard shipped.
Union and intersection: combining rows
Joins place columns side by side. Union and intersection work on rows. A union stacks tables that share the same columns, such as twelve monthly extracts. In SQL, UNION removes duplicate rows from the result and UNION ALL keeps every row; pandas concat() behaves like UNION ALL until you call drop_duplicates(). An intersection keeps only rows present in both inputs (SQL INTERSECT), and EXCEPT keeps rows of the first input that are absent from the second.
A worked example shows why the choice matters. Harbor's March extract runs from 1 to 31 March. The April extract was pulled with a start date of 31 March, so both contain the 412 orders placed on 31 March. Stacked with UNION ALL, those orders count twice. UNION removes them only if the copies are identical in every column. If each extract carries its own extracted_at timestamp, the copies differ, UNION keeps both, and the double count survives. The reliable fix is to deduplicate on the business key, order_id, after stacking.
Before any union, align the schemas: the same column names, types and units. A table in kilograms stacked under one in pounds produces a column the database accepts and nobody can use. Add a source column as you stack so that observation tracking survives the union.
Do not confuse a row union with the union of keys in a full outer join. A full outer join keeps every key value from both tables but still sets their columns side by side. A row union keeps the columns fixed and adds rows.
Data matching: match rates and fuzzy joins
Harbor's 1,140 guest orders have no usable customer_id, since each holds either a null or a guest ID with no partner, but most carry a name, an email address and a postal code. Linking records that describe the same entity without a shared clean key is data matching, also called record linkage or entity resolution. It runs in three stages: standardize the fields, compare candidate pairs, and decide which pairs are matches.
A fuzzy join joins on similarity instead of equality. Each candidate pair gets a score, and pairs above a chosen threshold count as matches. Common scores:
- Levenshtein distance: the fewest single-character insertions, deletions or substitutions that turn one string into the other. "Jon Smith" to "John Smith" is 1.
- Jaro-Winkler similarity: a score from 0 to 1 for short strings such as names. It rewards shared characters and gives extra weight to a shared prefix.
- Token-based similarity: compares sets of words, so "Smith, John" and "John Smith" score as identical.
Comparing every pair is expensive. 1,140 guests against 64,000 customers is about 73 million comparisons, and two files of a million records each would need a trillion. Blocking limits comparisons to pairs that share a cheap attribute, such as postal code or the first three letters of a surname. A dirty blocking key, such as a mistyped postal code, hides true matches, so many pipelines run two or three blocking passes on different attributes.
The match rate is the share of eligible records that found a partner:
match rate = matched records / eligible records
Always state the denominator. Harbor counts a guest order as eligible if it has at least a name and a postal code: 1,000 of the 1,140. Here is a fictional matching run:
| Method | Matched | Match rate | Correct in a reviewed sample of newly added matches |
|---|---|---|---|
| Exact join on raw email | 540 | 54.0% | Not reviewed |
| Exact join after lowercasing and trimming email | 690 | 69.0% | 100 of 100 |
| Add fuzzy name match, Jaro-Winkler at least 0.92, same postal code | 810 | 81.0% | 94 of 100 |
| Lower the threshold to 0.80 | 905 | 90.5% | 41 of 95 |
Read the last two rows together. Lowering the threshold raised the match rate by 9.5 points, yet only 41 of the 95 newly added pairs were correct. More than half of the new links attach one person's orders to someone else. A match rate counts links. It does not measure whether they are right. That second question is precision, the quantity you met with confusion matrices: of the pairs the method called matches, how many truly are. Missed true matches play the part of false negatives. Raising the threshold trades recall for precision, and the right setting depends on what each error costs. Merging two people's purchase histories for a marketing list is a nuisance; merging two patients' medical records is dangerous.
Report match rates by segment too. An overall 81 percent can hide 95 percent for web guests and 40 percent for phone orders, and the unmatched group is rarely a random sample of the whole.
One relative of the fuzzy join has its own tool. When the key is a time, pandas merge_asof() matches on the nearest key instead of an exact one, for example attaching to each trade the most recent quote at or before it.[2] That is approximate matching on an ordered key, not on string similarity.
What matters here: a fuzzy join is a classifier of record pairs. Judge it by a reviewed sample of its matches, not by its match rate alone.
Date and time standardization
Dates arrive as text in many conventions, and the convention is rarely written down. The usual target is ISO 8601, a standard from the International Organization for Standardization (ISO): year, month and day in that order (2025-04-03), a T before the time, and either Z for Coordinated Universal Time (UTC) or an explicit offset such as -04:00. Strings in this form sort correctly as text and cannot be misread across countries.
Standardizing a timestamp means fixing three things separately: the format, the time zone and the precision. The table shows each problem with a fictional value.
| Raw value | Where it came from | What is wrong | Standardized |
|---|---|---|---|
| 2025-04-03T14:05:00Z | Web application programming interface (API) | Nothing: ISO 8601 in UTC | 2025-04-03T14:05:00Z |
| 1743689100 | Event log | Unix epoch seconds, unreadable to people | 2025-04-03T14:05:00Z |
| 03/04/2025 10:05 | Boston store, US convention | Month-day order and time zone are implicit | 2025-03-04T15:05:00Z (Eastern Standard Time, UTC-5) |
| 4 Apr 2025 | Web form | A date with no time; not an instant | 2025-04-04, kept as a date |
| 2025-11-02 01:30 | Boston store | Occurs twice, because clocks fell back at 02:00 that night | Unresolvable without an offset or a stated rule |
Three rules follow. First, never let a parser guess day-month order. "03/04/2025" is 4 March in the United States and 3 April in much of Europe, and a guessing parser can read "13/04/2025" one way and "03/04/2025" the other way within the same column. Pass the format explicitly, for example pd.to_datetime(s, format='%m/%d/%Y %H:%M'), so a string that does not fit raises an error instead of being silently misread. Second, convert instants to UTC for storage and arithmetic, and keep the original zone or offset in its own column when local time matters, as it does for "orders placed after 6 p.m. local time". Third, keep dates as dates. A birth date or billing date shifted into UTC can slide to the previous day.
A value that cannot be parsed should become missing, not a default; pandas marks a missing datetime as NaT, "not a time". Watch for placeholder dates such as 1900-01-01 or 1970-01-01 (the Unix epoch, which is what a zero timestamp becomes). They are missing codes in disguise.
Regular expressions for pattern-based cleaning
A regular expression (RegEX, or regex) is a pattern that describes a set of strings. Python's documentation calls regex syntax a tiny, highly specialized programming language embedded inside Python.[4] In cleaning it does three jobs: testing whether a value fits a format, extracting part of a value, and replacing or removing parts of it.
Most characters match themselves. A few metacharacters carry meaning instead.
| Element | Meaning | Example |
|---|---|---|
\d, \w, \s | A digit; a word character; whitespace | \d\d matches "42" |
\D | Any character that is not a digit | Matches "(", ")", "-" and spaces in a phone number |
[A-Z] | Any one character from a set or range | Matches "Q" but not "q" |
*, +, ? | Zero or more; one or more; zero or one of the item before | colou?r matches "color" and "colour" |
{m}, {m,n} | Exactly m; between m and n of the item before | \d{5} matches five digits |
^, $ | Start and end of the string | Stop "123456" passing a five-digit test |
( ) | A group you can extract or refer back to | (\d{4})-(\d{2}) captures year and month |
| | Either alternative | kg|kilograms? |
For formats, the brace quantifier does most of the work: {m} matches the preceding item exactly m times.[4] Without anchors, \d{5} also finds five digits inside "123456"; with them, ^\d{5}$ accepts only a value that is exactly five digits.
A worked example. A phone column holds "(617) 555-0142", "617.555.0142" and "+1 617 555 0142". Step one: replace every non-digit, \D, with nothing. The values become "6175550142", "6175550142" and "16175550142". Step two: if a value has 11 digits and starts with 1, drop the 1, which is the North American country code. Step three: validate with ^\d{10}$, and flag anything that still fails instead of forcing it. In pandas the first step is s.str.replace(r'\D', '', regex=True); the r before the quote makes a Python raw string, which keeps the backslash intact.
Now change one input. The column also holds "617-555-0142 ext 23". Stripping non-digits gives "617555014223", twelve digits, which fails validation. That failure is useful: without the check, a wrong number would have entered the table. The fix is to split off the extension first, for example by matching \s*ext\.?\s*(\d+)$, storing the captured digits in their own column, and then cleaning what remains.
Two limits. A pattern checks form, not truth: ^\d{4}-\d{2}-\d{2}$ happily accepts 2025-02-30, so date validity needs a date parser. And regex is the wrong tool for fixed text. Python's documentation warns that sometimes using the re module is a mistake, because plain string methods are usually much faster for jobs such as replacing one fixed string with another.[4]
Missing codes: when -999 is a number to the computer
Missing values rarely arrive as empty cells. They arrive as missing codes: sentinel values that a person or a system used to mean "no value here". Common ones are -999, 9999, 0, 1900-01-01, "N/A", "NULL", "unknown", "?" and a single space. Survey files often use several codes with different meanings, for example a fictional codebook in which -7 means refused, -8 means don't know and -9 means not applicable.
Left in place, a numeric code is just a number. Take five ages: 34, 41, -999, 29, 38. With the code included, the mean is (34 + 41 - 999 + 29 + 38) / 5 = -857 / 5 = -171.4 years. With the code recoded to missing, the mean of the four real ages is 142 / 4 = 35.5. Nothing crashed, so nothing warned anyone.
The procedure: read the codebook or ask the data owner; list every code in every column; recode each to a true missing value; and keep the reason in a separate column when codes differ in meaning. In pandas, read_csv(..., na_values=[-999, 'N/A']) recodes at load time. pandas itself uses different sentinel values for missing data depending on the column's type: NaN (short for "not a number") for NumPy types, NaT for datetimes and pd.NA for its nullable types.[5] One side effect is easy to miss. The pandas guide warns that with NumPy types, the original data type is coerced to float64 or object when a missing value enters the column.[5] For an integer column that means float64: customer IDs can quietly become 5521.0, and a later join against text IDs fails.
Two more traps. In element-wise arithmetic, missing values propagate, so a + b is missing wherever either a or b is missing.[5] Aggregations behave the other way: sum() and mean() skip missing values by default (skipna=True), so a column total quietly ignores its gaps and nothing tells you how many rows were left out. Count the missing values before you trust a total. And JSON cannot write NaN at all: the standard's number grammar does not permit NaN or Infinity.[6] A pipeline that exports NaN to JSON therefore writes null, a string such as "NaN", or invalid JSON that a stricter reader rejects, depending on the library.
Keep the reason a value is missing, because the reason can be informative. If high earners refuse the income question more often than others, the refusals are missing not at random (MNAR): whether the value is missing depends on the value itself. A "refused" flag then carries signal that any filled-in number would erase.
What matters here: a missing code is a value that means "no value". Find every code from the documentation, recode each to a real missing value, and keep why it was missing.
Outliers: identify first, then decide
The NIST/SEMATECH e-Handbook of Statistical Methods defines an outlier as an observation that lies an abnormal distance from other values in a random sample, and notes that this leaves the meaning of "abnormal" to the analyst.[7] Identification turns that judgment into a rule. Two rules cover most exam scenarios.
Box-plot fences. Compute the lower quartile Q1, the upper quartile Q3 and the interquartile range IQR = Q3 - Q1. The inner fences sit at Q1 - 1.5 × IQR and Q3 + 1.5 × IQR, and the outer fences at 3 × IQR beyond the quartiles. A point beyond an inner fence is a mild outlier; a point beyond an outer fence is an extreme outlier. The handbook's worked example has 90 observations with Q1 = 429.75 and Q3 = 742.25, so IQR = 312.5.[7] The upper inner fence is 742.25 + 468.75 = 1211.0, and the upper outer fence is 742.25 + 937.5 = 1679.75.[7] The largest value, 1441, passes the inner fence but not the outer one, so it is a mild outlier.[7]
Change one input and the label flips. Had the largest value been 1700, it would lie beyond 1679.75 and count as an extreme outlier. The quartiles would not move at all, because they depend on the middle of the data, not the tail. That is why fences resist the very points they are looking for.
Z-scores and modified z-scores. The z-score is z = (x - mean) / s, the distance from the mean in sample standard deviations s. The habit of flagging |z| > 3 fails in small samples, because in a sample of n values the largest possible |z| is (n - 1) divided by the square root of n.[8] The outlier inflates both the mean and s, so it helps hide itself. The handbook cites Iglewicz and Hoaglin's modified z-score, which uses the median and the median absolute deviation (MAD) instead:
M = 0.6745 × (x - median) / MAD
Values with |M| greater than 3.5 are labeled potential outliers.[8] Here it is on seven fictional delivery times, in minutes: 22, 23, 24, 25, 26, 27, 95.
| Quantity | Working | Value |
|---|---|---|
| Mean | 242 / 7 | 34.57 |
| Sample standard deviation s | Square root of (4277.7 / 6) | 26.70 |
| z for 95 | (95 - 34.57) / 26.70 | 2.26 |
| Largest possible |z| when n = 7 | 6 / square root of 7 | 2.27 |
| Median | Middle of the seven sorted values | 25 |
| MAD | Median of the absolute deviations 3, 2, 1, 0, 1, 2, 70 | 2 |
| M for 95 | 0.6745 × 70 / 2 | 23.6 |
The |z| > 3 rule cannot flag anything in a sample of seven, because no value can exceed 2.27. The modified z-score flags 95 at 23.6, almost seven times the cutoff, while the other six values have |M| no larger than 0.6745 × 3 / 2 = 1.01.
Formal outlier tests have their own failure modes. Masking happens when a test looks for too few outliers: a second outlier inflates the statistic so much that neither is declared.[8] Swamping is the reverse: testing for too many can declare a good point an outlier along with a bad one. The handbook therefore pairs formal tests with plots.
Error or valid data point?
Flagging is not deleting. An outlier may indicate bad data, such as a value coded incorrectly or an experiment that was not run correctly.[8] When a value is shown to be erroneous, the handbook's advice is that it should be deleted from the analysis or, where possible, corrected.[8] When it cannot be shown to be an error, it may be real and important: the handbook asks that outliers be investigated carefully, because they often hold valuable information about the process or about how the data were collected.[7]
| Evidence about the value | Verdict | Action |
|---|---|---|
| Physically or logically impossible: age 212, negative quantity on a sale, delivery before order | Error | Correct from the source if possible, otherwise set to missing |
| Explained by a known systematic cause, such as the legacy terminals' cents | Error (systematic) | Fix by rule for the whole affected group |
| Possible but rare, and verified: a 40,000-dollar corporate order | Valid | Keep; use robust methods or winsorize for modeling |
| Possible, and cannot be verified | Unknown | Keep and label it; report results with and without it |
Notice that the outlier test answered none of these questions. It only said where to look. The verdict comes from evidence about how the value was produced.
Winsorization and cut points
Winsorization keeps every row but replaces values beyond chosen cut points with the cut point itself. Trimming removes those rows instead. Cut points are usually percentiles, such as the 1st and 99th, or fence values, or a domain limit such as a maximum plausible human age.
A worked example with ten fictional order values: 12, 15, 18, 20, 22, 25, 27, 30, 35, 410. Winsorize the single lowest and single highest value to their nearest neighbors (10 percent at each end), and compare with trimming the same two values.
| Treatment | Values | n | Mean | Median |
|---|---|---|---|---|
| None | 12, 15, 18, 20, 22, 25, 27, 30, 35, 410 | 10 | 61.4 | 23.5 |
| Winsorized | 15, 15, 18, 20, 22, 25, 27, 30, 35, 35 | 10 | 24.2 | 23.5 |
| Trimmed | 15, 18, 20, 22, 25, 27, 30, 35 | 8 | 24.0 | 23.5 |
The median never moves. The mean drops from 61.4 to 24.2 with winsorizing, and winsorizing keeps n at 10, so every row still contributes to the model.
Now the flip. Suppose the 410 is a verified bulk order from a school. For a model that predicts typical basket size, winsorizing is reasonable: one school order should not drag a linear model's coefficients. For the revenue report, winsorizing would understate this one order by 375 dollars, which is simply a wrong total. Winsorization is a modeling choice, never an accounting one.
Choose cut points on the training data, store them, and apply them unchanged to validation, test and production data. Computing the 99th percentile on the full data set before splitting leaks information from the test set into training. In production, the stored cut point doubles as a drift alarm: if many new values pile up at the cap, the population has moved.
What matters here: identify outliers with a rule the outliers cannot distort, decide error or valid from evidence about how the value arose, and winsorize only to limit a valid value's influence on a model.
Imputation types
Imputation replaces missing values with estimates so that the rows can be used. Which estimate is defensible depends on why the values are missing. Data are missing completely at random (MCAR) when missingness is unrelated to anything, such as forms lost at random in the post. They are missing at random (MAR) when missingness depends only on variables you observe, such as older customers skipping an optional web field when age is recorded. They are missing not at random (MNAR) when missingness depends on the missing value itself.
| Type | How it fills | When it fits | What goes wrong |
|---|---|---|---|
| Deletion (listwise) | Drops rows with any missing value | Few gaps, plausibly MCAR | Loses rows; biased if not MCAR |
| Mean, median or mode | One summary value per column | Quick baseline; median for skewed data | Shrinks variance and weakens correlations |
| Constant plus indicator | A fixed value and a was_missing flag | Tree models; MNAR where missingness is signal | The constant misleads a linear model if the flag is dropped |
| Forward fill (last observation carried forward) | The previous value in time order | Slowly changing states, such as a price list | Stale values; backward fill leaks the future |
| Interpolation | Values between known neighbors: linear, time-weighted, spline | Regular, smooth time series | Invents smoothness across real jumps |
| Regression or model-based | Predicts the value from other columns | MAR with strong predictors | Single predictions understate uncertainty |
| k-nearest neighbors (KNN) | Averages the k most similar complete rows | MAR with local structure | Needs scaled features; slow on large data |
| Multiple imputation | Several plausible completed data sets, results pooled | Inference that needs honest standard errors | More computation and more care in reporting |
A worked example shows why mean imputation is a weak default. A column holds 10, 20, 30 and two missing values. The observed mean is 20, and the observed sample variance is ((-10)2 + 02 + 102) / 2 = 100. Fill both gaps with 20 and the variance becomes (100 + 0 + 100 + 0 + 0) / 4 = 50. The column now looks half as variable as it is. Any correlation with another column also weakens, because the filled rows sit at the mean whatever the other column says. Regression and KNN imputation preserve relationships better, but each fill is still a single predicted value with no noise. Multiple imputation addresses that by drawing several plausible values and pooling the results.
For time series, pandas offers several interpolation methods, and its guide notes that the appropriate method depends on the data type.[5] The data's behavior matters as well. Linear interpolation suits a temperature log sampled every minute. It is wrong across a step change such as a price increase, where forward fill reflects what actually happened.
Three rules apply to every method. Fit the imputer on training data and apply the stored values to validation and test data, exactly as with winsorization cut points. Add a was_missing indicator when missingness might carry signal, as it does under MNAR. And never impute a key, a label, or a null that means "no match" after a left join: those nulls record facts, not gaps.
Data flattening: JSON and XML
APIs and logs deliver nested records; most models and SQL tables want flat rows. Data flattening converts a nested structure into a table. JSON's current specification is Request for Comments (RFC) 8259, an Internet Standard (STD 90) published in December 2017.[6] JSON nests in two ways: objects, which hold name and value pairs inside braces, and arrays, which hold ordered lists inside square brackets. The two flatten differently. Here is one fictional order from an API:
{
"order_id": "A-1001",
"placed": "2025-04-03T14:05:00Z",
"shipping_fee": 8.00,
"customer": {"id": "C-5521", "region": "West"},
"items": [
{"sku": "TNT-2", "qty": 1, "price": 189.00},
{"sku": "STK-9", "qty": 2, "price": 24.50}
]
}
A nested object flattens into columns: customer becomes customer.id and customer.region. An array flattens into rows: two items become two rows. In pandas:
flat = pd.json_normalize(orders, record_path='items',
meta=['order_id', 'placed', 'shipping_fee',
['customer', 'id'], ['customer', 'region']])
| sku | qty | price | order_id | placed | shipping_fee | customer.id | customer.region |
|---|---|---|---|---|---|---|---|
| TNT-2 | 1 | 189.00 | A-1001 | 2025-04-03T14:05:00Z | 8.00 | C-5521 | West |
| STK-9 | 2 | 24.50 | A-1001 | 2025-04-03T14:05:00Z | 8.00 | C-5521 | West |
The table shows the trap. The order's 8.00 shipping fee now appears on both rows. The grain changed from one row per order to one row per order line, and summing shipping_fee at this grain gives 16.00. This is the same mechanism as Harbor's duplicate customers: a one-to-many expansion repeats the parent's values. Sum parent-level fields before exploding the array, or from a separate order-level table, and record the grain of every flattened table.
Three other JSON details cause trouble. Many parsers read every number as a double-precision float, so a long numeric ID can lose its final digits; read IDs as strings. A field can be absent, null or an empty string, three states to map deliberately. And, as noted above, NaN cannot be written at all.
The same order as XML:
<order id="A-1001" placed="2025-04-03T14:05:00Z" shipping_fee="8.00">
<customer id="C-5521" region="West"/>
<item sku="TNT-2" qty="1" price="189.00"/>
<item sku="STK-9" qty="2" price="24.50"/>
</order>
XML adds its own wrinkles. Data can sit in attributes, like sku="TNT-2", or in child elements, and a flattener must read both. Every value is text, so types must be cast. Repeating elements, like the two item elements, become rows, just as JSON arrays do. Namespaces, prefixes such as ns:item declared at the top of a document, must be supplied to the query or nothing matches. A query language called XPath selects which elements to flatten: pandas read_xml(path, xpath='//item') returns one row per item element with its attributes as columns. The parent order's attributes are not included, so they must be parsed at the order level and joined back on order_id, which is one more key to define and validate.
What matters here: flattening objects adds columns, flattening arrays adds rows, and adding rows changes the grain. Know the grain of the flat table before you sum anything in it.
Ground truth labeling
Ground truth is the set of target values treated as correct when a supervised model is trained and evaluated. Every metric built from a confusion matrix assumes it. Labels come from a few places.
- Observed outcomes: the customer did or did not churn; the loan did or did not default. Accurate but slow, so the newest records may not have a label yet.
- Human annotation: people read tickets, draw boxes on images or tag sentences, following written guidelines.
- Expert adjudication: a specialist settles the cases where annotators disagree.
- Weak or programmatic labels: rules such as "a ticket containing the word refund is a complaint". Cheap, fast and noisy.
Labeling belongs in a wrangling lesson because labels suffer every defect in this lesson: duplicates, inconsistent codes ("Complaint", "complaint", "COMPLAINT"), systematic errors (one annotator who marks almost everything negative) and idiosyncratic slips. The usual controls are written guidelines with examples of hard cases, a share of items labeled independently by two people, gold items with known labels mixed into the queue to check each annotator, and an agreement statistic.
Cohen's kappa measures agreement between two annotators beyond what chance would produce: kappa = (po - pe) / (1 - pe). Here po is the observed share of items on which they agree, and pe is the agreement expected if each labeled at random at their own rates. A worked example: two annotators label 200 support tickets and agree on 170, so po = 0.85. Annotator A calls 40 percent of tickets complaints and B calls 50 percent, so pe = 0.40 × 0.50 + 0.60 × 0.50 = 0.50. Kappa is (0.85 - 0.50) / (1 - 0.50) = 0.70.
Change the inputs: raw agreement rises to 90 percent, but complaints are rare, and each annotator calls only 10 percent of tickets complaints. Then pe = 0.10 × 0.10 + 0.90 × 0.90 = 0.82, and kappa = (0.90 - 0.82) / (1 - 0.82) = 0.44. Higher raw agreement, lower kappa. With a rare class, two annotators who mostly say "no" agree by default, and kappa removes that free agreement.
Two timing rules protect labels from leakage. Define the label window precisely, for example "churned within 90 days after the snapshot date", and build features only from data available on the snapshot date. And exclude records whose window has not closed yet, rather than labeling them negative because no outcome has arrived.
Reading the scenario: exam cues
| The question stem says | It points to | Often confused with |
|---|---|---|
| Row count rose after joining a lookup table | Duplicate keys; define keys and deduplicate, validate cardinality | Unmatched keys, which add nulls but never rows |
| Keep every record from the main table even without a match | Left outer join | Full outer join, which also keeps the other table's orphans |
| Only records present in both systems | Inner join (intersection of keys) | Union |
| Stack monthly extracts with identical columns | Union (UNION ALL or concat, then deduplicate on the business key) | Join |
| Names spelled differently across systems, no shared ID | Fuzzy join (data matching) | merge_asof, which matches nearest times, not similar strings |
| What share of records found a partner | Match rate | Precision of the matches |
| Show where each row went and how many were lost | Observation tracking | Deduplication |
| -999, 9999 or "N/A" in a numeric field | Missing codes | Outliers |
| Mixed pounds and kilograms, or cents and dollars | Unit conversion and standardization | Z-score standardization |
| 03/04/2025 read differently by region; time zones | Date and time standardization | Regular expressions alone |
| Extract or validate a pattern such as a postal code | Regular expressions | Fuzzy matching |
| Every reading from one device is off by the same amount | Systematic error | Idiosyncratic error |
| One random typo in one record | Idiosyncratic error | Systematic error |
| Cap extremes at percentile cut points but keep the rows | Winsorization | Trimming |
| A value that is physically impossible | Error data point: correct or set to missing | Valid but extreme point |
| Nested API response to one table | Data flattening (JSON) | Deduplication |
| Annotators create labels; measure their agreement | Ground truth labeling (kappa) | Raw percent agreement |
| Fill gaps using similar rows | KNN imputation | Mean imputation |
Common misconceptions
- "A left join always returns as many rows as the left table." Only when the right table's key is unique. Each duplicate right key multiplies its matching left rows.
- "A higher match rate means better matching." A match rate counts links, not correct links. Lowering a fuzzy threshold raises the rate and can add mostly false matches.
- "Outliers are errors, so delete them." An outlier is only a flag. Delete or correct a value when evidence shows it is an error; otherwise keep it and, for modeling, limit its influence.
- "Winsorizing and trimming are the same." Winsorizing replaces extreme values with the cut point and keeps the rows; trimming removes the rows.
- "An absolute z-score above 3 identifies outliers in any data set." In small samples |z| cannot reach 3 at all, and an outlier inflates the mean and standard deviation that z depends on. The modified z-score uses the median and MAD instead.
- "Missing data shows up as blank cells, and a total will warn me about it." It often arrives as codes such as -999, 9999 or 1900-01-01, which software treats as real values until you recode them, and pandas sums skip true missing values silently.
Summing up
- A join pairs each row with every matching row on the other side, so a repeated key on the side meant to be unique multiplies rows. A left join to a unique key never changes the row count.
- An inner join keeps the intersection of keys, a full outer join the union, and a left join keeps all left rows with nulls for missing matches. In SQL a null key never matches. A row union stacks rows, and SQL UNION removes only rows identical in every column.
- Match rate = matched records / eligible records. A fuzzy join's quality is judged by a reviewed sample of its matches, and lowering the threshold raises the match rate while admitting false matches.
- Systematic errors share a cause and a direction, bias results however large the sample, and are fixed by one rule for the affected group. Idiosyncratic errors are one-offs handled record by record.
- Missing codes such as -999 must be recoded to missing with the reason kept. NaN in a NumPy integer column turns it into float64, element-wise arithmetic propagates missing values while sum() skips them, and JSON cannot represent NaN.
- Box-plot fences at 1.5 × IQR beyond the quartiles mark mild outliers and 3 × IQR extreme ones. The modified z-score, 0.6745 × (x - median) / MAD, flags |M| above 3.5, while ordinary |z| can never exceed (n - 1) divided by the square root of n.
- Winsorization caps values at cut points chosen on training data and keeps the rows. It suits model features, not accounting totals.
- Store instants in UTC in ISO 8601 and parse with an explicit format. Never let a parser guess day-month order.
- Flattening a nested array changes the grain, so parent-level fields repeat and must not be summed at the child grain.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- pandas (NumFOCUS). (n.d.). Merge, join, concatenate and compare. pandas.pydata.org
- PostgreSQL Global Development Group. (n.d.). 2.6. Joins Between Tables. postgresql.org
- A.M. Kuchling. (n.d.). Regular expression HOWTO. Python Software Foundation. docs.python.org
- pandas (NumFOCUS). (n.d.). Working with missing data. pandas.pydata.org
- T. Bray, Ed. (2017). The JavaScript Object Notation (JSON) Data Interchange Format (RFC 8259). IETF / RFC Editor. rfc-editor.org
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: What are outliers in the data? itl.nist.gov
- NIST. (n.d.). NIST/SEMATECH e-Handbook of Statistical Methods: Detection of Outliers. itl.nist.gov
- Key terms
- Join key
- The column or set of columns used to pair rows from two tables. On the side expected to be unique, each key value must identify exactly one row at that table's grain.
- Match rate
- The share of eligible records that a matching process linked to a partner record, calculated as matched records divided by eligible records. It counts links, not whether the links are correct.
- Fuzzy join
- A join that pairs records whose key values are similar rather than identical, using a similarity score such as Levenshtein distance or Jaro-Winkler and a chosen threshold.
- Observation tracking
- Keeping a record of every row's origin and fate through a pipeline, using stable record IDs, row counts and control totals at each step, match-status flags and source columns.
- Missing code
- A sentinel value such as -999, 9999, N/A or 1900-01-01 that stands for an absent value. It must be recoded to a true missing value before analysis, ideally keeping the reason.
- Systematic error
- An error with a shared cause, such as a miscalibrated device or a unit mismatch in one source, that shifts a group of records in a consistent direction and does not average out.
- Idiosyncratic error
- A one-off error with no shared cause, such as a single typo or transposed digits, that affects individual records in no consistent direction.
- Winsorization
- Replacing values beyond chosen cut points, such as the 1st and 99th percentiles of the training data, with the cut point values, so that extreme values lose influence while every row is kept.
- Data flattening
- Converting nested data such as JSON objects and arrays or XML elements into a flat table. Nested objects become columns, and arrays or repeating elements become rows, which changes the table's grain.
- Ground truth
- The target values treated as correct for training and evaluating a supervised model, obtained from observed outcomes, human annotation, expert adjudication or programmatic rules.
Best Practices Across the Data Science Life Cycle
- Use CRISP-DM to find which project phase failed, and DAMA-DMBOK to find which organization-wide data responsibility nobody held.
- Version code, data, hyperparameters and models together so that any prediction can be traced back and reproduced.
- Choose and apply the right documentation, clean code or unit testing practice for a given data science scenario.
- Plan API-based data retrieval and model endpoints, and decide whether a dependency's license permits the intended use.
A churn score that nobody could explain
At 09:14 on a Monday, an account manager at a regional telecom sends the analytics team one question: why did customer 48211's churn score jump from 0.12 on Friday to 0.81 this morning? The company and the numbers are fictional, but each failure in this story happens in real teams. The customer did nothing unusual over the weekend. The data scientist who owns the model opens the shared drive. She finds three notebooks, churn_final.ipynb, churn_final_v2.ipynb and churn_final_v2_REAL.ipynb, and one file in the production folder called model.pkl. Nobody can say which notebook produced that file, which extract of the customer table it learned from, or which settings it used.
It takes two days to rebuild the story. A colleague retrained the model on Sunday with a fresh extract. The upstream customer system had recoded the contract-type column from letters to numbers. A hyperparameter had been changed in a notebook cell and never recorded anywhere else. The scoring service loaded whatever model.pkl sat in the folder, so the new model went live as soon as someone copied it there. And while the pipeline was being reviewed, the legal team found a library whose license the company does not allow in its products.
The gradient boosting model itself was fine. Every failure was a failure of practice. There was no shared process, no versioning, no documentation, no tests, no controlled way to serve the model and no license check. This lesson takes the incident apart one failure at a time. Each failure gets the fix the exam names, and the lesson ends with a table that turns scenario wording into answers.
Exam objectives: CompTIA DataX DY0-001 objective 4.5, "Given a scenario, implement best practices throughout the data science life cycle." Its bullets are: data science workflow models (CRISP-DM and DAMA); version control of code, data, hyperparameters and models; the integrated development environment (IDE); dependency licensing; access via application programming interface (API), covering data access and retrieval and model endpoints or model services; process documentation (Markdown, docstrings, appropriate code commenting, reference data and documentation); clean code methods; and unit test writing.[1]
CRISP-DM: finding the failure in the project life cycle
A post-mortem starts by asking where in the work things went wrong. A workflow model gives the team a shared map for that conversation. The exam names two models, and they answer different questions.
The Cross-industry standard process for data mining (CRISP-DM) describes how one analytics project moves from a business question to something in use. IBM's guide calls CRISP-DM "an industry-proven way to guide your data mining efforts."[2] As a methodology, it describes the typical phases of a project and the tasks in each phase.[2] As a process model, it gives an overview of the whole data mining life cycle.[2] That process model has six phases, with arrows between them marking the most important and most frequent dependencies.[2] The table lists the phases and shows where the churn incident touched each one.
| Phase | Question it answers | Typical outputs | What went wrong in the churn incident |
|---|---|---|---|
| 1. Business understanding | What decision will this support, and how will we judge success? | Objectives, success criteria, project plan | Nobody had decided who answers questions about score changes, or how |
| 2. Data understanding | What data exists, and how good is it? | Data collection, description, exploration and quality reports | The Sunday extract was never profiled, so the recoded column went unnoticed |
| 3. Data preparation | How do raw tables become a modeling table? | Cleaned, joined and derived features; a data cleaning report | The contract-type encoder quietly mapped unfamiliar codes to a default |
| 4. Modeling | Which technique and settings fit the problem? | Trained models, parameter settings, model descriptions | A hyperparameter changed in a notebook cell and was never recorded with the run |
| 5. Evaluation | Does the model meet the business goal, and was the process sound? | Assessment against success criteria, review, go or no-go decision | The Sunday model went live without anyone evaluating it |
| 6. Deployment | How are the results put to use, monitored and maintained? | Deployment plan, monitoring and maintenance plan, final report | Copying a file into a folder was the only deployment process |
People tend to forget the arrows. IBM's guide says the order of the phases is not strict, and most projects move back and forth between phases as needed.[2] If evaluation shows the model answers the wrong business question, you go back to business understanding, not forward to deployment. If data preparation exposes a quality problem, you go back to data understanding. In the incident nobody went back at all. A new extract went straight from the warehouse into modeling and then into production, skipping data understanding and evaluation.
Deployment in CRISP-DM means more than putting a model behind a web service. IBM defines it as using your new insights to make improvements within your organization.[2] That can be a formal integration, such as churn scores written into a data warehouse every night. It can also be informal, such as a finding that changes a marketing plan. Either way, the deployment phase includes planning how the results will be monitored and maintained, and the scoring folder had no such plan.
CRISP-DM dates from the late 1990s, and you will meet newer methods built on it at work. IBM's Analytics Solutions Unified Method for Data Mining (ASUM-DM) adds project management and operations. Microsoft's Team Data Science Process (TDSP) adds team roles and repository templates. CRISP-ML(Q) adapts the phases to machine learning and adds quality assurance at each step plus an explicit monitoring and maintenance phase. The exam uses the original name, CRISP-DM, and if you know its six phases you can read any of these variants.
DAMA-DMBOK: the organization's view of the same data
The Data Management Association (DAMA) International works at a different scale. Its reference book is the DAMA Guide to the Data Management Body of Knowledge (DAMA-DMBOK). The framework in current use is the second edition, usually called DMBOK2, first published in 2017. It does not describe a project. It describes the ongoing functions an organization needs in order to manage data as an asset. Its well-known "DAMA wheel" puts data governance at the center. Around it sit ten knowledge areas: data architecture; data modeling and design; data storage and operations; data security; data integration and interoperability; document and content management; reference and master data; data warehousing and business intelligence; metadata management; and data quality.
Seen through DAMA, the contract-type recoding was a data management failure before it became a modeling failure. The contract codes are reference data: a controlled list of allowed values that other records point to, like country codes or product categories. In DAMA, reference data, metadata and data quality are permanent responsibilities with named owners, usually called data stewards, who approve changes and announce them. If someone had owned that code list, the recoding would have come with a change notice instead of a surprise.
| Question | CRISP-DM | DAMA-DMBOK |
|---|---|---|
| Scope | One analytics or modeling project | All data management across the organization |
| Shape | Six phases in a cycle you can step back through | Governance at the center of ten knowledge areas |
| Time horizon | The life of a project, repeated for each new project | Continuous, with no end date |
| Typical owners | Project team, data scientists, business sponsor | Chief data officer, governance council, data stewards |
| Typical outputs | Project plan, data quality report, model, deployment plan | Policies, data dictionary, metadata catalog, quality rules, access controls |
| Words a scenario uses | Phases, iterate, business understanding, evaluation | Governance, stewardship, enterprise-wide, metadata, master data |
Why this matters: CRISP-DM tells you which phase a project skipped. DAMA tells you which organization-wide responsibility nobody held. If a scenario is about the order of work within one project, think CRISP-DM. If it is about enterprise ownership, quality rules or metadata, think DAMA.
Version control for code, data, hyperparameters and models
Go back to the account manager's question. To explain why a score changed, you must be able to name, for any prediction, the exact code, data, settings and trained file behind it. The four version-control bullets in the objective add up to that one ability, often called Data lineage: a traceable chain from a prediction back to everything that produced it. Each kind of artifact needs its own mechanism.
Source code version control. Git is the standard tool. Each commit records a snapshot of the tracked files, its author, a message and a link to the commit before it. The commit is named by a hash calculated from its contents, so an ID such as 9f3c2ab identifies one exact state of the code. Change one character and you get a different hash. Branches let you try an idea without disturbing the main line of work. Tags give a release a readable name, such as churn-v6. Pro Git, a widely used free book on Git by Scott Chacon and Ben Straub, published by Apress, can be read in full online, and its early chapters cover recording changes, tagging and branching.[3]
Dataset versioning. Git was built for text files that change through small edits. A 40 GB training extract does not fit that design. Every version would be stored in full, and the repository would become unusably large. The fictional team made a different mistake: their training query read a live warehouse table, so the "same" query returned different rows each week. Data needs one of three approaches:
- Immutable dated snapshots. Write each training extract once to storage that is never overwritten. Record a content hash, such as one computed with Secure Hash Algorithm 256 (SHA-256), so that any later change to the file can be detected.
- Data versioning tools. Tools such as DVC (Data Version Control) and Git Large File Storage commit a small pointer file to Git while the data itself lives in separate storage. Checking out an old commit then brings back the matching data.
- Tables with time travel. Table formats such as Delta Lake and Apache Iceberg keep numbered snapshots, so you can query a table as it was at a given version.
The rule behind all three is the same. A training run must refer to a version of the data that cannot change underneath it. A query such as SELECT * FROM customers is not a version.
Hyperparameters. Hyperparameters are the settings you choose before training, as opposed to the parameters the model learns. Examples are tree depth, learning rate, regularization strength and number of estimators. For versioning, add the random seed and the definition of the train and test split, because both change the result. Keep them in a configuration file committed next to the code, and log them with every run in an experiment tracker such as MLflow. A common format is YAML (YAML Ain't Markup Language), plain text made of indented key: value pairs. A value typed into a notebook cell is saved in the .ipynb file, but that cell can be edited, re-run out of order or overwritten, and no commit, run log or config file records which value produced which model. Here is the kind of file that would have saved the team two days:
# configs/train.yaml (fictional example)
model: gradient_boosting
params:
n_estimators: 400
max_depth: 6
learning_rate: 0.05
subsample: 0.8
seed: 42
data:
snapshot: customers_2026-03-01
holdout: most recent 2 months
Model versioning and environments. A trained model should go into a model registry under a name and a version number, linked to the run that produced it. The model also depends on its software environment: the library versions it was trained and served with. Platforms treat that environment as a versioned artifact too. In Azure Machine Learning, a deployment's environment can either reference an existing versioned environment in the workspace or be specified inline.[4] For MLflow models deployed without a custom scoring script, Azure installs the Python packages listed in the model's conda.yaml file.[5] It installs them while the container is starting up.[5] So if that file says only scikit-learn, with no version number, a later redeploy may install a different release than the one you tested. Pin the versions you tested.
| Artifact | What must be fixed in place | Common mechanism | What breaks if you skip it |
|---|---|---|---|
| Code | The exact source at training time | Git commit hash; tags for releases | Nobody can say which logic produced a model |
| Data | The exact rows and columns used for training and evaluation | Immutable snapshot with hash; pointer file in Git; table time travel | Retraining from the same commit gives a different model |
| Hyperparameters | Every setting chosen before training, plus seed and split | Config file in Git; parameters logged per run | A good model cannot be rebuilt; tuning history is lost |
| Models | The trained artifact, its environment and its source run | Model registry name and version; versioned environment | No rollback, and no way to say which model served a prediction |
When all four are versioned, every training run leaves a record like this one (fictional):
run_id: 2026-03-08-sun-01
git_commit: 9f3c2ab
data_snapshot: customers_2026-03-08 sha256=4be1c9...
params: configs/train.yaml @ 9f3c2ab, override max_depth=10
seed: 42
environment: churn-env version 3 (scikit-learn 1.4.2)
model: churn-gbm version 7
holdout_auc: 0.861
The holdout_auc line is the area under the curve (AUC) of the receiver operating characteristic (ROC) curve, measured on held-out data the model never trained on. The sha256 line is the content hash of the data snapshot.
Why this matters: versioning only one artifact gives a false sense of safety. A model is reproducible only when its code, data, hyperparameters and environment are all pinned and linked to the registered model version.
Worked example: which change moved customer 48211?
After the incident, the team rebuilt the two run records by hand. Read them the way you would read a code diff.
| Field | Version 6 (Friday) | Version 7 (Sunday) | Changed? |
|---|---|---|---|
| Git commit | 9f3c2ab | 9f3c2ab | No |
| Data snapshot | customers_2026-03-01 | customers_2026-03-08 | Yes |
| max_depth | 6 | 10 | Yes |
| learning_rate | 0.05 | 0.05 | No |
| Environment | churn-env version 3 | churn-env version 3 | No |
| Score for customer 48211 | 0.12 | 0.81 | Yes |
Step 1: rule things out. The code and the environment are identical, so neither a logic change nor a library upgrade can explain the jump.
Step 2: notice the confound. Two things changed together, the data and max_depth. From these two runs alone you cannot tell which one moved the score. This is the same problem as an experiment where two treatments were applied at once.
Step 3: separate them. Because every input is versioned, you can build the two missing combinations. Run C uses the old hyperparameters with the new data. Run D uses the new hyperparameters with the old data. Together with the two real runs, that makes a small 2 by 2 design.
| Run | Data snapshot | max_depth | Score for 48211 |
|---|---|---|---|
| A (version 6) | 03-01 | 6 | 0.12 |
| B (version 7) | 03-08 | 10 | 0.81 |
| C (new data only) | 03-08 | 6 | 0.79 |
| D (new depth only) | 03-01 | 10 | 0.14 |
Step 4: read the effects. Changing only the data (A to C) raises the score by 0.67. Changing only the depth (A to D) raises it by 0.02. To check whether the two changes interact, compare the depth effect on new data with the depth effect on old data: (B minus C) minus (D minus A) = (0.81 minus 0.79) minus (0.14 minus 0.12) = 0.02 minus 0.02 = 0. There is no interaction. The data change explains almost the whole jump.
Step 5: find the mechanism. Now compare customer 48211's row in the two snapshots. In 03-01, contract_type is "A" (annual). In 03-08 it is 2, because the upstream system switched to numeric codes. The encoder only knew the letter codes, so it filled anything unfamiliar with 0, which meant month-to-month. Month-to-month contracts are the strongest churn signal in the model. An annual customer had become, as far as the model could tell, a month-to-month customer.
The same method, with one input changed. Suppose the reruns had given C = 0.15 and D = 0.78. Now changing the depth alone moves the score by 0.66, and changing the data alone moves it by 0.03. The diagnosis flips. The cause is the hyperparameter, perhaps deeper trees overfitting to small groups of customers. The fix is different too: re-run validation, compare training and validation error, and either go back to depth 6 or justify depth 10 with evidence. With more than two changes between versions, change one factor at a time from a known baseline. For code changes, git bisect performs a binary search over commits. Neither approach is possible unless every input is versioned. Without versions, the team can only argue from memory.
The IDE and the notebook: where reproducible code gets written
An Integrated development environment (IDE) brings the tools for writing, running, inspecting and managing code together in one application. A typical IDE includes:
- an editor with code completion and inline error checking, called linting;
- a debugger that pauses code at breakpoints so you can inspect variables;
- a built-in terminal and test runner;
- a selector for the interpreter or environment the code runs in;
- built-in Git integration.
Visual Studio Code, PyCharm and RStudio are common IDEs in data science. JupyterLab sits somewhere between a notebook and an IDE.
In the incident, a debugger would have found the bug in minutes. Put a breakpoint inside the encoder, run one Sunday row, and inspect the raw values: you see 2 where you expected "A". IDEs can also bring the development environment closer to production. Microsoft documents that Azure Machine Learning's local endpoints use Docker and Visual Studio Code development containers to set up a local debugging environment.[4] Microsoft's page marks this capability as a public preview, so treat it as a convenience rather than a guarantee that your local container matches the served one exactly.[4]
Notebooks still have a place. They are excellent for exploration and for explaining an analysis, because code, output and prose sit together. Their weakness is hidden state. Cells can be run out of order, edited and re-run, so what is in the session's memory can differ from what the saved file says. Sunday's max_depth=10 lived in exactly such a re-run cell. The usual practice: explore in notebooks, then move any logic you will reuse into modules (plain .py files) that you edit in the IDE, test and version. Notebooks then import from those modules.
| Tool | Strength | Typical risk | Best use |
|---|---|---|---|
| Notebook | Code, charts and prose together; fast iteration | Hidden state from out-of-order cells; awkward to diff and test | Exploration, reports, teaching |
| IDE with modules | Debugger, linting, test runner, Git, refactoring tools | Slower for quick visual exploration | Pipelines, shared libraries, anything deployed |
| Plain text editor | Light and available everywhere | No debugger or project-wide checks | Quick edits to config files on a server |
Clean code methods: making the failure loud
Clean code is code that another person, or you in six months, can read, change and trust. The bug that cost the team two days was not complicated. It was hidden, and the code it hid in looked like this:
# fictional "before": a notebook cell
df['ct'] = df['contract_type'].map({'A': 1, 'B': 2, 'M': 0}).fillna(0)
m = GradientBoostingClassifier(max_depth=10).fit(X, y)
Count the problems. The name ct says nothing. The codes and their meanings are magic values buried in the line. Worst of all, fillna(0) turns every unknown code into "month-to-month" without any warning. That is the opposite of failing loudly. And the hyperparameter is hard-coded in a cell instead of read from the config file. Here is the cleaned version:
# fictional "after": churn/features.py
import pandas as pd
CONTRACT_CODES = {"M": "month_to_month", "A": "annual", "B": "biennial"}
def encode_contract_type(raw):
"""Map raw contract codes to named contract types.
Args:
raw: pandas Series of contract codes from the customer table.
Returns:
pandas Series of contract type names, with missing values kept missing.
Raises:
ValueError: if any non-missing code is not in CONTRACT_CODES, so an
upstream recoding stops the pipeline instead of passing silently.
"""
unknown = set(raw.dropna().unique()) - set(CONTRACT_CODES)
if unknown:
raise ValueError(f"Unknown contract codes: {sorted(unknown)}")
return raw.map(CONTRACT_CODES)
The model itself is now trained by a separate train_model function that reads its hyperparameters from configs/train.yaml. The methods the exam groups under clean code are summarized below.
| Method | In practice | Why it matters for data science |
|---|---|---|
| Descriptive names | contract_type, not ct; churn_model, not m | A reviewer can check the meaning without running the code |
| Small, single-purpose functions | encode_contract_type, build_features, train_model | Each piece can be tested and reused on its own |
| Named constants and config files | CONTRACT_CODES; hyperparameters in YAML | No magic numbers; one place to change a value, and that change is recorded in Git |
| Fail loudly | Raise an error on unknown categories or wrong types | Bad data stops the pipeline before it produces wrong scores |
| Do not repeat yourself | One feature module imported by both training and scoring | Prevents training-serving skew, where the same feature is computed differently in two places |
| Consistent style | Follow PEP 8 (Python Enhancement Proposal 8, Python's style guide), enforced by a formatter and a linter | Diffs show changes in logic, not changes in whitespace |
The "do not repeat yourself" row matters especially in data science. If the training notebook and the scoring service each have their own copy of the encoder, the two copies will drift apart. The model then sees features at scoring time that differ from the ones it learned on, even though both copies look correct.
Unit test writing with Python's unittest
Unit testing means running one small piece of code, such as a single function, on inputs you choose and comparing the result with an output you know is correct. Python's standard library includes the unittest framework, which was originally inspired by JUnit, the Java testing framework.[6] Its pattern is the same as in most languages: test cases are methods on a class, and each method asserts something about the result. Here are three tests for the cleaned encoder:
# tests/test_features.py (fictional example)
import unittest
import pandas as pd
from churn.features import encode_contract_type
class TestEncodeContractType(unittest.TestCase):
def test_known_codes_map_to_names(self):
"""Known letter codes become readable contract types."""
result = encode_contract_type(pd.Series(["M", "A", "B"]))
self.assertEqual(list(result), ["month_to_month", "annual", "biennial"])
def test_numeric_recoding_is_rejected(self):
"""A numeric recoding upstream must stop the pipeline."""
with self.assertRaises(ValueError):
encode_contract_type(pd.Series([1, 2, 3]))
def test_missing_values_stay_missing(self):
"""Missing codes are not silently replaced."""
result = encode_contract_type(pd.Series(["A", None]))
self.assertTrue(pd.isna(result.iloc[1]))
if __name__ == "__main__":
unittest.main()
If you run python -m unittest with no arguments, unittest starts test discovery: it searches the project for test files and runs them all.[6] Two details decide whether discovery finds anything. By default it looks for files whose names match test*.py. And each folder it searches must be an importable package, which means it contains a file named __init__.py, even an empty one. Since Python 3.11, folders without that file are skipped, so a project laid out like this one would otherwise report that it ran 0 tests:
churn/
__init__.py
features.py
tests/
__init__.py (empty, but required for discovery)
test_features.py
configs/
train.yaml
Adding -v gives verbose output. A test's description in that output comes from its method's docstring: the shortDescription method returns the first line of the docstring, or None if there is no description.[6] Output from a passing run looks like this (illustrative):
$ python -m unittest -v
test_known_codes_map_to_names (tests.test_features.TestEncodeContractType.test_known_codes_map_to_names)
Known letter codes become readable contract types. ... ok
test_missing_values_stay_missing (tests.test_features.TestEncodeContractType.test_missing_values_stay_missing)
Missing codes are not silently replaced. ... ok
test_numeric_recoding_is_rejected (tests.test_features.TestEncodeContractType.test_numeric_recoding_is_rejected)
A numeric recoding upstream must stop the pipeline. ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.004s
OK
What should a data scientist unit test? Test the deterministic code around the model: feature encoders, joins, date logic, metric calculations, schema checks and anything that decides what goes into the model. Use tiny hand-built inputs whose correct outputs you can work out on paper. Cover the edge cases that break pipelines: empty inputs, missing values, unseen categories, wrong types and boundary dates. Fix random seeds wherever randomness is involved, so a failure can be repeated. Run the tests on every commit, so a refactor that changes behavior fails within minutes.
Unit tests do not check whether the model is good. Holdout performance belongs to evaluation and experiment design. Checks on a full production dataset, such as "no more than 2% nulls in tenure", are data validation. They run on every new extract rather than on every code change. In the incident, a unit test would have shown that the encoder handled unknown codes badly. A data validation rule would have caught the new codes arriving.
Why this matters: a unit test turns "I think the encoder handles that" into a check that runs on every commit. The cheapest place to catch a silent data bug is a three-row test, not a production score that an account manager questions.
Process documentation: Markdown, docstrings, comments and reference data
The objective lists four kinds of documentation. They have different readers and live in different places, and exam scenarios usually hinge on choosing the right one.
Markdown is a lightweight markup language. Plain text with a few symbols (# for headings, hyphens for lists) renders as formatted text in Git hosting sites, IDEs and notebook text cells. It is the usual format for project-level documents: a README that explains what the project does and how to run it, a CHANGELOG recording each model version, and data or model documentation. A minimal README for the churn project:
# Churn model
## Purpose
Scores monthly churn risk for consumer accounts. Owner: retention analytics.
## How to run
python -m churn.train --config configs/train.yaml
python -m unittest
## Data
Source: crm.customers, monthly immutable snapshots.
Column meanings and allowed values: docs/data_dictionary.md
## Versions
Production: churn-gbm version 6. History in CHANGELOG.md.
A Docstring documents one module, class or function, right next to the code it describes. PEP 257, the Python Enhancement Proposal that sets Python's docstring conventions, defines a docstring as a string literal that occurs as the first statement in a module, function, class or method definition.[7] Because of where it sits, Python stores it as that object's __doc__ attribute.[7] That is why help() and IDE tooltips can show it, and why unittest can print it. PEP 257 says a function's docstring should summarize the function's behavior.[7] It should also document the arguments, return values, side effects, exceptions raised and any restrictions on when the function can be called.[7] The encoder's docstring above does exactly that. PEP 257 describes itself as conventions, not laws or syntax.[7] Teams often adopt a more specific layout, such as the Google or NumPy styles, so that documentation tools can parse the sections.
Appropriate code commenting explains what the code cannot say for itself, which is usually why. A comment that repeats the code goes out of date and adds nothing. Compare:
x = x * 0.9 # multiply x by 0.9 (says nothing)
charge = charge * 0.9 # loyalty rebate, pricing policy PR-12 (says why)
Three more habits help. Delete dead code instead of commenting it out, because Git already keeps the history. When you change code, update the comment next to it. And when you are tempted to write a comment explaining a confusing line, first try renaming or restructuring the code so the comment is unnecessary.
Reference data and documentation covers what the data means. Reference data, as the DAMA section described, is a controlled set of allowed values, such as contract codes, country codes or product categories. Document each set in a Data dictionary: column names, types, meanings, allowed values, owners and change history. One entry from the churn project's dictionary, after the incident:
| Column | Type | Allowed values | Steward | Change log |
|---|---|---|---|---|
| contract_type | string code | M = month-to-month; A = annual; B = biennial | CRM data steward | 2026-03-08: unannounced switch to numeric codes 1-3 detected in the source extract; reverted to letter codes; future changes need steward approval and notice to downstream users |
The same heading also covers documentation about the work itself: where each dataset came from and under what terms, and what each model is for, how it was evaluated and where it should not be used. Many teams write that last part as a short model card in Markdown.
Access via API: pulling data in and serving predictions out
An Application programming interface (API) is a defined way for one program to ask another for data or actions. The objective uses APIs in two directions. Data comes into the project through an API, and predictions go out through one.
Data access and retrieval. Instead of emailing CSV (comma-separated values) files around, a pipeline calls a data provider's API. Most modern ones follow Representational state transfer (REST): resources are addressed by a web address (a Uniform Resource Locator, or URL), read with HTTP (Hypertext Transfer Protocol) GET requests, and returned as JSON (JavaScript Object Notation). Older enterprise systems may use SOAP (Simple Object Access Protocol), which wraps requests in XML (Extensible Markup Language) envelopes. Internal services may use RPC (Remote Procedure Call) styles that call a named function on a remote server. Good practice for retrieval is the same whatever the style:
- keep credentials in a secrets store or environment variable, never in the notebook or the repository;
- handle pagination so you do not silently keep only the first page of results;
- respect rate limits, and retry failed calls with increasing waits (backoff);
- save each pull as an immutable snapshot, along with the request parameters and the retrieval time, because the API will return different data tomorrow.
The last point connects back to data versioning. An API is a live source, just like the warehouse table in the incident.
Model endpoints and model services. Going the other way, other applications get predictions by calling the model through an endpoint. Microsoft's documentation defines inferencing as applying new input data to a machine learning model to generate outputs.[4] An online endpoint is a stable URL that serves those outputs in real time. Behind it, a deployment is the set of compute resources that actually hosts the model. A single endpoint can contain several deployments with different configurations.[4] Microsoft's example routes 90% of incoming traffic to a blue deployment running model version 1 and the remaining 10% to a green deployment running version 2.[4] That is how you release a new model gradually and roll back instantly: change the traffic split, not the URL.
Each deployment runs a scoring script with two functions. The init() function runs when the model is created or updated, for example to load the model into memory once.[4] The run() function is called at every invocation of the endpoint to do the actual scoring.[4] Here is a request and response for the churn service (fictional):
POST https://churn-scoring.example.com/score
Authorization: Bearer <token>
Content-Type: application/json
{"customer_id": 48211, "tenure_months": 31, "contract_type": "A", "monthly_charge": 64.50}
HTTP/1.1 200 OK
Content-Type: application/json
{"customer_id": 48211, "churn_probability": 0.12, "model_name": "churn-gbm", "model_version": 6}
Notice the model_version field. With it, every score answers "which model said this?" by itself, and the account manager's question takes seconds. Authentication matters as well. Microsoft's deployment walkthrough uses key-based authentication and says it does so for simplicity.[5] For production it recommends Microsoft Entra token-based authentication, which provides stronger security through identity-based access control.[5] The general lesson holds on any platform: shared keys are easy to set up, and identity-based tokens are easier to scope, rotate and audit. Atlas's Security+ course covers authentication and key management in more depth.
Compared with the folder of pickles, an endpoint gives you a fixed interface, versioned deployments, controlled rollout, authentication and a place to log every request for monitoring. Batch scoring, where a scheduled job writes scores to a table, is still the right choice when nobody needs an answer within seconds. The model should still be pulled from the registry by name and version.
Dependency licensing: what every installed package brings with it
Every package you install comes with a Software license: the copyright holder's terms for using, changing and redistributing the work. So does every package that package depends on, which are called transitive dependencies. Datasets and pretrained model weights carry terms too. Pro Git is a handy example of terms that are not "anything goes". The book is free to read, but its content is licensed under Creative Commons Attribution Non Commercial Share Alike 3.0.[3] Reading it to learn Git is fine. Copying its text into a paid training product is a different question, because of the NonCommercial term.
Licenses fall into a few families. This summary describes common, widely understood terms. It is not legal advice, and your organization's legal team decides what its policy allows.
| Family | Examples | Main obligations | Typical risk for a data science product |
|---|---|---|---|
| Permissive | MIT License; BSD-3-Clause (the three-clause Berkeley Software Distribution license); Apache-2.0 (Apache License 2.0) | Keep the copyright and license notice; Apache-2.0 also includes a patent grant and a NOTICE file | Low; usually allowed everywhere |
| Weak copyleft | LGPL (GNU Lesser General Public License); MPL-2.0 (Mozilla Public License 2.0) | Changes to the library itself must be shared under the same license; using it from your own code is generally allowed | Moderate; follow the rules on modifications |
| Strong copyleft | GNU General Public License (GPL-3.0) | If you distribute a work that includes it, you must release the combined work's source under the GPL | High for software you ship to customers |
| Network copyleft | GNU Affero General Public License (AGPL-3.0) | Like the GPL, plus: if you modify it and users interact with it over a network, you must offer them the modified source | High for hosted APIs and software-as-a-service products |
| Non-commercial or restricted | Creative Commons Attribution-NonCommercial (CC BY-NC); many dataset and model-weight licenses | No commercial use, or use limited by stated conditions | Often blocks commercial use entirely |
| No license stated | A repository with no license file | None granted: by default, copyright reserves all rights | Cannot safely be used until the author grants a license |
To find a package's declared license, run pip show, or read the license file in the package's repository. CompTIA's acronym list expands PIP as Preferred Installer Program; pip's own documentation simply calls it the package installer for Python. Output for a fictional package might look like this:
$ pip show fastgeo
Name: fastgeo
Version: 2.3.1
Summary: Fast geospatial joins
License: AGPL-3.0-only
Requires: numpy, shapely
A worked decision. The churn team wants to put a scoring model inside a desktop application that the company sells to retail partners. The model needs a small text-cleaning library. Version 1 of that library is under the MIT License. Shipping it inside the app is fine, provided the MIT copyright notice goes into the app's third-party notices.
Change one input. Now the library's maintainers relicense version 2 under GPL-3.0, and someone upgrades to it. Selling the app now means distributing a combined work that includes GPL code. That requires releasing the app's source under the GPL, which conflicts with the company's proprietary product. The same import line, after an upgrade, changed the answer from "fine" to "blocked". This is why license checks must run again on every upgrade, not only when a package is first added.
Good practice follows from that. Keep a list of every dependency and its license, sometimes formalized as a software bill of materials. Pin versions in a lock file or the environment's conda.yaml. Check licenses automatically when dependencies change. Keep an allowlist of acceptable licenses. Treat datasets and pretrained weights as dependencies with their own licenses.
Exam cues: turning scenario wording into a practice
"Given a scenario" questions describe a symptom and ask for the practice that prevents or fixes it. The table pairs common stem wording with the answer it points to, and with the nearby answer people confuse it with.
| The stem says | Points to | Commonly confused with |
|---|---|---|
| Same code, but retraining gives a different model; training data is a live table | Data versioning (immutable snapshots, pointer files, time travel) | Code version control, which is already in place |
| Cannot rebuild the best run from last month's tuning | Hyperparameter versioning in config files and run logs | Model registry, which stores the result but not how to rebuild it |
| Need to roll back, or say which model produced a score | Model versioning in a registry, with version returned by the endpoint | Git tags on the code alone |
| Project moved to modeling without checking the business goal | CRISP-DM, return to business understanding | DAMA, which is organization-wide rather than per project |
| Enterprise-wide stewardship, metadata, quality rules | DAMA-DMBOK, with data governance at the center | CRISP-DM |
| Colleagues need a function's arguments, returns and exceptions | Docstring | Inline comment |
| Explain why a constant or threshold has the value it has | Code comment | Docstring, which describes the interface |
| Project overview and how to run it, rendered in the repository | Markdown README | Docstring |
| Allowed values and owner for a code list | Reference data documentation, data dictionary | README |
| A refactor silently changed outputs | Unit tests run on every commit | Holdout evaluation, which measures model quality, not code behavior |
| Need a debugger, linting and integrated Git | IDE | Notebook |
| Magic numbers, copied code, cryptic names, silent defaults | Clean code methods | More comments |
| Applications need predictions in real time | Model endpoint or model service | Batch scoring job |
| Pull fresh vendor data every day | API data retrieval, saving each pull as a snapshot | Model endpoint |
| A package's terms forbid commercial use or require releasing source | Dependency licensing review | Version pinning, which fixes the version, not the terms |
Common misconceptions
- "Our code is in Git, so our models are reproducible." Git pins the code. A model also depends on the data, the hyperparameters, the random seed and the library versions. Retraining from the same commit on a live table gives a different model.
- "CRISP-DM is a waterfall: finish one phase, then start the next." The sequence is not strict. Projects routinely go back from evaluation to business understanding, or from data preparation to data understanding.
- "DAMA is just another project life cycle like CRISP-DM." DAMA-DMBOK describes ongoing, organization-wide data management with governance at the center. It is not a sequence of steps for one project.
- "Comments and docstrings are the same thing." A docstring is the first statement of a module, class or function, stored in __doc__ and shown by help(). It documents the interface. A comment is ignored by Python and should explain why the code does something.
- "Unit tests are for software engineers; data scientists validate with metrics." Metrics test the model. Unit tests check the deterministic code around it, such as encoders, joins and date logic, which is where silent data bugs live.
- "If it is on GitHub or on pip, we can use it." Being publicly available is not the same as being licensed for your use. Copyleft, non-commercial and missing licenses can all block a commercial product.
Looking back
- CRISP-DM has six phases (business understanding, data understanding, data preparation, modeling, evaluation, deployment), and projects move back and forth between them rather than in strict order.
- DAMA-DMBOK puts data governance at the center of ten knowledge areas, including reference and master data, metadata and data quality. It covers the whole organization on an ongoing basis, not a single project.
- A model is reproducible only when its code, data, hyperparameters (plus seed and split) and environment are all versioned and linked to a registered model version.
- When two inputs change between model versions, rebuild the missing combinations, changing one factor at a time, to find which change moved the result. That is only possible if every input is versioned.
- A docstring is the first statement in a module, class or function, stored as __doc__. A function's docstring covers behavior, arguments, return values, side effects and exceptions.
- Comments explain why. A Markdown README explains the project and how to run it. A data dictionary documents reference data, including allowed values and owners.
- Unit tests check small pieces of deterministic code on hand-built inputs. Running python -m unittest with no arguments starts test discovery, which finds test*.py files inside folders that contain __init__.py.
- One model endpoint can hold several deployments with a traffic split, such as 90% and 10%, which allows gradual release and instant rollback without changing the URL.
- Every dependency, dataset and set of pretrained weights has license terms. Permissive licenses need attribution, copyleft can force you to release source, and with no license nothing is permitted.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- IBM. (n.d.). IBM SPSS Modeler CRISP-DM Guide. ibm.com
- Scott Chacon, Ben Straub. (2014). Pro Git, 2nd Edition. Git project (git-scm.com). git-scm.com
- Microsoft Learn. (n.d.). Online endpoints and deployments for real-time inference. learn.microsoft.com
- Microsoft Learn. (n.d.). Deploy MLflow models to online endpoints. learn.microsoft.com
- Python Software Foundation. (n.d.). unittest, Unit testing framework. docs.python.org
- David Goodger, Guido van Rossum. (2001). PEP 257, Docstring Conventions. Python Software Foundation. peps.python.org
- Key terms
- CRISP-DM
- Cross-industry Standard Process for Data Mining: a process model for one analytics project with six phases (business understanding, data understanding, data preparation, modeling, evaluation, deployment) that teams move back and forth between.
- DAMA-DMBOK
- The Data Management Association's Data Management Body of Knowledge, a framework for organization-wide data management with data governance at the center of knowledge areas such as metadata, data quality, and reference and master data.
- Data versioning
- Recording an unchangeable, identifiable version of a dataset, such as a hashed snapshot or table snapshot ID, so a training run always refers to exactly the same rows.
- Model registry
- A store that keeps trained models under a name and version number, linked to the run, code, data and environment that produced each version, so models can be promoted or rolled back.
- Docstring
- In Python, a string literal written as the first statement of a module, class, function or method; it becomes the object's __doc__ attribute and documents its behavior and interface.
- Unit test
- An automated check that runs one small piece of code on chosen inputs and asserts that the output matches a known correct value or that an expected error is raised.
- Model endpoint
- A stable network address that applications call to get predictions from a deployed model; it can route traffic across several deployments of different model versions.
- Reference data
- A controlled set of allowed values, such as country codes or contract types, that other records refer to and that should have a documented owner and change history.
- Copyleft license
- A software license, such as the GPL or AGPL, that requires derived or combined works to be released under the same license terms when they are distributed or, for the AGPL, offered over a network.
- Integrated development environment
- An application that combines a code editor, linting, a debugger, a terminal, a test runner, environment selection and version control integration in one place.
DevOps and MLOps for Data Science
- Explain which DevOps practices (CI/CD pipelines, code isolation, virtualization, container orchestration and data replication) carry over to machine learning unchanged, and what failure each one prevents.
- Distinguish offline from online model validation, and choose among shadow, canary, blue/green and A/B releases for a stated goal.
- Use an A/B test result, a drift statistic and a guardrail metric to decide whether to promote, hold or roll back a model.
- Explain what model performance monitoring compares, how baselines and constraints work, and what to watch when outcome labels arrive late.
A model that passed every test and still lost money
Google's Cloud Architecture Center guide to MLOps makes a claim about where machine learning (ML) work actually gets hard. With relevant training data, a data scientist can usually build a model that predicts well on an offline holdout dataset. According to the guide, the hard part is building an integrated ML system and keeping it running in production.[1]
Here is an invented example of that gap. In March, a subscription company trains version 4 (v4) of its churn model. On the holdout set it scores a receiver operating characteristic area under the curve (ROC-AUC) of 0.86, compared with 0.85 for version 3 (v3). The code passes its unit tests and the model ships. In May, marketing launches a new "flex" plan that never appeared in the training data, and thousands of customers switch to it. Nobody commits a line of code and every test stays green. For six weeks the model sends retention discounts to customers who were never going to leave and misses the ones who were.
No software bug caused that loss, at least not in the usual sense. That raises the question this lesson is built around: is running models in production the same engineering problem that software teams already solved with DevOps, or a different problem that needs its own practices?
Exam objectives: DataX DY0-001 objective 4.6, "Explain the importance of DevOps and MLOps principles in data science."[2] It lists data replication, continuous integration/continuous deployment (CI/CD) pipelines, model deployment, container orchestration, virtualization, code isolation, model performance monitoring and model validation. Model validation comes in two forms, online and offline, and model A/B testing is one way to do the online kind.
Two positions on what MLOps is
DevOps (development plus operations) is the practice of having one team build, test, release and run software, with as many of those steps automated as possible. The usual promise is shorter development cycles, faster deployment and more dependable releases. MLOps (Machine Learning Operations) applies the same principles to ML systems. Google describes practicing MLOps as pushing for automation and monitoring at every step of building an ML system: integration, testing, release, deployment and infrastructure management.[1]
Few people dispute that definition. The argument is about how much the "ML" part changes the job. The two positions below are a framing this lesson uses to sort the evidence, not quotations from named authors.
Position one: MLOps is DevOps with a model inside. In this view a trained model is just another build artifact, like a compiled binary. You version it, test the code around it, package it and release it with the tools you already have. Google's own guide admits a large overlap: ML and other software systems are alike in continuous integration of source control, unit testing and integration testing.[1] The infrastructure doesn't care what it runs either. A container platform treats a container holding a web shop and one holding a gradient-boosted tree the same way. The case for this view is that many production failures in any service are ordinary software failures: a library version mismatch, a server that runs out of memory, a malformed request. On this view, a separate MLOps toolchain mostly duplicates tools that already exist.
Position two: ML breaks assumptions that DevOps relies on. DevOps quietly assumes that software only behaves differently when someone changes its code or configuration. An ML system's behavior also depends on the data it learned from and the data it receives, and the world that produces that data keeps changing. Google's guide notes that testing an ML system must add data validation, trained model quality evaluation and model validation to the usual unit and integration tests.[1] Deployment may mean shipping a multi-step pipeline that retrains and redeploys models automatically, rather than one service. And in production, a model can decay while its code stays exactly the same. Amazon's Well-Architected Machine Learning Lens lists data quality, model quality, model bias and model explainability among the reasons a model's performance can degrade over time.[3] The flex-plan story above sums up position two's case.
The table shows where the positions overlap and where they split.
| Concern | DevOps answer | What an ML system adds |
|---|---|---|
| What changes behavior | Code and configuration | Also training data, live input data and the trained weights |
| What gets tested | Unit and integration tests | Also data validation, model quality evaluation and model validation |
| What gets released | An application build | A model artifact, or a whole pipeline that trains models |
| What triggers a release | A commit | Also new data, a schedule or a monitoring alert |
| How it fails in production | Errors, crashes, slow responses | Also silent decay: outputs that look valid but are wrong more often |
| What a rollback restores | The previous build | The previous model, which still faces the same shifted data |
The trigger row is the one with no DevOps counterpart. Google's reference architecture adds continuous training (CT): the training pipeline runs automatically on new data so the model can pick up new patterns. In that design, filters on log messages can start a run when new data arrives or when a monitoring service raises skew or drift alerts.[4] Many teams also retrain on a fixed schedule. A web application never needs a new build just because the world changed. A model often does.
Remember: both positions accept the same software practices. They disagree about whether data and model behavior need their own tests, triggers and monitors. The next five sections cover the shared ground: CI/CD, code isolation, virtualization, orchestration and replication. The sections after that cover the problems that only position two's additions can catch.
CI/CD pipelines: the shared foundation
Continuous integration (CI) means developers merge small changes into a shared repository often, and every merge triggers an automatic build and test run. A broken change gets caught within minutes of being written rather than on release day. Continuous deployment goes further: every change that passes the pipeline goes to production with no human approval. A close relative, continuous delivery, stops one step short. Every passing build is ready to release, but a person decides when. CompTIA's acronym list expands CI/CD as Continuous Integration/Continuous Deployment. Real teams and vendor documents use "CD" for both meanings, so read the context.
A pipeline is the ordered set of automated stages a change goes through. Google's reference architecture for ML on Google Cloud gives a concrete one. When a developer pushes code, Cloud Build copies the repository into its build environment, runs the unit and integration tests, and builds the Docker container images, one per pipeline component, only if those tests pass.[4] The same repository holds the component source code, the tests, configuration files for pipeline parameters, the exploratory notebooks and one Dockerfile per container image. A Dockerfile is a short text recipe that lists the steps for building a container image: which base image to start from, which packages to install and which command to run.
Here is what that kind of pipeline might look like for a model service. It is an illustrative outline, not any one product's syntax.
# Illustrative CI/CD pipeline for a model service (generic outline)
trigger: push to branch main
stages:
1 checkout copy the repository into a clean build workspace
2 lint static analysis, for example Pylint
3 unit_test run tests/unit
4 data_test check schema, types and value ranges of the training snapshot
5 build build one container image per component, tagged with the commit hash
6 train_eval run the training pipeline on a pinned data snapshot
7 gate fail unless the candidate beats the production model on the holdout set
8 register store model, metrics, data version and image tag together
9 deploy_staging release to a staging endpoint and run smoke tests
10 deploy_prod canary at 10 percent, then full rollout if monitors stay healthy
A smoke test, in stage 9, is a quick check that the freshly deployed service starts and answers a basic request; it is not a full evaluation. Stages 1, 2, 3, 5, 9 and 10 would look the same in any web application's pipeline, which supports position one. Stages 4, 6, 7 and 8 have no counterpart in ordinary software, which supports position two. Stage 8 matters more than it seems. If a model misbehaves in June, you need to know which commit, which container image and which data snapshot produced it. Only a record written at build time can tell you.
To see what each stage is for, take four failures and ask which stage stops each one.
| Failure (invented examples) | Stage that stops it | Why that stage and not an earlier one |
|---|---|---|
| A refactor renames a function that the serving code still calls | 3, unit tests | Plain code breakage: the classic CI catch |
| An upstream team starts sending monthly_charge in cents instead of dollars | 4, data tests | The code is unchanged and runs fine. Only a range check notices: expected 5 to 250, observed values up to 24,900 |
| A useful feature is dropped by mistake and ROC-AUC falls by 0.03 | 7, model gate | The code works and the data is valid. Only comparing metrics with the current model shows the problem |
| The new model needs about 2.4 GB of memory, but its container is limited to 2 GiB (gibibytes, about 2.15 GB) | 9, staging smoke tests, or the canary in 10 | The container is killed when the model loads. Only running it under production-like limits shows this |
The second failure is the most revealing. Without stage 4, a model trained on the corrupted snapshot would still build and pass its unit tests. It might even score well on a holdout drawn from the same corrupted data. Then it would meet real requests priced in dollars. A DevOps pipeline that tests only code has no stage that can see this.
Code isolation: same code, same libraries, every run
Code isolation means each project, or each pipeline step, runs with its own explicitly declared dependencies. It is kept separate from other projects and from whatever happens to be installed on the host. This is the fix for the oldest complaint in the field: "it works on my machine." A model saved with pickle under one version of scikit-learn is not guaranteed to load, or to predict the same way, under another version. A data scientist's laptop and a production server rarely match by accident.
There are three common levels of isolation. Each one isolates more than the one before it.
| Level | What it isolates | What it still shares with the host | Typical use |
|---|---|---|---|
| Virtual environment (Python venv with pip, conda, R's renv) | Language packages and their versions | Operating system, system libraries, drivers, kernel | Local development, one environment per project |
| Container image | Packages, system libraries, a filesystem and its own process space | The host operating system kernel | Pipeline components, model servers, CI jobs |
| Virtual machine | A whole guest operating system | Only the physical hardware, through a hypervisor | Different operating system needs, strong separation between tenants |
pip is the Python package installer, which CompTIA's list expands as Preferred Installer Program (PIP). It installs packages into whichever environment is active. Isolation only helps if the versions are pinned. A requirements file like this example records exact versions, so a rebuild next month gets the same libraries:
# requirements.txt (example)
pandas==2.2.2
numpy==1.26.4
scikit-learn==1.5.1
Containers take isolation further, and Google recommends containerizing ML pipeline components for reasons that match this objective. A container separates the execution environment from the custom code's runtime, and each pipeline component gets its own isolated environment, with its own runtime version, language and libraries.[1] That means a feature-engineering step can keep an older pandas while the training step uses a new deep learning library, and neither can break the other.
Model hosting services make the pairing of model and environment explicit. In Microsoft's Azure Machine Learning safe-rollout tutorial, the new model goes into a second deployment named green. The tutorial's code pairs that model file with its own conda environment file and its own base container image:
model2 = Model(path="../model-2/model/sklearn_regression_model.pkl")
env2 = Environment(
conda_file="../model-2/environment/conda.yaml",
image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu22.04",
)
Isolation applies to code paths as well as libraries. Experimental code stays on branches and in separate development and staging environments until the pipeline has tested it. That way a half-finished idea in a notebook never shares a runtime with the model that serves customers.
Remember: isolation is only as reliable as its version pins. An unpinned requirements file, or a container image built from a floating "latest" tag, gives you a fresh and different environment every time it is rebuilt.
Virtualization: virtual machines and containers
Virtualization is software presenting physical resources (processors, memory, disks, network cards) as several isolated virtual ones. The classic form uses a Hypervisor, a software layer that runs virtual machines (VMs). The Kubernetes documentation's short history of deployment explains why this caught on. Virtualization isolates applications from each other, uses a physical server's resources better, and lets you treat hardware as a pool of disposable machines. Each VM is a full machine with its own operating system, running on virtualized hardware.
Containers virtualize at a different level. The National Institute of Standards and Technology (NIST) Special Publication 800-190, the Application Container Security Guide published in September 2017, defines application containers as a form of operating system virtualization combined with application software packaging.[5] A container does not emulate hardware for a guest operating system. Instead, the host's operating system kernel gives each container its own view of the filesystem, processes and network, plus a share of CPU (central processing unit) time and memory. The Kubernetes documentation describes containers as similar to VMs but with relaxed isolation, so that applications share the operating system (OS). Sharing the OS is why containers are small and start quickly. It is also their main weakness.
| Question | Virtual machine | Container |
|---|---|---|
| What is virtualized | Hardware, under a guest OS | The OS view: filesystem, processes, network |
| Own OS kernel? | Yes | No: shares the host kernel |
| What the image contains | A whole OS plus the application | The application, its libraries and a minimal filesystem |
| Size and start-up | Larger; boots an OS | Smaller; starts a process |
| Isolation boundary | The hypervisor: strong | Kernel features: weaker, because a kernel flaw affects every container on the host |
| Different OS family from the host? | Yes, for example a Windows guest on a Linux host | No: Linux containers need a Linux kernel |
| Typical data science use | Per-team notebook servers, legacy tools, untrusted tenants | Model servers, pipeline steps, CI jobs |
The table turns into decisions quickly. Here are three invented cases.
- Scoring code needs a Windows-only library, and the cluster runs Linux. A container can't supply a Windows kernel, so this calls for a VM (or a Windows host).
- Forty replicas of a Python model server on Linux. Use containers. Each replica is a process with its own filesystem, and nobody wants forty copies of an operating system.
- A platform runs code uploaded by different customers. A shared kernel means one tenant's escape could reach another. Use VMs, or put each tenant's containers inside its own VM. The risks of containers are the subject of NIST SP 800-190, and the Atlas Security+ course covers them.
In practice the two layers usually stack. Cloud Kubernetes clusters typically run containers on nodes that are themselves VMs. On a Windows laptop, the Windows Subsystem for Linux (WSL) version 2 and Docker Desktop both run a lightweight Linux VM, so that Linux containers have a Linux kernel to share. Graphics processing units (GPUs) follow the same logic. The GPU driver lives on the host, and the container carries user-space libraries, such as NVIDIA's CUDA (Compute Unified Device Architecture) toolkit, that must be compatible with that driver.
Container orchestration with Kubernetes
One container on a laptop needs no management. Forty replicas spread across six servers do. Something has to place them on machines with spare memory, restart the ones that crash, spread requests across them, and replace version 4 with version 5 without dropping traffic. That job is container orchestration, and Kubernetes is the usual open-source example.
The Kubernetes documentation lists what it provides. It can expose a container under a Domain Name System (DNS) name or its own Internet Protocol (IP) address, and spread traffic across replicas when load is high. It can automatically mount storage, from local disks to public cloud providers. It also handles automated rollouts and rollbacks: you describe the desired state of your containers, and Kubernetes changes the actual state to match at a controlled rate. Here is an invented manifest for a model server:
# Example Kubernetes Deployment for a model server (illustrative)
apiVersion: apps/v1
kind: Deployment
metadata:
name: churn-model
spec:
replicas: 4
selector:
matchLabels:
app: churn-model
template:
metadata:
labels:
app: churn-model
spec:
containers:
- name: server
image: registry.example.com/churn-model:v4-3f9c2ab
ports:
- containerPort: 8080
resources:
limits:
memory: "2Gi"
cpu: "1"
Read the manifest as a statement of what should be true, not a list of steps. It says: four replicas of the image tagged v4-3f9c2ab, each allowed at most 2 GiB of memory and one CPU core. If a node dies and takes a replica with it, a controller sees three replicas where there should be four and starts a new one elsewhere. If the CI/CD pipeline changes the image tag to v5 and applies the file, Kubernetes replaces replicas a few at a time and keeps the previous version's record so the rollout can be reversed. Notice the memory limit, too. A container whose process goes over it is killed, which is the fourth failure from the pipeline table.
Two boundaries confuse people. First, Kubernetes is not a CI/CD system. Its documentation says plainly that it does not deploy source code or build your application, and that CI/CD workflows are left to each organization.[6] The pipeline builds and tests the image, and Kubernetes runs it. Second, "orchestration" means two different things in ML. The Kubernetes documentation itself says it is not orchestration in the strict sense of running a defined workflow (first A, then B, then C). Instead it runs independent control processes that keep pushing the current state toward the desired state.[6] ML pipeline tools do the other kind of orchestration. In Google's architecture, a pipeline is a set of containerized components plus a specification, written in Python, of the order in which the ML tasks run. That order forms a directed acyclic graph (DAG): steps with dependencies between them and no loops.
| Aspect | Container orchestration | Workflow (pipeline) orchestration |
|---|---|---|
| Unit managed | Long-running containers (replicas) | Tasks that run once and finish |
| Core idea | Keep the declared desired state true | Run steps in dependency order |
| ML example | Keep four model-server replicas healthy | Validate data, then train, then evaluate, then deploy |
| Typical tools | Kubernetes | Kubeflow Pipelines, Apache Airflow (often running on Kubernetes) |
| What failure looks like | A replica crashes and is restarted automatically | A failed step blocks every step downstream of it |
Data replication: copies that must agree
Data replication means keeping copies of the same data on more than one machine or in more than one location, and keeping those copies in step as the data changes. Data science teams rely on it for four things. One is availability: if the primary database fails, a replica takes over. Another is read scaling: online models read features from read replicas, so the primary is not overloaded. A third is locality: training data is copied into the region where the GPUs are. The last is disaster recovery across regions.
The most important design choice is timing. With synchronous replication, a write isn't confirmed until the replicas have it too. Every copy agrees, but writes are slower and depend on the network between the copies. With asynchronous replication, the primary confirms the write right away and sends it to the replicas afterward. Writes are fast, but each replica runs behind the primary by some replication lag. The lag is usually small, but it can grow much larger under load.
Here is an invented example showing why lag matters for a model. A payments company computes txn_count_10min, the number of transactions on a card in the last 10 minutes. Training data was built from the primary database, where the count is exact. The online fraud model reads the same feature from an asynchronous read replica that runs about 90 seconds behind. During a card-testing attack, a stolen card makes 12 transactions in 2 minutes, one every 10 seconds: the first at 10 seconds, the 12th at 120 seconds. When the model scores the 12th, the replica only holds transactions that are more than 90 seconds old, meaning those at 10, 20 and 30 seconds. The lag hides the other 9. The model sees "3 in 10 minutes", a normal pattern, and approves. The model itself was fine. The copy it read was out of date.
Now change one input. Suppose the feature were avg_spend_12mo, average monthly spend over 12 months. The same 90-second lag would change that value by almost nothing, and the replica would be perfectly safe to read. Lag matters relative to the feature's time window. Features over short windows feel it most. The fixes for the fraud case: read short-window features from the primary or a synchronously replicated store, compute them in the event stream, or log features exactly as they were served and train on those logs.
The general principle is consistency between training and serving. When a model is trained on one version of a feature and served another, the gap is called training/serving skew, and it looks exactly like model decay. Google's architecture offers a feature store as one remedy: a central repository that standardizes how features are defined, stored and accessed for both training and serving.[1]
Replication is often confused with three other ways of making or splitting copies of data:
| Technique | What it does | Protects against | Does not protect against |
|---|---|---|---|
| Replication | Keeps live copies in sync | Machine or site failure; heavy read load | Mistakes, which are replicated too |
| Backup | Takes periodic point-in-time copies, stored separately | Accidental deletion, corruption | Data written since the last backup |
| Snapshot or versioned dataset | Freezes a labeled copy of data at one moment | Being unable to reproduce a training run | Live outages, because it is not kept in sync |
| Sharding (partitioning) | Splits data across machines, each holding a part | The size limits of one machine | Losing a shard, unless the shard is also replicated |
The first row's last column is the one to remember. Replication copies mistakes faithfully. If someone drops the feature table on the primary, the replicas drop it within seconds. Recovering yesterday's table takes a backup or a versioned snapshot. Reproducing last quarter's model takes the exact snapshot it trained on, which is why the pipeline's register stage records the data version.
Offline model validation: the gate before any traffic
Offline model validation judges a trained model on stored data it was not trained on, before any user sees it. Google's process splits this into two steps. Model evaluation computes quality metrics on a holdout test set. Model validation then confirms the model is good enough to deploy, meaning its predictive performance beats a baseline.[1] The baseline is usually the model currently in production, called the champion. If no model exists yet, a simple rule can serve as the baseline. Google adds that the model must also be tested for deployment: it has to work with the serving infrastructure and be consistent with the prediction service's application programming interface (API).
Here is a hypothetical re-run, separate from the opening story. In that story the team checked one number, overall ROC-AUC, and shipped v4. Suppose instead it had put v4 through a stricter gate, with the champion v3 as the baseline. The rules: overall ROC-AUC must be at least the champion's, no customer segment may lose more than 0.02 ROC-AUC, and 95th-percentile (p95) latency in staging must be 120 milliseconds (ms) or less.
| Check | Rule | Champion v3 | Candidate v4 | Result |
|---|---|---|---|---|
| Schema and data tests | Must pass | Pass | Pass | Pass |
| ROC-AUC, all customers | At least the champion's | 0.848 | 0.862 | Pass |
| ROC-AUC, tenure under 6 months | No drop over 0.02 | 0.823 | 0.791 | Fail: drop of 0.032 |
| ROC-AUC, tenure 6 months or more | No drop over 0.02 | 0.856 | 0.874 | Pass |
| p95 latency in staging | 120 ms or less | 88 ms | 97 ms | Pass |
Overall ROC-AUC rose from 0.848 to 0.862 (the 0.85 and 0.86 of the opening, before rounding), so the one-number check the team actually used let v4 through. The slice check catches what the average hides. Customers in their first six months are a minority of the holdout, so a 0.032 drop for them barely moves the overall figure. Yet they are exactly the customers most likely to churn. Under this gate, v4 fails and would not have shipped.
Now change one input. The team retrains with six more months of data, which adds many recent sign-ups. The new candidate scores 0.860 overall and 0.829 on short-tenure customers, which is now above the champion's 0.823. Every rule passes, and the model moves on to online validation.
Why not stop at the offline gate? An offline holdout comes from the past. It can't show how the model behaves on next month's inputs, how its decisions change customer behavior, or how the serving system copes with real traffic. Neither gate would have caught the flex plan, which did not exist yet. So Google's guide says that, on top of offline validation, a newly deployed model goes through online validation in a canary deployment or an A/B testing setup before it serves predictions to all online traffic.[1] Online model validation means judging the model on live production traffic.
Model deployment: serving patterns and release strategies
Model deployment means putting a validated model where it can serve predictions. Google lists three targets: a microservice with a REST API that serves online predictions, a model embedded in an edge or mobile device, and a batch prediction system. REST (Representational State Transfer) is a style of web API. The client sends a Hypertext Transfer Protocol (HTTP) request, here a JavaScript Object Notation (JSON) record of features, and gets the prediction back in the response. Microsoft's Azure documentation calls the online form an online endpoint and uses it for real-time inference.
| Serving pattern | When predictions are made | Latency need | Example | Typical failure |
|---|---|---|---|---|
| Batch | On a schedule, over a whole table | Minutes to hours is fine | Nightly churn scores written to the customer database | Stale scores; a failed job nobody notices |
| Online (real-time) | Per request, through a REST API | Milliseconds | Fraud check when a card is used | Latency spikes, timeouts, out-of-memory restarts |
| Edge or embedded | On the device itself | No network round trip | Next-word suggestions on a phone keyboard | Old model versions linger on devices that never update |
Choosing a serving pattern means choosing when features are computed and how fresh a prediction has to be. A churn score that drives a weekly email campaign can be computed in a nightly batch, which is cheap and simple to recover when it fails. A fraud decision at the card terminal can't wait for tonight's batch.
The second choice is how traffic moves from the old model to the new one. The five common release strategies answer different questions:
| Strategy | Who receives the new model's answers | Question it answers | Main cost or risk |
|---|---|---|---|
| Replace in place | Everyone, all at once | None: nothing is tested on live traffic first | Every user is exposed if it is wrong |
| Blue/green | Everyone after the switch, with the old version kept ready | Can we switch back instantly? | Running two full environments |
| Canary | A small share at first, then more | Is it safe? (errors, latency, guardrails) | A small group is exposed to problems |
| Shadow (mirroring) | Nobody: it gets copies of requests, and its answers are discarded | How does it behave on real inputs? | Duplicate compute; no outcomes can be measured |
| A/B test | A random share, for a planned period | Is it better on a business metric? | Needs a planned sample size; some users get the worse model |
Microsoft's safe-rollout tutorial walks through several of these using one endpoint with two deployments: blue (current) and green (new). First you test green directly. A REST client can call a specific deployment, bypassing the endpoint's traffic rules, by naming it in an HTTP header. Next you can mirror a percentage of live traffic to green; the tutorial's example mirrors 10 percent.[7] Mirrored requests are copies, so clients still get blue's answers. Only after green has been tested do you send it a small share of real traffic. These are the tutorial's commands, with the request body trimmed:
# From Microsoft's Azure Machine Learning safe-rollout tutorial
# 1. Call the green deployment directly, bypassing traffic rules
curl --request POST "$SCORING_URI" --header "Authorization: Bearer $ENDPOINT_KEY" --header "azureml-model-deployment: green" ...
# 2. After mirroring has been tested, turn it off
az ml online-endpoint update --name $ENDPOINT_NAME --mirror-traffic "green=0"
# 3. Canary: send 10 percent of live traffic to green
az ml online-endpoint update --name $ENDPOINT_NAME --traffic "blue=90 green=10"
Mirroring is what Amazon calls shadow deployment: version B runs alongside version A and receives copies of A's requests without affecting production traffic.[8] It lets you measure the new model's latency, errors and predictions on real inputs without putting any customer at risk. It has two costs. You pay for the extra resources needed to run a second model in parallel with the live one. And because no customer ever sees the shadow model's output, you learn nothing about outcomes. You cannot know whether customers would have accepted the shadow model's offers. That question needs an A/B test.
Remember: shadow tests behavior without users, canary tests safety on a few users, and an A/B test measures which model is better. Blue/green is about switching and switching back instantly, not about measuring anything.
Model A/B testing: online validation with a decision rule
Model A/B testing randomly assigns users to the current model (A) or the candidate (B) for a planned period. It then compares an outcome that matters to the business, such as offer acceptance, revenue per user or fraud losses. Google's guide notes that a new model version usually goes through A/B testing or online experiments before it is promoted to serve all prediction traffic, and Amazon's Well-Architected guidance recommends A/B testing for model updates so that improvements are confirmed before the existing model is fully replaced.
A/B tests and canary releases both split traffic, which is why they get confused. They answer different questions. A canary asks whether the new model is safe. It watches errors, latency and guardrail metrics on a small share, then either ramps up or rolls back quickly. An A/B test asks whether the new model is better. It fixes a primary metric, a sample size and a significance level before it starts, and it keeps the split in place until the sample is reached. Many teams run them in that order: canary first, then the experiment. Randomize by user, not by request, so that no customer sees both models.
For a yes-or-no outcome (did the customer accept the offer?), the standard tool is the two-proportion z-test. It gives the same p-value as the chi-squared test on a 2-by-2 table of arm by outcome, because z squared equals that chi-squared statistic. Let nA and nB be the number of customers in each arm, xA and xB the number who accepted, and pA = xA/nA and pB = xB/nB the acceptance rates. Under the null hypothesis that both models convert at the same rate, you pool the data:
- Pooled rate: p = (xA + xB) / (nA + nB)
- Standard error: SE = sqrt( p(1 - p)(1/nA + 1/nB) )
- Test statistic: z = (pB - pA) / SE, read against the standard normal distribution
Here is a worked example (invented numbers). The churn team planned 10,000 customers per arm and a two-sided significance level of 0.05.
| Quantity | Run 1: 10,000 per arm | Run 2: 2,000 per arm |
|---|---|---|
| Accepted, model A | 400 (4.0%) | 80 (4.0%) |
| Accepted, model B | 460 (4.6%) | 92 (4.6%) |
| Pooled rate p | 860 / 20,000 = 0.043 | 172 / 4,000 = 0.043 |
| p(1 - p) | 0.043 x 0.957 = 0.041151 | 0.041151 |
| 1/nA + 1/nB | 0.0002 | 0.001 |
| SE | sqrt(0.0000082302) = 0.00287 | sqrt(0.000041151) = 0.00641 |
| z = 0.006 / SE | 2.09 | 0.94 |
| Two-sided p-value | about 0.037 | about 0.35 |
| Decision at 0.05 | B is better: promote, subject to guardrails | No evidence of a difference: keep A or collect more data |
The observed lift is the same in both runs: 0.6 percentage points. Only the sample size changed. With five times fewer users per arm, the standard error grows by a factor of sqrt(5), about 2.24, so z shrinks by the same factor: 2.09 / 2.24 is about 0.94. A gap that looks like a win on a dashboard can be indistinguishable from chance. Run 2 doesn't show that the models are equal either. It only shows that the test was too small to tell them apart.
Two more rules keep A/B decisions honest. First, don't peek and stop early. Checking the p-value every day and stopping the first time it dips below 0.05 pushes the real false-positive rate well above 5 percent. Fix the sample size in advance, as Lesson 10 described. Second, set guardrail metrics alongside the primary metric: error rate, latency, complaint rate, or performance across protected groups. A model that wins on the primary metric but breaks a guardrail is not promoted.
Model performance monitoring: watching a model no one is changing
Go back to the churn model and the flex plan. What would have caught the problem in days rather than six weeks? Model performance monitoring: continuously comparing what a deployed model receives and produces with what it was validated on, and raising an alert when they diverge. Google's guide says that because models decay as data profiles change, you need to track summary statistics of your data and monitor the model's online performance. That lets you send notifications or roll back when values move away from what you expect.[1]
The documentation for Amazon SageMaker Model Monitor gives a useful checklist of four kinds of monitoring. Data quality watches for drift in the input data. Model quality watches for drift in metrics such as accuracy. Bias drift watches for growing bias in the model's predictions. Feature attribution drift watches for a change in which features drive the predictions. Add the operational signals that any web service needs (latency, error rate and throughput) and you have the full set.
The mechanism is a baseline plus constraints. You build a baseline from the dataset used to train the model. The baseline computes statistics and suggests constraints on them, and any live or batch predictions that fall outside those constraints are reported as violations.[9] Here is what a weekly report on the churn model might have shown (invented values):
| Check | Baseline constraint | Last 7 days | Status |
|---|---|---|---|
| Missing rate, tenure_months | At most 1.0% | 0.4% | OK |
| plan_type categories | monthly, annual | Adds "flex" (18% of rows) | Violation |
| monthly_charge range | 5 to 250 | 5 to 240 | OK |
| Share predicted to churn | 10% to 14% | 19% | Violation |
| p95 latency | At most 120 ms | 91 ms | OK |
| ROC-AUC on labeled cases | At least 0.82 | Labels not yet available | Pending |
The first violation would have flagged the flex plan in its first week. The second shows the model reacting to it. Look at the last row too. Model quality needs ground truth, meaning the actual outcome, and outcomes often arrive late. A churn label comes after the 30-day renewal window, and a loan default can take a year or more. Until labels arrive, input drift and prediction drift are your leading indicators. They don't prove the model is wrong. They show that it is now working on data unlike its training data, which is when it is most likely to be wrong. Two kinds of drift matter here. Data drift is a change in the distribution of the inputs. Concept drift is a change in the relationship between inputs and the outcome, which only labels can confirm. Amazon's Well-Architected guidance lists ignoring either one until performance falls badly as an anti-pattern.
A common single-number measure of input or score drift is the population stability index (PSI). Split a variable into bins. Let ei be the share of the baseline in bin i and ai the share of recent data in bin i. Then:
PSI = sum over bins of (ai - ei) x ln(ai / ei)
Every term is zero or positive, because ai - ei and ln(ai/ei) always have the same sign. Worked example: the training baseline puts 25% of churn scores in each of four bins, and last week's live scores fall 10%, 20%, 30% and 40%.
- Bin 1: (0.10 - 0.25) x ln(0.10/0.25) = (-0.15) x (-0.916) = 0.137
- Bin 2: (0.20 - 0.25) x ln(0.80) = (-0.05) x (-0.223) = 0.011
- Bin 3: (0.30 - 0.25) x ln(1.20) = 0.05 x 0.182 = 0.009
- Bin 4: (0.40 - 0.25) x ln(1.60) = 0.15 x 0.470 = 0.071
- Total: PSI = 0.228
Now change the input. If last week's shares were 22%, 26%, 27% and 25%, the terms would be 0.0038, 0.0004, 0.0015 and 0, for a PSI of about 0.006. Many teams treat a PSI below 0.1 as stable and above 0.25 as a major shift. Those cut-offs are an industry convention from credit scoring, not a statistical test. Set your own thresholds from the variable's history.
A note on how current tools are. Amazon's documentation now says that SageMaker Model Monitor is no longer open to new customers.[9] Its four kinds of monitoring are still a good checklist and other platforms offer the same functions, but tools come and go faster than certification objectives. Learn the functions (baseline, constraints, alerts, response), not a product name.
Monitoring is only worth having if an alert leads to action. The possible responses, roughly from cheapest to most expensive: fix an upstream data problem, roll back to the previous model, retrain on recent data through the continuous training pipeline, or redesign the features. A team that relies only on occasional manual checks of model performance has, in practice, no monitoring between those checks.
Remember: monitoring compares live inputs, predictions and (once labels arrive) quality metrics against a baseline taken from training. When labels are late, input and prediction drift are the early warning.
What would settle the dispute
Look back over the evidence. Position one is right that most of this lesson's machinery is shared. CI/CD, code isolation, virtualization, container orchestration and data replication would look the same for a payments API. Position two is right that a system can fail while all of that machinery works perfectly, as the flex plan showed. Only data tests, model gates, online validation and drift monitoring can see that kind of failure.
So the dispute is settled system by system, by an empirical question rather than by argument: when this system's outputs got worse, was a code or infrastructure change involved? A team can answer that from its own incident log by classifying each production incident over a quarter by root cause. The following reading of the result is this lesson's judgement, not a rule from any source. If nearly all incidents trace back to code, configuration or capacity, DevOps practice covers most of the risk, and a heavy MLOps stack would mostly add cost. If incidents trace back to data (new categories, shifted distributions, decay discovered late), the ML-specific practices are paying for themselves, and the faster the data moves, the stronger the case for continuous training and automated monitoring.
One catch makes this audit harder than it sounds. A team with no model performance monitoring will undercount data incidents, because silent decay that nobody detected never reaches the incident log. The six weeks of wasted discounts in the opening story would have shown up, if at all, as a disappointing quarter for marketing rather than as an engineering incident. Some monitoring has to exist before the question can be answered fairly.
For the exam, the verb in objective 4.6 is "explain the importance". Expect questions that describe a failure or a goal and ask which practice addresses it, so be able to name what each practice prevents.
Exam cues: what the stem says and where it points
| Words in the question | Points to | Commonly confused with |
|---|---|---|
| Works on laptop, fails on server; dependency or version conflict | Code isolation: pinned environment or container image | Monitoring, which only notices the failure afterward |
| Each instance needs its own operating system; different OS family | Virtual machine | Container, which shares the host kernel |
| Lightweight, starts quickly, packages app with dependencies | Container | Virtual machine |
| Keep N replicas running, restart failures, rolling update, scale | Container orchestration (Kubernetes) | CI/CD, which builds and tests but does not run replicas |
| Run step B only after step A finishes; pipeline as a graph | Workflow orchestration (DAG) | Container orchestration |
| Every commit triggers build and tests | Continuous integration | Continuous deployment |
| Passing changes reach production with no human approval | Continuous deployment | Continuous delivery, which waits for approval |
| Copy in another region, read replica, failover | Data replication | Backup, which is what restores a table deleted yesterday |
| Holdout set, beats the baseline or champion before release | Offline model validation | Online validation |
| Copy of live requests, users never see the new model's output | Shadow (mirrored) deployment | Canary |
| Small share of live traffic, watch errors, ready to roll back | Canary release | A/B test |
| Random split of users, compare conversion, statistical significance | Model A/B testing | Canary |
| Accuracy falling with no code change; drift; baseline constraints | Model performance monitoring | CI/CD, which only reacts to commits |
| Retrain automatically when new data arrives or drift is detected | Continuous training | Continuous integration |
Common misconceptions
- "Kubernetes is our CI/CD system." Kubernetes keeps containers in a declared desired state. Its own documentation says it does not build applications or deploy source code. A separate pipeline does that.
- "A container is a small virtual machine with its own operating system." Containers share the host's kernel, and a VM brings its own operating system. That is why a Linux host can't natively run a Windows container, and why container isolation is weaker.
- "Replicated data is backed-up data." Replication copies an accidental delete to every replica within seconds. Recovery needs a point-in-time backup or a versioned snapshot.
- "The model passed offline validation, so it is validated." An offline holdout comes from the past. Online validation through shadow, canary or A/B testing checks live behavior and real outcomes.
- "Canary releases and A/B tests are the same thing because both split traffic." A canary checks safety on a small, growing share. An A/B test measures which model is better, using a planned sample and a statistical decision rule.
- "If nobody changed the code, the model cannot have broken." Models decay when the data shifts, which is exactly the failure that code tests can't see.
Recap
- MLOps applies DevOps automation and monitoring to ML systems. What it adds is tests, triggers and monitors for data and model behavior, including continuous training, which retrains when new data arrives, on drift alerts, or on a schedule.
- Continuous integration builds and tests every change. Continuous deployment releases passing changes automatically, while continuous delivery waits for a person. ML pipelines add data tests, a model gate and a registry that records code, image and data versions together.
- Code isolation runs each project or component with pinned, declared dependencies. The levels are a virtual environment, a container image and a VM, and isolation only reproduces a run if the versions are pinned.
- A VM runs its own operating system on a hypervisor. A container shares the host kernel and packages the application with its dependencies; NIST SP 800-190 calls this operating system virtualization combined with application packaging.
- Kubernetes is container orchestration: it keeps a declared desired state, restarts failures, balances load and performs rolling updates and rollbacks. It does not build code, and it is different from workflow orchestration of a pipeline DAG.
- Data replication keeps live copies in sync. Asynchronous replicas lag behind the primary, which can cause training/serving skew in short-window features, and replication is not a backup.
- Offline validation compares a candidate with a baseline on a holdout set, including segment slices and latency. Online validation uses shadow deployment (no user impact, no outcomes), canary releases (safety) and A/B tests (which model is better).
- In an A/B test, the same lift from 4.0% to 4.6% is significant with 10,000 users per arm (z about 2.09, p about 0.037) but not with 2,000 per arm (z about 0.94, p about 0.35). Fix the sample size in advance and enforce guardrail metrics.
- Model performance monitoring checks data quality, model quality, bias drift and feature attribution drift against constraints taken from a training baseline. When labels are late, input drift and prediction drift (measured, for example, with PSI) are the early warning.
Sources
- Google Cloud Architecture Center. (n.d.). MLOps: Continuous delivery and automation pipelines in machine learning. docs.cloud.google.com
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Amazon Web Services. (n.d.). MLPERF06-BP04 Machine Learning Lens (Well-Architected). docs.aws.amazon.com
- Google Cloud Architecture Center. (n.d.). Architecture for MLOps using TFX, Kubeflow Pipelines, and Cloud Build. docs.cloud.google.com
- Murugiah Souppaya, John Morello, Karen Scarfone. (2017). SP 800-190, Application Container Security Guide. NIST. csrc.nist.gov
- The Kubernetes Authors / Cloud Native Computing Foundation. (n.d.). Kubernetes Overview. kubernetes.io
- Microsoft Learn. (n.d.). Perform safe rollout of new deployments for real-time inference. learn.microsoft.com
- Amazon Web Services (AWS Machine Learning Blog). (n.d.). Deploy shadow ML models in Amazon SageMaker. aws.amazon.com
- Amazon Web Services. (n.d.). Data and model quality monitoring with Amazon SageMaker Model Monitor. docs.aws.amazon.com
- Key terms
- MLOps
- Machine Learning Operations: applying DevOps automation and monitoring to ML systems, plus ML-specific practices such as data validation, model validation, continuous training and drift monitoring.
- CI/CD pipeline
- An automated sequence of stages that builds and tests every code change (continuous integration) and releases passing changes, either automatically (continuous deployment) or after approval (continuous delivery).
- Code isolation
- Running each project or pipeline step with its own pinned dependencies in a virtual environment, container image or virtual machine, so that results do not depend on whatever is installed on the host.
- Virtualization
- Software presenting physical resources as isolated virtual ones: a hypervisor runs virtual machines that each have their own operating system, while containers virtualize the operating system view and share the host kernel.
- Container orchestration
- Automated placement, scaling, restarting, load balancing and rolling update of many containers across machines to keep a declared desired state, as done by Kubernetes.
- Data replication
- Keeping synchronized copies of the same data on several machines or sites for availability, read scaling and disaster recovery; asynchronous replicas lag behind the primary, and replication copies mistakes as well as data.
- Model validation
- Confirming that a model is fit to serve: offline, by beating a baseline on held-out data before release; online, by checking its behavior and outcomes on live traffic through shadow, canary or A/B testing.
- Shadow deployment
- Running a new model alongside the current one on copies of live requests and discarding its outputs, so its latency and predictions can be measured without affecting users.
- Model A/B testing
- Randomly assigning users to the current or candidate model for a planned sample and comparing a business outcome with a statistical test before promoting the candidate.
- Model performance monitoring
- Continuously comparing a deployed model's inputs, predictions and quality metrics with constraints from a training baseline, and alerting when they drift so the team can investigate, roll back or retrain.
Deployment Environments Compared
- Sort containerization, cluster, on-premises, cloud, hybrid and edge deployment by the question each one answers: how the model is packaged, how many machines work together, or where the hardware sits and who runs it.
- Choose a deployment environment for a model from evidence about latency, bandwidth, connectivity, data residency, utilization and cost.
- Calculate a rent-versus-own break-even and an edge latency budget, and show how changing one input reverses the decision.
- Explain how container images and Kubernetes clusters carry one model across on-premises, cloud and edge environments.
A rack that arrives by truck
Amazon Web Services (AWS) sells a product called AWS Outposts. It runs AWS infrastructure and services on premises, inside the customer's own building, and Amazon markets it as "a consistent hybrid experience."[1] One form of Outposts is an industry-standard 42U rack filled with rack-mountable servers and switches. A U, or rack unit, is 1.75 inches of height.[2] The customer's staff can walk up to the rack and read the serial numbers. Even so, AWS operates, monitors and manages that capacity as part of one of its cloud regions.[2]
Suppose your fraud model is served from that rack. Is that an on-premises deployment, a cloud deployment or a hybrid one? The answer depends on which question you ask. Who owns the hardware? Where does it stand? Who operates it? This lesson teaches you to keep those questions apart. The rack gets its verdict in the hybrid section, once all six environments have been covered. The six deployment environments in the objective look like six rival choices. In fact they answer different questions, and most real systems combine several of them.
Lesson 23 built the pipeline that tests a model and ships it. This lesson asks where the shipped model ends up, and what that location costs you in latency, money, control and engineering effort.
Exam objectives: 4.7 Compare and contrast various deployment environments: containerization, cloud deployment, cluster deployment, hybrid deployment, edge deployment and on-premises deployment.[3]
Three questions hiding behind six bullets
Read the bullets again and sort them by what each one describes.
| Question | Bullet that answers it | What it is chosen instead of |
|---|---|---|
| How is the model packaged so it runs the same way everywhere? | Containerization | Installing libraries by hand on each host, or shipping a whole virtual machine image |
| How many machines work together to run it? | Cluster deployment | A single server or a single device |
| Where does the hardware sit, and who operates it? | On-premises, cloud, hybrid, edge | Each other: these four are alternatives to one another |
A production system answers all three questions. A typical line from an architecture review covers them all at once: a containerized scoring service, running on a Kubernetes cluster, in a hybrid deployment that keeps customer records in the company's data center. Exam questions work differently. They usually turn on one dominant requirement in the stem, such as a latency deadline, a data residency rule or a library conflict, and that requirement points to one bullet.
The table below compares all six. Every row has the same columns, so you can read across.
| Environment | What defines it | Who runs the hardware | Typical data science use | Main strength | Typical trouble |
|---|---|---|---|---|---|
| Containerization | Model, runtime and libraries packaged into one image | Whoever runs the host | Making a model behave the same from laptop to production | Same behavior on every host | Bloated images; mismatch with the host's Graphics Processing Unit (GPU) driver |
| On-premises | Hardware in a facility the organization controls | The organization | Sensitive data, steady GPU load, data already stored locally | Full control; no hourly bill | Fixed capacity; slow to grow; staff burden |
| Cloud | Resources rented on demand from a provider's shared pool | The provider | Bursty training, managed endpoints, fast experiments | Capacity that grows and shrinks on demand; pay per use | Runaway bills, data transfer charges, residency limits |
| Cluster | Many machines coordinated as one system | The organization or a provider | Distributed training, replicated serving, large batch jobs | Scale and fault tolerance | Hard to operate; overkill for small loads |
| Hybrid | Two or more environments joined so data and applications can move between them | Both | Data kept local, extra compute rented from the cloud | Each workload runs where it fits best | Two environments to secure, connect and operate |
| Edge | Compute on or next to the device that produces the data | The organization, across many remote devices | Real-time inference on cameras, sensors and vehicles | Low latency; keeps working offline | Small hardware; a fleet that is hard to update and monitor |
In short: containerization is about packaging. Cluster deployment is about how many machines share the work. On-premises, cloud, hybrid and edge say where the hardware lives and who runs it. That is why one system can be all three at once.
Containerization: shipping the model with its whole world
Picture a churn model that reaches an Area Under the Curve (AUC) of 0.91 in a data scientist's notebook and then crashes in production with an import error. The model is rarely the cause. The production server has a different Python minor version, or an older NumPy, or it lacks a compiled system library that one package quietly needed. Containerization prevents this kind of failure. It packages the application with everything it needs outside the operating system kernel: the language runtime, the pinned libraries, the system libraries, the model file and the command that starts the service.
Two terms need separating. A container image is the packaged, read-only template: a stack of filesystem layers plus metadata that says what to run. A container is a running instance of an image, which is a process on a host. One image can start a hundred identical containers. Docker made the format popular. Kubernetes and most cloud services run the same images through container runtimes such as containerd.
The way containers work explains both their strengths and their limits. A container is not a small virtual machine (VM). It is an ordinary process on the host's Linux kernel, and the kernel fences it off in two ways. Namespaces give the process its own view of process IDs, network interfaces, hostnames and filesystem mounts, so it behaves as if it had the machine to itself. Control groups (cgroups) cap how much processor time and memory it can use. Every container shares the host's kernel, so no guest operating system has to boot. A container starts in about the time its own program needs to start, and a host can fit many more containers than VMs. On Windows and macOS, Docker Desktop runs Linux containers inside a lightweight Linux VM. On Windows this is usually WSL 2, the Windows Subsystem for Linux.
| Feature | Virtual machine | Container |
|---|---|---|
| What is virtualized | The hardware, by a hypervisor | The process's view of the operating system, through kernel namespaces |
| Operating system | Each VM boots its own guest operating system and kernel | Shares the host kernel; the image carries only user-space files |
| Typical size | Gigabytes, including a full operating system | Megabytes to a few gigabytes, mostly libraries |
| Start time | An operating system boot | About the time the application needs to start |
| Isolation | Strong boundary at the hypervisor | Weaker: a kernel flaw can expose every container on the host |
| GPU access | Pass-through or virtual GPU set up on the hypervisor | The host's driver is exposed to the container; the image carries the user-space libraries of CUDA (NVIDIA's Compute Unified Device Architecture, its platform for programming GPUs) |
Here is a container definition. The file below is a Dockerfile, an illustrative example for a small scoring service. Each instruction adds a layer to the image.
# Illustrative Dockerfile for a churn-scoring API
FROM python:3.11-slim
WORKDIR /app
# 1. Dependencies first: this layer is reused until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 2. Model and code last: they change most often
COPY model/churn_v7.onnx model/
COPY serve.py .
EXPOSE 8080
CMD ["python", "serve.py"]
# requirements.txt (exact versions pinned; illustrative)
numpy==1.26.4
onnxruntime==1.17.1
fastapi==0.110.0
uvicorn==0.29.0
Read it from the top. FROM names a base image. pip, the Preferred Installer Program, installs the exact versions listed in requirements.txt, so a rebuild next year gets the same libraries. The order of the steps matters. The build tool caches each layer and reuses it until that layer's inputs change. The slow-changing requirements are copied before the fast-changing code, so a one-line fix to serve.py rebuilds in seconds instead of reinstalling every library.
Containers matter in every other environment in this lesson because they move between them. Microsoft's end-to-end tutorial for Internet of Things (IoT) devices wraps a trained model in a web service and packages that service in a Docker container. It notes that the container can then be deployed either in the cloud or as an IoT Edge module.[4] Azure IoT Edge is Microsoft's software for running containerized modules on field devices. A companion Microsoft guide warns about size. An IoT Edge module image for artificial intelligence (AI) work is typically at least 1 gigabyte (GB), which is a lot to push through a narrow network link.[5]
Five things commonly go wrong:
- Unpinned versions. If the base image is tagged latest, or a library has no pinned version, two builds of the "same" Dockerfile can differ. Pin the base image tag and every library version. Record the image's content digest (a hash that identifies the exact image) next to the model version.
- GPU driver mismatch. The kernel is shared, so the GPU driver lives on the host, not in the image. The image carries the CUDA libraries, and they must be compatible with the host's driver. A CUDA image that runs on a new workstation can fail on a server with an older driver.
- Lost writes. A container's writable layer disappears when the container is replaced. Logs, stored predictions and downloaded models that must survive belong on a mounted volume or in external storage.
- Secrets in layers. An API key copied into an image stays in that layer even if a later instruction deletes the file. Pass secrets in when the container starts instead.
- Bloat. Images that include a full GPU framework run to several gigabytes. Slim base images help, and so do multi-stage builds, which compile in one stage and copy only the results into a smaller final stage. Smaller images download faster to every node and device.
In short: containerization packages a model with its runtime, so it behaves the same on a laptop, a cluster node or an edge gateway. It shares the host kernel, so it is light and starts fast, but it cannot bring its own kernel or GPU driver.
On-premises deployment: your building, your hardware, your on-call rota
In an on-premises deployment, the organization runs the model on hardware it owns or leases, in a facility it controls, such as its own data center or server room. The organization is responsible for everything: power and cooling, the operating system, GPU drivers, the network and the model server.
Some cases sit on the border. An organization that rents cage space in a third-party colocation facility owns and runs its own servers, but another company runs the building. People describe that arrangement in different ways, so do not build an exam answer on it. The test that settles most cases is who controls the hardware and the facility. On the exam, the cue for on premises is usually "our own data center" or "our server room".
Why keep doing this when the cloud exists? AWS's own prescriptive guidance is written to win cloud customers, yet it concedes that some applications must stay on premises. The reasons it gives are the low latency and local data processing of the on-premises environment, avoiding high data transfer costs, and regulatory compliance.[6] Each reason has a data science version:
- Data gravity. A 2-petabyte archive of seismic surveys or medical images already sits on local storage. Moving the model to the data is cheaper than moving the data to the model.
- Regulation and contracts. Personally Identifiable Information (PII), health records or defense data may be bound by law or contract to stay in a specific facility.
- Steady, heavy load. A GPU server that is busy 20 hours a day costs less to own than to rent, as the worked example below shows.
- Links to local systems. A model that scores transactions inside a mainframe workflow, or controls equipment on a plant network, may need to sit on that network with no internet path at all.
The costs are just as concrete. Capacity is fixed. When four teams want the same eight GPUs in the same week, someone waits. Growing means buying, shipping, racking and testing hardware, which takes weeks or months rather than minutes. The organization also does all the upkeep: patching systems, replacing failed disks, upgrading drivers, and planning for the day the cooling fails.
One trap deserves a name now: "on premises" and "private cloud" do not mean the same thing. The US National Institute of Standards and Technology (NIST) defines a private cloud as cloud infrastructure provisioned for the exclusive use of a single organization.[7] NIST adds that a private cloud may be owned and run by that organization, by a third party or by both, and that it may exist on or off premises.[7] A company that runs a self-service computing platform on its own servers has an on-premises private cloud. A company that rents dedicated single-tenant hardware, run by a provider in the provider's building, has an off-premises private cloud. To decide whether something is on premises, ask where the hardware sits and who controls it. Whether it is called a cloud does not settle the question.
Cloud deployment and the NIST definition
The standard definition comes from NIST Special Publication 800-145, written by Peter Mell and Timothy Grance in 2011. It defines cloud computing as a model for convenient, on-demand network access to a shared pool of configurable computing resources.[7] Those resources can be provisioned and released quickly with little management effort. The model has five essential characteristics, three service models and four deployment models.[7]
Learn the five characteristics by name, because each one changes how a data scientist works.
| Characteristic | What it means | What it changes for data science |
|---|---|---|
| On-demand self-service | You provision capacity yourself, without a request handled by the provider's staff | A GPU instance is ready minutes after you ask for it |
| Broad network access | Capabilities are reached over the network from many kinds of client | Notebooks, pipelines and apps all call the same endpoints |
| Resource pooling | The provider serves many customers from shared hardware | Your workload may share hardware with other customers; keeping them separate is the provider's job |
| Rapid elasticity | Capacity scales out and back in, often automatically | 64 GPUs for a weekend search, none on Monday |
| Measured service | Usage is metered, and you are billed for it | Every idle GPU hour appears on an invoice |
The three service models trade control for convenience. In Infrastructure as a Service (IaaS), the provider runs the underlying infrastructure, and you control the operating systems, storage and deployed applications. In Platform as a Service (PaaS), the provider also runs the servers, operating systems and storage. You control your deployed applications and perhaps some settings of the hosting environment. Software as a Service (SaaS) gives you a finished application.
| Service model | Data science example | Trade-off |
|---|---|---|
| IaaS | Rent a GPU virtual machine, then install drivers, CUDA and your own serving stack | Most control; you patch everything |
| PaaS | Submit a managed training job, or deploy a model to a managed endpoint that scales itself | Less work; you accept the platform's frameworks and limits |
| SaaS | Use a hosted analytics or automated machine learning product through its own interface | Least work; least control over the model |
NIST names four deployment models. When people say "cloud deployment" they almost always mean the public cloud, which is infrastructure open to use by the general public and located on the provider's premises. The other three are private cloud, community cloud (shared by organizations with common concerns such as compliance) and hybrid cloud, which has its own section below.
For data science, the characteristic that matters most is elasticity, because training runs and hyperparameter searches come in spikes. A team can rent 64 GPUs on Friday, run a search over the weekend and release them all on Monday. It buys nothing and waits for no delivery.
Cloud deployments fail in their own ways. A GPU instance left running after an experiment bills every hour. Moving large datasets out of a provider usually incurs data transfer (egress) charges. Data residency rules may require a particular country or region. Security is shared: the provider secures its facilities and hardware, and you still secure your identities, data and endpoints. Managed machine learning platforms also differ between providers, so moving a pipeline from one to another can be costly. Containers and open model formats such as ONNX, the Open Neural Network Exchange, reduce that lock-in.
In short: cloud deployment rents elastic, metered capacity from a provider's shared pool. IaaS, PaaS and SaaS give up control in exchange for convenience. The bill follows usage, which suits bursty work and punishes forgotten resources.
Worked example: renting versus owning GPU capacity
The prices below are made-up round numbers chosen to keep the arithmetic clear. Real prices depend on the provider, region, GPU model and contract, and they change often. The method is what you should take away.
A research team needs an 8-GPU server for training. Option A is to buy one for the company data center. Option B is to rent an equivalent cloud instance by the hour.
| Cost item (illustrative) | Option A: own (on-premises) | Option B: rent (cloud) |
|---|---|---|
| Hardware | $216,000 spread over 36 months = $6,000 per month | None |
| Power, cooling and rack space | $700 per month | Included in the rate |
| Share of an engineer's time for upkeep | $1,300 per month | Small; the provider maintains the hardware |
| Usage charge | None | $32 per hour while running |
| Monthly total | $8,000, fixed, whether used or not | $32 times the hours used |
Step 1: find the break-even point. Owning costs a fixed $8,000 a month. Renting costs $32 for each hour. The two cost the same when 32 × hours = 8,000, so the break-even is 8,000 / 32 = 250 hours a month. A month has about 730 hours, so 250 hours means the server is busy about 34 percent of the time.
Step 2, first run: training in bursts. The team trains around the clock for two weeks each quarter. That is 14 × 24 = 336 hours a quarter, or 112 hours a month on average. Renting costs 112 × $32 = $3,584 a month, against $8,000 for owning. Renting is cheaper by $4,416 a month. An owned server would sit idle 1 − 112/730, or about 85 percent, of the time.
Step 3, second run: one input changes. The model goes into production. The same server now handles real-time inference around the clock, with retraining every night: 730 hours a month. Renting now costs 730 × $32 = $23,360 a month, while owning still costs $8,000. Owning is cheaper by $15,360 a month, almost a factor of three.
Only utilization changed, and the decision reversed. That is the general rule: renting versus owning comes down to how busy the hardware will be. Two refinements belong in a real analysis. First, cloud providers discount committed use, through reserved capacity or savings plans, and a lower hourly rate pushes the break-even point higher. Second, buying hardware takes weeks to months, so a team that needs GPUs next Tuesday may rent regardless of the arithmetic. The common compromise is to own the steady baseline and rent the peaks, which is a hybrid design.
In short: break-even hours equal the fixed monthly cost of owning divided by the hourly rental rate. Below that number, rent. Above it, own. Owning the base load and renting the peaks gives you a hybrid deployment.
Cluster deployment and Kubernetes
A computer cluster is a group of networked machines, called nodes, that work together under shared software so they can be managed and used as one system. Data scientists meet clusters for two different reasons, and it helps to keep them apart.
- Scale-out. The job is too big for one machine: a Spark job over terabytes, training spread across many GPUs, or a hyperparameter search of 400 configurations run 40 at a time. In data-parallel training, each GPU holds a copy of the model and processes its own slice of every batch. The gradients are averaged across GPUs before each weight update. That averaging takes network time, so 8 GPUs rarely run exactly 8 times faster than one.
- Availability. The job is small, but it must not stop. Three copies of a scoring service on three nodes keep serving when one node dies.
Traditional High-performance Computing (HPC) clusters, common in universities and research labs, run batch jobs through a scheduler such as Slurm. For serving models and for mixed workloads, the main cluster platform is Kubernetes, an open-source system for running containers across many machines. Its documentation describes a cluster as a control plane plus a set of worker machines, called nodes, that run containerized applications.[8] The control plane makes cluster-wide decisions, such as where to place work, and manages the nodes and the Pods. A Pod is the smallest unit Kubernetes schedules: one or more containers that share a network address. On every node, an agent called the kubelet makes sure the containers assigned to that node are running in their Pods.[8] In production, the control plane usually runs on several machines and the cluster has several nodes. That redundancy is where the fault tolerance comes from.
You do not tell Kubernetes what to do step by step. You declare the state you want, in a file usually written in YAML (YAML Ain't Markup Language), and the control plane keeps working until the cluster matches it. The illustrative declaration below asks for three identical replicas of the churn service built earlier. For each one it reserves half a Central Processing Unit (CPU) core and 1 gibibyte of memory, and it caps memory at 2 gibibytes.
# Illustrative Kubernetes Deployment for the churn scorer
apiVersion: apps/v1
kind: Deployment
metadata:
name: churn-scorer
spec:
replicas: 3 # desired number of identical Pods
selector:
matchLabels:
app: churn-scorer
template:
metadata:
labels:
app: churn-scorer
spec:
containers:
- name: scorer
image: registry.example.com/churn-scorer:1.4.2 # the image built earlier
ports:
- containerPort: 8080
resources:
requests: # what the scheduler reserves on a node
cpu: "500m" # half a CPU core
memory: "1Gi"
limits:
memory: "2Gi" # exceed this and the container is killed
Now suppose one node loses power. Once the cluster has noticed that the node is gone, you list the Pods with kubectl, the Kubernetes command-line tool. The output looks something like this (illustrative and simplified):
$ kubectl get pods -l app=churn-scorer
NAME READY STATUS RESTARTS AGE
churn-scorer-7d9f8c6b5-2xkqp 1/1 Running 0 3h
churn-scorer-7d9f8c6b5-8mzt4 1/1 Running 1 3h
churn-scorer-7d9f8c6b5-qw7rn 1/1 Running 0 4m
The 4-minute-old Pod is the replacement. The control plane saw fewer running Pods than the three declared, so it scheduled a new one on a healthy node. Nobody was paged. The listing is simplified. In a real cluster, the Pod from the dead node can stay listed for a while with a status of Terminating or Unknown until the cluster finishes cleaning up after that node. That Pod is not serving traffic. GPUs are handled the same way. A Pod requests a GPU as a resource (for NVIDIA cards, nvidia.com/gpu: 1, provided through a device plugin), and the scheduler places it only on a node with a free GPU.
A cluster does not say where it runs. Cloud providers offer managed Kubernetes services that run the control plane for you. If you run Kubernetes on your own premises, or on your own PC for learning, the cluster simply has no cloud controller manager. That is the component that talks to a cloud provider's Application Programming Interface (API).[8] A cluster can therefore be on premises, in the cloud, or spread across both.
Clusters fail in their own ways. They are overkill for a single small model that one server could handle, because the cluster's own components need care too. If memory requests and limits are set too low, containers are killed for exceeding them. If they are set too high, expensive nodes sit half empty. GPUs can end up scattered, with one free on each of four nodes while a job that needs four on one node waits. Stateful components such as databases and feature stores need more care than stateless scorers.
In short: a cluster makes many machines act as one, either for scale-out or for availability. Kubernetes does this by comparing the state you declared with the actual state and fixing any difference. A cluster can run in any location.
Hybrid deployment: two environments bound together
NIST defines a hybrid cloud as a composition of two or more distinct cloud infrastructures (private, community or public) that remain separate entities.[7] What binds them is technology that lets data and applications move between them. NIST's own example is cloud bursting for load balancing between clouds.[7] In everyday use, a hybrid deployment means an organization's own on-premises or private environment working with a public cloud. Using two public providers together is usually called multicloud.
Cloud bursting means running a workload on your own capacity normally and sending the overflow to a public cloud when demand exceeds that capacity. The break-even example showed why bursting is attractive. You own the hardware that stays busy and rent only the hardware that would otherwise sit idle.
The rules about data usually decide what stays local. AWS describes hybrid designs that store data in a specific country, state or municipality to meet security and tax regulations and data sovereignty rules.[1] Size matters too: a dataset too large to copy cheaply tends to stay where it is, and the compute comes to it. Four hybrid patterns come up often in data science:
| Pattern | What stays local | What goes to the cloud | Why split it |
|---|---|---|---|
| Train in the cloud, serve locally | Live scoring next to the transaction system | Training on de-identified or synthetic data | Elastic GPUs for training; low latency and control for serving |
| Keep data home, burst compute | Raw customer records and baseline scoring | Extra scoring capacity for seasonal peaks | Residency rules plus spiky demand |
| Local hot data, cloud archive | Recent data used every day | Older history and backups | Cheap long-term storage; disaster recovery |
| Edge plus cloud | Real-time inference on devices | Fleet data for retraining and monitoring | Speed at the device, heavy compute in the cloud |
The main engineering goal is consistency: the same image, configuration and pipeline should run on both sides. Providers sell tools for exactly this, including Kubernetes distributions that run on your own servers with the same tooling as their cloud. Containers do the same job at a smaller scale. The image that serves on premises is the same image that bursts to the cloud.
Now return to the Outposts rack from the opening and ask the three questions in turn. Where does the hardware sit? In the customer's building, so on premises. Who operates it? AWS, as part of one of its cloud regions. How is the fraud model packaged? Probably as a container, but that is a separate question. The rack is on-premises hardware run as an extension of a public cloud region, with that region's services and tools. The whole arrangement is therefore best described as a hybrid deployment, which is also how Amazon sells it. On an exam, a stem that says "the data must stay in our building, but we want the same services and tools as our cloud" points to hybrid, not to on premises alone.
The hard part of hybrid is the join between the two sides. You need a secure network link, either a virtual private network (VPN) or a dedicated circuit, and its bandwidth limits how much data can cross it. Identities and permissions must work on both sides. Model versions can drift apart, with version 7 serving on premises while version 8 serves in the cloud. Data leaving the provider incurs transfer charges. Every design also needs an answer to one question: what happens when the link between the sites goes down?
In short: hybrid deployment joins separate environments so that data and applications can move between them. Data rules usually decide what stays local, and utilization decides what is rented. The link between the sites is both what makes it work and the part most likely to break.
Edge deployment: inference where the data is born
Edge computing places computation on or next to the device that produces the data: a camera on a production line, a controller in a wind turbine, a phone, a vehicle, a gateway in a shop. In data science, edge deployment almost always means running inference there. Training usually happens elsewhere. Typical edge models classify images, detect objects or flag anomalies in sensor signals.
Four forces push a model to the edge:
- Latency. Light in optical fiber covers roughly 200 km per millisecond. A server 1,000 km away therefore costs at least 10 milliseconds (ms) for the round trip, before any routing, queuing or inference. A decision needed within a few milliseconds cannot wait for that.
- Bandwidth. If a camera produces far more data than the site's uplink can carry, the data has to be processed locally. You then send results instead of raw frames.
- Connectivity. Turbines, offshore platforms and pipelines often sit far from reliable networks. Microsoft's guide notes that some IoT devices connect only at scheduled hourly, daily or weekly times, to save power or reduce network traffic.[5] A model that needs the cloud for every prediction stops working whenever the link is down.
- Privacy. Raw video or audio that never leaves the device is never exposed in transit or in central storage.
Edge hardware is small. It has limited memory, limited power and at best a modest accelerator, so models are usually shrunk before deployment. Quantization stores weights as 8-bit integers instead of 32-bit floating-point numbers. That makes the model about four times smaller and often faster. The cost is usually a small loss of accuracy, which you must measure. Pruning removes weights that contribute little. Knowledge distillation trains a small "student" model to imitate a large one. The shrunken model is then exported to a portable runtime format such as ONNX or LiteRT, the runtime formerly called TensorFlow Lite.
Updating a fleet is where edge deployment differs most from the other environments. Recall that AI module images can be 1 GB or more. Microsoft's edge inference design does not resend the whole image for every model change. Instead, you upload the new model version to cloud storage and sync the device configuration again, which gives an incremental update.[5] The container stays the same and only the model file changes. This is the containerization idea applied again: code that rarely changes and a model that often changes travel separately.
Edge deployment rarely means "no cloud". In most designs the model is trained centrally. In Microsoft's predictive maintenance tutorial, data collected after deployment is used to retrain and refine the model, which is then redeployed to IoT Edge.[4] Edge also covers more than one place. It can mean the device itself, a gateway on the site, or the network edge, which is compute placed inside a telecom operator's network close to users. (The Atlas Network+ course covers latency and round-trip time in detail.)
How is edge different from on premises? An on-premises deployment uses a data center or server room: a few large machines, with technical staff nearby. An edge deployment uses many small, often unattended devices in the field, next to the sensors. A server in a factory's server room that runs a model for the production line could be called either. On the exam, the cue decides. "On the device", "near the sensor", "intermittent connectivity" and "milliseconds" point to edge. "Our data center", "existing servers" and "data must not leave the building" point to on premises.
Edge models are hard to monitor. Each site can drift differently, because a camera in a dusty plant does not see what a camera in a clean one sees. Telemetry arrives late or in batches. Different devices end up running different model versions. Someone can physically tamper with the hardware. Lesson 13's drift checks still apply, but the evidence arrives from hundreds of devices, often hours late.
In short: edge deployment runs inference next to the data when latency, bandwidth, connectivity or privacy rule out a round trip. Edge models are compressed for small hardware, updated incrementally, and usually retrained in the cloud.
Worked example: where should the defect detector run?
This scenario is made up, but each number is the kind you would measure on site. A bottling plant photographs every bottle as it passes a gate on the conveyor. The model must decide "reject" or "pass" in time to fire an air jet that pushes bad bottles off the line.
| Measurement (illustrative) | Value |
|---|---|
| Camera rate | 30 images per second |
| Image size (grayscale crop) | 100 kilobytes (KB) = 0.8 megabits |
| Share of bottles rejected | About 1 percent |
| Deadline from capture to decision | 60 ms |
| Plant uplink to the internet | 50 megabits per second (Mbps) |
| Measured round trip to the nearest cloud region | 45 ms |
| Inference time on a cloud GPU | 20 ms |
| Inference time on a small GPU box beside the line | 25 ms |
Step 1: bandwidth. 30 images a second × 0.8 megabits = 24 Mbps. The uplink carries 50 Mbps, so the camera alone would use 48 percent of it. It fits, but with little room for anything else.
Step 2: cloud latency. Sending one image takes 0.8 / 50 = 0.016 s = 16 ms. Add the 45 ms round trip and 20 ms of inference: 16 + 45 + 20 = 81 ms. The deadline is 60 ms, so the cloud path misses it by 21 ms on an average frame. Variation in network delay (jitter) will make some frames worse.
Step 3: edge latency. 25 ms of inference plus a few milliseconds on the local network gives about 30 ms. That is well inside 60 ms.
Decision. Inference runs at the edge. The cloud is still useful. Suppose the plant uploads only the rejected images (about 1 percent of frames) plus a 1 percent random sample, about 2 percent of frames in total. That needs roughly 0.02 × 24 = 0.48 Mbps. It fits the uplink easily, and it gives the cloud enough data for retraining and drift monitoring. The full design is edge inference with cloud training, which is the hybrid edge-plus-cloud pattern.
Second run: change one input. The engineers move the air jet further down the conveyor. The deadline becomes 250 ms, and nothing else changes. The cloud path still takes 81 ms, which now leaves 169 ms of margin. Latency no longer forces the decision, so other factors decide. The cloud avoids maintaining GPU hardware on the plant floor. The edge keeps the line running if the uplink fails, and it frees almost half the plant's bandwidth. A reasonable team could pick either. If it picks the cloud, it must decide what happens when the link drops, for example sending every bottle to manual inspection.
One changed number turned "must be edge" into "either can work, so decide on cost and resilience". The method generalizes. Write down the deadline, add up every delay on each path, and compare the data rate with the link. Only then talk about preferences.
Exam cues: what the stem says and where it points
| Words in the question stem | Points to | Commonly confused with |
|---|---|---|
| "Works on my machine", dependency conflict, reproducible environment, same artifact in development and production | Containerization | Cluster deployment: more machines do not fix a missing library |
| Our own data center or server room, data cannot leave the building, steady around-the-clock load, full control of hardware | On-premises deployment | Private cloud, which may be off premises |
| Needed for a few days, pay only for use, no capital purchase, managed endpoint, scales automatically | Cloud deployment | Cluster deployment, which can be on premises |
| Distributed training, many nodes, replicas, self-healing, orchestration, Kubernetes, scheduler | Cluster deployment | Cloud deployment: location is a separate question |
| Burst to the cloud at peaks, data stays local but compute expands, same tooling in both places, data residency plus scale | Hybrid deployment | Multicloud, which means two public providers |
| Milliseconds at the sensor, intermittent or no connectivity, camera, vehicle or turbine, uplink too small for raw data | Edge deployment | On-premises deployment, which uses a data center rather than the device |
Common misconceptions
- "Containers and the cloud are alternatives." They answer different questions. A container is a packaging format, and the cloud is a location. The same image runs on premises, in the cloud and at the edge.
- "A container is a lightweight virtual machine with its own operating system." A container is a fenced-off process that shares the host's kernel. That is why it starts fast. It is also why it cannot bring its own GPU driver, and why it is a weaker security boundary than a VM.
- "Private cloud means on premises." NIST allows a private cloud to be run by a third party and to sit on or off premises. On premises describes where the hardware is and who controls it.
- "A cluster deployment is a cloud deployment." Kubernetes runs on your own servers, and even on a laptop, with no cloud provider involved. A cluster describes how many machines cooperate, not where they are.
- "The cloud is always cheaper." It is cheaper for bursty work or low utilization. Once usage passes the break-even hours, owning busy hardware usually wins.
- "Edge deployment means no cloud." Most edge designs still train, store fleet data and push model updates through the cloud. Only the time-critical inference moves to the device.
What to carry forward
- Containerization answers how a model is packaged. Cluster deployment answers how many machines cooperate. On-premises, cloud, hybrid and edge answer where the hardware sits and who runs it.
- A container shares the host's operating system kernel. It is small and starts fast, but the GPU driver must come from the host and must be compatible with the image's CUDA libraries.
- In a Dockerfile, put slow-changing dependencies before fast-changing code so that cached layers make rebuilds fast. Pin every version.
- NIST SP 800-145 defines cloud computing through five essential characteristics (on-demand self-service, broad network access, resource pooling, rapid elasticity, measured service), three service models (IaaS, PaaS, SaaS) and four deployment models (public, private, community, hybrid).
- A private cloud may sit on or off premises, so "private cloud" and "on premises" are not synonyms.
- Rent-versus-own break-even hours = fixed monthly cost of owning / hourly rental rate. Rent below that number and own above it.
- A Kubernetes cluster is a control plane plus worker nodes. You declare the desired state, such as three replicas, and the control plane replaces Pods that fail.
- Hybrid deployment joins separate environments so that data and applications can move between them. Cloud bursting is the classic example, and data residency rules usually decide what stays local. Cloud-run hardware installed on premises, such as AWS Outposts, is a hybrid deployment.
- Edge deployment runs inference next to the data source when latency, bandwidth, connectivity or privacy rule out a round trip. Edge models are compressed, updated incrementally and usually retrained in the cloud.
Sources
- Amazon Web Services. (2020). Hybrid Cloud with AWS. docs.aws.amazon.com
- Amazon Web Services. (2020). Hybrid cloud use cases - Hybrid Cloud with AWS. docs.aws.amazon.com
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Microsoft Learn. (n.d.). Deploy AI and ML computing on-premises and to the edge. learn.microsoft.com
- Microsoft Learn. (n.d.). Machine learning inference on IoT Edge devices. learn.microsoft.com
- Amazon Web Services. (n.d.). Hybrid cloud best practices. docs.aws.amazon.com
- Peter Mell, Timothy Grance. (2011). The NIST Definition of Cloud Computing (SP 800-145). NIST. nvlpubs.nist.gov
- Kubernetes (The Linux Foundation). (n.d.). Cluster Architecture. kubernetes.io
- Key terms
- Containerization
- Packaging an application with its runtime, libraries and configuration into an image that runs as an isolated process sharing the host's operating system kernel.
- Container image
- A read-only, layered template that holds an application and its user-space dependencies. Identical running containers are started from it.
- On-premises deployment
- Running systems on hardware an organization owns or leases, in a facility it controls. The organization is responsible for everything from power to software.
- Cloud deployment
- Running systems on computing resources rented on demand from a provider's shared, metered pool, typically through IaaS, PaaS or SaaS offerings.
- Cluster deployment
- Running a workload across a group of networked machines, called nodes, that shared software coordinates as one system, for scale-out capacity, fault tolerance or both.
- Hybrid deployment
- An architecture that joins two or more distinct environments, typically on-premises or private infrastructure and a public cloud, so that data and applications can move between them.
- Edge deployment
- Running computation, usually model inference, on or near the device or site where data is produced, to cut latency and bandwidth use and to keep working offline.
- Cloud bursting
- Running a workload on local capacity normally and sending the overflow to public cloud capacity when demand exceeds what the local resources can handle.
- Control plane
- In Kubernetes, the components that make cluster-wide decisions, such as scheduling Pods, and that keep the cluster's actual state matching the declared desired state.
Module 5: Specialized Applications of Data Science
Optimization, natural language processing, computer vision and other specialized applications.
Optimization Concepts
- Formulate a resource allocation problem as a linear program, solve it by listing corners and by the simplex method, and read shadow prices from the result.
- Distinguish linear, mixed-integer, constraint programming and non-linear solvers, and match each to pricing, bundling, scheduling, network topology and traveling salesman problems.
- Explain boundary cases, local versus global optima and convexity, and predict when one changed input moves an optimum.
- Compare one-armed and multi-armed bandits with A/B testing, using regret to judge exploration strategies.
Dantzig's corners: where this objective begins
In 1947, George B. Dantzig developed a technique for solving linear programs, the simplex method.[1] A linear program asks you to maximize or minimize a linear expression while obeying linear limits. The method rests on one picture. The best answer sits at a corner of a fenced-in region, and the method walks from corner to corner, improving at every step, until no neighboring corner is better. Keep that picture in mind. Almost every item on this objective is a version of it, with constraints fencing in a region and the best point usually on the fence. The rest are deliberate departures from it: problems with no fence at all, or with a payoff you can only learn by trying.
Exam objectives: 5.1 Compare and contrast optimization concepts.[2] Under constrained optimization the objective lists resource allocation, network topology, bundling, boundary cases, traveling salesman, scheduling, linear solvers, the simplex method, non-linear solvers and pricing. Under unconstrained optimization it lists the one-armed bandit, the multi-armed bandit, and finding local maxima or minima.
This lesson is a procedure. You will set up one resource allocation problem and solve it by hand. Then you will change one number and watch the answer jump to a different corner. After that, the same three questions (what do I control, what am I scoring, what limits me) carry you through pricing, bundling, scheduling, networks, the traveling salesman, calculus-style minima and bandits. Every worked example uses fictional numbers chosen so you can check the arithmetic.
Three questions to answer before touching a solver
Google's OR-Tools guide (OR-Tools is Google's open-source operations research library) says the first step in solving an optimization problem is to identify the objective and the constraints.[3] In practice you name three things:
- Decision variables: the quantities you control. Examples are how many jobs of each type to run, what price to charge, which option to try next, or which weights a model uses.
- Objective function: the single number you want as large or as small as possible. Profit, revenue, total distance, finishing time, loss and clicks are all objectives.
- Constraints: rules the decision variables must obey. Budgets, capacities, deadlines, 'visit every city exactly once' and 'price at or above the floor' are constraints.
Any assignment of values that obeys every constraint is a feasible solution. The set of all feasible solutions is the feasible region. An optimal solution is a feasible solution with the best objective value. Maximizing and minimizing are the same problem in disguise: to maximize f you can minimize -f, which is why optimization notes usually describe only minimization.[4] Most Python minimizers follow that convention, so you negate revenue or profit before passing it in.
The exam's main split is whether the feasible region is restricted. In unconstrained optimization the variables may take any real values: you minimize a real-valued function over all of n-dimensional space.[5] Optimization notes from Rutgers University set that apart from constrained optimization, which they also call non-linear programming, where the set of points you may choose from is restricted.[4] Strictly, the name non-linear programming fits when the objective or a constraint is curved; a constrained problem in which everything is linear is a linear program. The table shows the practical difference.
| Question | Constrained optimization | Unconstrained optimization |
|---|---|---|
| Where may the variables go? | Only inside the feasible region | Anywhere in the variable space |
| Where is the optimum usually found? | Often on the boundary, frequently at a corner where constraints meet | Where the gradient (the vector of slopes) is zero |
| What goes wrong? | No feasible point exists (infeasible), or the objective improves forever (unbounded) | The search sticks in a local optimum, or no minimum exists at all |
| Typical tools | Linear, mixed-integer, constraint programming and non-linear solvers | Calculus, gradient descent and Newton-type methods; bandit algorithms when payoffs must be learned by trial |
| Exam items | Resource allocation, network topology, bundling, boundary cases, traveling salesman, scheduling, linear solvers, simplex method, non-linear solvers, pricing | One-armed bandit, multi-armed bandit, finding local maxima or minima |
The upshot: name the decision variables, the objective and the constraints before you choose a method. Their shape decides which solver fits: linear or curved, continuous or whole-number, fenced in or free.
Worked example 1: resource allocation as a linear program
Resource allocation means dividing limited resources among competing uses to get the most total value. Here is a fictional version a data platform team might face.
Each night the team has 60 GPU-hours (Graphics Processing Unit hours) and 40 engineer review hours. Two kinds of batch job compete for them:
| Job type | GPU-hours per job | Engineer hours per job | Value per job |
|---|---|---|---|
| Feature-build job (x jobs) | 2 | 1 | 40 |
| Model-scoring job (y jobs) | 1 | 1 | 30 |
| Available each night | 60 | 40 |
Step 1: write the model.
maximize z = 40x + 30y
subject to 2x + y ≤ 60 (GPU-hours)
x + y ≤ 40 (engineer hours)
x ≥ 0, y ≥ 0
The objective and every constraint are linear expressions in the variables, so this is a linear programming problem, often shortened to LP.[3] For now x and y may be fractions. The answer here happens to come out in whole numbers.
Step 2: find the feasible region. Each constraint allows the points on one side of a line. Put x on the horizontal axis and y on the vertical. The GPU line 2x + y = 60 runs from (30, 0) to (0, 60). The engineer line x + y = 40 runs from (40, 0) to (0, 40). The feasible region is the four-sided shape below both lines, with x and y both zero or positive. Its corners are where the boundary lines cross:
| Corner (x, y) | Which boundaries meet there | z = 40x + 30y |
|---|---|---|
| (0, 0) | x = 0 and y = 0 | 0 |
| (30, 0) | GPU line and y = 0 | 1,200 |
| (20, 20) | GPU line and engineer line: subtract x + y = 40 from 2x + y = 60 to get x = 20, so y = 20 | 1,400 |
| (0, 40) | Engineer line and x = 0 | 1,200 |
Step 3: see why the best point is a corner. Fix any value of z. The points with 40x + 30y = z form a straight line, and the lines for different z values are parallel. Raising z slides the line outward. The best feasible z is where the line last touches the region before leaving it. A straight line leaving a polygon last touches it at a corner, or along a whole edge if the line is parallel to that edge. So if a linear program has an optimum, at least one optimum is a corner. Here the best corner is (20, 20) with z = 1,400: run 20 jobs of each type.
Step 4: translate the answer back into a decision. At (20, 20) the team uses 2(20) + 20 = 60 GPU-hours and 20 + 20 = 40 engineer hours. Both constraints are binding: each holds with equality, so that resource is fully used. A constraint that is not binding at the optimum has spare capacity, called slack.
The simplex method, pivot by pivot
Listing corners works with two variables. With 2,000 variables and 500 constraints there are far too many corners to list. The simplex method avoids that. It never visits every corner. It moves only to neighboring corners that improve the objective.
First it turns each inequality into an equation by adding a slack variable. Here s1 is unused GPU-hours and s2 is unused engineer hours, both zero or positive:
2x + y + s1 = 60
x + y + s2 = 40
z - 40x - 30y = 0
Set x and y to zero, and the slacks equal the right-hand sides: s1 = 60, s2 = 40, z = 0. MIT's linear programming notes call this kind of starting point a basic feasible solution. The basic variables (here the slacks) are read off the right-hand sides, and the nonbasic variables are set to zero.[1] Geometrically it is a corner, here the origin. The simplex method generates a sequence of basic feasible solutions, each one a corner, and stops at an optimal one.[1]
The bookkeeping lives in a tableau, a table of the equations' coefficients. The z row holds the objective equation z - 40x - 30y = 0.
| Row | x | y | s1 | s2 | Right-hand side |
|---|---|---|---|---|---|
| z | -40 | -30 | 0 | 0 | 0 |
| s1 | 2 | 1 | 1 | 0 | 60 |
| s2 | 1 | 1 | 0 | 1 | 40 |
Each iteration makes three moves.
- Choose the entering variable. A negative entry in the z row means raising that variable raises z. x has the most negative entry, -40, so x enters: it will become positive.
- Run the minimum ratio test. As x grows, the basic variable in each row shrinks. Divide each right-hand side by that row's positive coefficient on x: the s1 row gives 60 / 2 = 30, and the s2 row gives 40 / 1 = 40. The smallest ratio, 30, is how far x can grow before some variable would go negative. s1 reaches zero first, so s1 leaves.
- Pivot. Divide the s1 row by 2 so x has coefficient 1. Then subtract multiples of that row from the other rows so x has coefficient 0 everywhere else. These are elementary row operations, so the equations still describe exactly the same feasible region. Only the bookkeeping changes.[1]
| Row | x | y | s1 | s2 | Right-hand side |
|---|---|---|---|---|---|
| z | 0 | -10 | 20 | 0 | 1,200 |
| x | 1 | 0.5 | 0.5 | 0 | 30 |
| s2 | 0 | 0.5 | -0.5 | 1 | 10 |
Read the tableau: x = 30, y = 0, s1 = 0, s2 = 10, z = 1,200. That is corner (30, 0), with all GPU-hours used and 10 engineer hours idle. The z row still has a negative entry, -10 under y, so raising y will raise z further.
Second iteration: y enters. The ratio test on y's positive coefficients gives 30 / 0.5 = 60 for the x row and 10 / 0.5 = 20 for the s2 row. The minimum is 20, so s2 leaves. Multiply the s2 row by 2, then clear y from the other rows.
| Row | x | y | s1 | s2 | Right-hand side |
|---|---|---|---|---|---|
| z | 0 | 0 | 10 | 20 | 1,400 |
| x | 1 | 0 | 1 | -1 | 20 |
| y | 0 | 1 | -1 | 2 | 20 |
The z row now says z = 1,400 - 10s1 - 20s2. No entry is negative, so no variable can enter and raise z. Since s1 and s2 cannot go below zero, z cannot exceed 1,400. The method stops at x = 20, y = 20, z = 1,400, the same corner the listing found, after visiting three of the four corners.
The final z row carries a bonus. The coefficient 20 on s2 is the shadow price of an engineer hour: the change in the best objective value per extra unit of that resource, valid within a range. Check it. With 41 engineer hours, the binding lines 2x + y = 60 and x + y = 41 give x = 19 and y = 22, so z = 40(19) + 30(22) = 1,420, up 20. The same check shows a GPU-hour is worth 10. A manager choosing between one more GPU-hour and one more engineer hour now has a price for each. A constraint with slack at the optimum has a shadow price of zero, because more of a resource you are not using is worth nothing at the margin.
Three refinements from the MIT notes complete the method. First, when two rows tie in the minimum ratio test, you may pick either.[1] Ties can lead to a degenerate pivot, which changes the bookkeeping without moving to a new point. The notes prove the method finishes in finitely many iterations when the program is nondegenerate.[1] For the degenerate case they use an anti-cycling choice, Bland's rule. Second, the origin is not always feasible. A constraint such as 'run at least 5 feature jobs' rules it out, so there is no ready-made starting corner. A first phase then solves a helper problem to find one, which is the two-phase simplex method.[1] Third, practical solvers also offer interior-point methods, which travel through the inside of the region instead of along its edges. Simplex can be forced to visit very many corners on contrived worst-case examples, but it is usually fast in practice.
The upshot: the simplex method moves from corner to corner of the feasible region. It picks an entering variable from a negative z-row entry and a leaving variable by the minimum ratio test, and it stops when no z-row entry is negative. The final z row also gives the shadow price of each constraint.
Second run: one value change moves the optimum to another corner
Now change one input. Suppose a new downstream use makes each feature-build job worth 70 instead of 40. The constraints are untouched, so the feasible region and its corners stay the same. Only the scores change:
| Corner (x, y) | Original: z = 40x + 30y | Second run: z = 70x + 30y |
|---|---|---|
| (0, 0) | 0 | 0 |
| (30, 0) | 1,200 | 2,100 |
| (20, 20) | 1,400 | 2,000 |
| (0, 40) | 1,200 | 1,200 |
The optimum jumps to (30, 0): run only feature-build jobs and leave 10 engineer hours idle. The simplex method finds this sooner. Start from z - 70x - 30y = 0 and add 70 times the new x row (x + 0.5y + 0.5s1 = 30). The z row becomes z + 5y + 35s1 = 2,100. No entry is negative, so the method stops after one pivot.
Why did the answer flip? Compare the ratio of the two values, value(x) / value(y), with the trade-off rate along each binding constraint. On the engineer line, one more x costs one y (rate 1). On the GPU line, one more x costs two y (rate 2). Corner (20, 20) stays optimal while 1 ≤ value(x) / value(y) ≤ 2. The original ratio, 40 / 30 ≈ 1.33, is inside that range. The new ratio, 70 / 30 ≈ 2.33, is outside it, so the objective line tilts past the GPU edge and the best point slides to (30, 0).
Now try a variant of the second run with a value of 60 for x. The ratio is exactly 60 / 30 = 2, and the objective line is parallel to the GPU edge. Then (30, 0) and (20, 20) both score 1,800, and so does every point on the edge between them. That is a tie with infinitely many optimal solutions, and a solver will report just one of them.
Checking how far each coefficient can move before the plan changes is called sensitivity analysis. A plan that flips when a value estimate moves 10 percent deserves less confidence than one that holds across the plausible range of estimates.
Linear solvers in code, and when variables must be whole numbers
You will rarely pivot by hand. A linear solver is software that takes an objective and constraints and returns an optimal solution, or a status saying why there is none. In OR-Tools, the main solver for linear problems is a wrapper around several linear and mixed-integer libraries, including third-party ones.[3] Here is the same model in Python using the OR-Tools pattern: create the variables, add constraints with their coefficients, then set the objective.
from ortools.linear_solver import pywraplp
solver = pywraplp.Solver.CreateSolver('GLOP') # Google's linear solver
inf = solver.infinity()
x = solver.NumVar(0, inf, 'feature_jobs')
y = solver.NumVar(0, inf, 'scoring_jobs')
gpu = solver.Constraint(-inf, 60, 'gpu_hours') # 2x + y at most 60
gpu.SetCoefficient(x, 2)
gpu.SetCoefficient(y, 1)
eng = solver.Constraint(-inf, 40, 'engineer_hours') # x + y at most 40
eng.SetCoefficient(x, 1)
eng.SetCoefficient(y, 1)
objective = solver.Objective()
objective.SetCoefficient(x, 40)
objective.SetCoefficient(y, 30)
objective.SetMaximization()
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print(x.solution_value(), y.solution_value(), objective.Value())
Running it should print about 20.0, 20.0 and 1400.0, the hand result. The values come back as floating-point numbers, so a tiny rounding difference in the last digits is normal and not an error. Change the 40 in the objective to 70 and the result becomes about 30.0, 0.0 and 2100.0.
Many real allocation problems need whole numbers. You cannot run 20.5 jobs, open 0.3 of a warehouse or assign half a worker. A mixed-integer optimization problem requires some or all variables to be integers.[3] Google's example assigns workers to tasks using variables that equal 1 if a worker gets a task and 0 otherwise. Such problems are usually solved by branch and bound. The solver first solves the LP relaxation, which is the same problem with the whole-number rule dropped. If a variable comes out fractional, say x = 20.5, it splits into two subproblems, x ≤ 20 and x ≥ 21, and keeps only branches whose relaxation could still beat the best whole-number plan found so far. Simply rounding the LP answer is not a substitute: the rounded point can break a constraint or sit far from the true integer optimum.
Whatever the solver, read its status before reading its numbers:
| Status | What it means | What to do next |
|---|---|---|
| Optimal | A feasible point was found and proven best | Check which constraints bind and how sensitive the plan is |
| Feasible | A valid point was found but not proven best, often because an integer problem hit a time limit | Report the remaining gap to the best bound, or allow more time |
| Infeasible | No point satisfies every constraint at once | Find the conflicting constraints and decide which one to relax |
| Unbounded | The objective can improve without limit | Look for a missing constraint, such as a forgotten budget or capacity |
Boundary cases: binding limits, infeasible models, unbounded models and ties
Boundary cases matter in optimization in two senses, and you should be ready for both.
The first sense is where the optimum lies. In a linear program, an optimum (if one exists) always includes a corner, which is on the boundary. In a curved problem the optimum may be in the interior, where the slope is zero, or on the boundary, where a constraint binds. So the safe procedure for small curved problems is to collect every candidate: the interior points where the gradient is zero, the best points along each boundary, and the corners. Then compare their objective values. The pricing and calculus examples below both show an optimum forced onto the boundary.
The second sense is the edge cases of the model itself. Each has a recognizable symptom:
| Case | Symptom | Fictional example | Usual repair |
|---|---|---|---|
| Binding constraint | Resource fully used; nonzero shadow price | All 60 GPU-hours used at the optimum | Decide whether buying more of it is worth its shadow price |
| Infeasible model | Solver reports no feasible solution | Add 'at least 50 jobs in total' to the engineer limit of 40 jobs | Relax a constraint, add capacity, or treat a hard rule as a penalized soft rule |
| Unbounded model | Solver reports the objective can grow forever | Delete both resource constraints: z = 40x + 30y grows without limit | Restore the missing limit |
| Ties and degeneracy | Several optimal plans; pivots that do not move | A value of 60 for x (ratio exactly 2), the variant of the second run | Add a secondary objective, or report the range of optimal plans |
| Inputs at their limits | Odd results at zero demand, exactly-full capacity or a floor equal to the optimum | Price floor set exactly at the revenue peak | Test these values on purpose when validating the pipeline |
The unbounded row is easy to see from the math. Stanford's gradient descent notes point out that minimizing a linear function with no constraints is trivial, because you can make the objective arbitrarily negative.[5] A linear objective needs constraints to have an answer. In a production model, an unbounded result almost always means a forgotten limit, not a fabulous opportunity.
Non-linear solvers and price optimization
A non-linear solver handles problems whose objective or constraints are curved. Examples include revenue equal to price times a demand that falls as price rises, risk measured as variance, and a classifier's log-loss. Without linearity the corner argument fails. The optimum may be in the interior, and when the problem is not convex a solver may return a local optimum rather than the global one.
The common families are these. Gradient-based methods handle smooth problems: gradient descent, Newton's method, and quasi-Newton methods such as Broyden-Fletcher-Goldfarb-Shanno (BFGS), which builds up an estimate of the curvature from successive gradients instead of computing second derivatives directly. Sequential quadratic programming, which solves a series of simpler quadratic approximations, and interior-point methods handle smooth problems with constraints. Derivative-free or global methods (Nelder-Mead, simulated annealing, genetic algorithms) are used when gradients are unavailable or the surface is rugged. Model fitting is the everyday case. With squared error and a model that is linear in its parameters, the best parameters can be solved for directly, which is the basis of least squares regression.[4] Curved models such as neural networks need iterative solvers instead.
Pricing, more formally price optimization, is the exam's standard curved problem. Here is a fictional subscription with demand q = 1000 - 20p, where p is the monthly price in dollars (0 to 50) and q is the number of subscribers.
- Write revenue. R(p) = p × q = p(1000 - 20p) = 1000p - 20p2.
- Set the derivative to zero. dR/dp = 1000 - 40p = 0 gives p = 25.
- Confirm it is a maximum. The second derivative is -40, which is negative, so R curves downward (it is concave) and p = 25 is a maximum. At p = 25, q = 500 and R = 12,500.
In general, for linear demand q = a - bp, revenue peaks at p = a / (2b). Here that is 1000 / 40 = 25.
Second run: add a capacity cap. The platform can host only 400 subscribers. The constraint q ≤ 400 means 1000 - 20p ≤ 400, so p ≥ 30. The old optimum, 25, is now infeasible. Revenue peaks at 25 and falls steadily after it, so on the allowed range p ≥ 30 the best point is the boundary itself: p = 30, q = 400, R = 12,000. The constraint binds.
| Capacity | Best price | Subscribers | Revenue | Capacity constraint binding? |
|---|---|---|---|---|
| None | $25 | 500 | $12,500 | Not applicable |
| 600 | $25 | 500 | $12,500 | No: 100 seats of slack |
| 400 | $30 | 400 | $12,000 | Yes: optimum on the boundary |
The binding cap has a shadow price, just as in the linear program. Write price in terms of quantity: p = 50 - q/20, so R(q) = 50q - q2/20 and dR/dq = 50 - q/10. At q = 400 that is 10, so one more seat of capacity is worth about $10 of revenue a month. In curved problems this marginal value is called a Lagrange multiplier.
A general non-linear solver reaches the same answer. SciPy, a Python scientific computing library, provides a general minimizer. Here it uses the Sequential Least Squares Programming (SLSQP) method, a form of sequential quadratic programming that accepts bounds and constraints. You minimize negative revenue, and an 'ineq' constraint means the function you supply must stay at or above zero:
from scipy.optimize import minimize
def negative_revenue(v):
p = v[0]
return -(1000 * p - 20 * p ** 2) # minimize the negative to maximize
capacity = {'type': 'ineq', # fun(v) must be at least 0
'fun': lambda v: 400 - (1000 - 20 * v[0])}
result = minimize(negative_revenue, x0=[20.0], method='SLSQP',
bounds=[(0, 50)], constraints=[capacity])
print(result.x, -result.fun) # about 30 and 12000
Real pricing adds two complications. Demand is unknown and has to be estimated from data. And business rules add constraints: price floors and ceilings, matching competitor prices, regulation and fairness limits. When demand must be learned while selling, pricing becomes a learning problem. Slivkins's survey of bandit algorithms lists dynamic pricing with limited supply as one of the problems studied in that framework.[6] That connects pricing to the bandits at the end of this lesson.
Product bundling: optimizing what goes together
Product bundling sells several items together at one price. Whether it helps depends on how customers' valuations differ, and you can work that out exactly. Here are two fictional customers and the most each would pay:
| Customer | Analytics software | Premium support | Both together |
|---|---|---|---|
| Ana | 120 | 40 | 160 |
| Ben | 80 | 90 | 170 |
Price separately. Software at 80 sells to both customers (160); at 120 it sells only to Ana (120). So charge 80 and earn 160. Support at 40 sells to both (80); at 90 it sells only to Ben (90). So charge 90 and earn 90. Total: 250.
Sell only a bundle. A customer buys if the bundle price is no more than their combined value. That is a constraint: price ≤ 160 for Ana and price ≤ 170 for Ben. At 160 both buy, earning 320. Bundling wins by 70 because Ana's high value for software offsets her low value for support, and the reverse holds for Ben. The bundle captures both totals with one price.
Second run: correlated valuations. Suppose Ana values software at 120 and support at 90 (total 210), while Ben values them at 80 and 40 (total 120). Separate pricing still earns 160 + 90 = 250. A bundle at 120 sells to both for 240; at 210 it sells only to Ana for 210. Now bundling loses. When the same customer values everything more, a bundle cannot balance one item against another.
As an optimization model, the decision variables are which items go in which bundles and at what prices. The constraints say each customer picks whichever option gives them the most value for the money, along with inventory limits and minimum margins. Bundling also has a packing sense: choosing items to fit a cost or size budget. OR-Tools treats this as bin packing, and its single-container special case is the knapsack problem.[3] A promotional bundle that must stay under a cost of 50 while including the most valuable mix of add-ons is a knapsack problem.
The upshot: constraints decide where the optimum lands. In the job example the best plan sat where two resource lines crossed. In pricing it moved to the capacity boundary. In bundling the profitable price is set by each customer's willingness to pay.
Scheduling: tasks, machines and time
Scheduling problems assign resources to perform tasks at specific times.[3] The classic case is job-shop scheduling: several jobs, each a sequence of tasks that must run in order on particular machines. The usual goal is to finish everything as early as possible, which means minimizing the makespan, the time from the first start to the last finish. Typical constraints are:
- Precedence: task B cannot start until task A finishes, such as training before evaluation.
- Capacity: a machine, GPU or analyst handles one task at a time.
- Time windows and deadlines: a report is due by 06:00.
Scheduling models are full of 'either this task runs first or that one does' choices, which makes them integer problems. They are often solved with constraint programming, which searches very large sets of candidates for solutions that satisfy arbitrary constraints.[3] Google describes constraint programming as based on feasibility rather than optimization: its core job is to find a schedule that breaks no rule, and an objective such as makespan is handled on top of that search.
A small fictional example shows feasibility at work. One GPU starts at hour 0 and has three jobs:
| Job | Duration (hours) | Deadline (hours after start) |
|---|---|---|
| J1 | 4 | 5 |
| J2 | 2 | 3 |
| J3 | 3 | 9 |
With hard deadlines, J1 and J2 together need 6 hours, but the later of their deadlines is hour 5. Running J2 first finishes J1 at hour 6, which is late. Running J1 first finishes J2 at hour 6, also late. No order works, so the model is infeasible: a boundary case. Change the objective to minimizing the worst lateness, and sorting by earliest deadline (J2, J1, J3) finishes the jobs at hours 2, 6 and 9. Lateness is 0, 1 and 0, so the worst lateness is 1 hour.
Second run: add a second GPU. Put J2 on GPU A (hours 0-2), J1 on GPU B (hours 0-4) and J3 on GPU A (hours 2-5). Every job is on time. One extra resource turned an infeasible model into a feasible one, which is the scheduling version of a shadow price.
Network topology: optimizing over graphs
Network topology is the pattern of connections among nodes. Many optimization problems can be drawn as a directed graph of nodes joined by arcs.[3] Nodes might be warehouses, data centers or servers, and arcs are roads, rail lines or network links, each with a cost or capacity. The standard network problems are these:
- Shortest path problem: the cheapest route from one node to another.
- Maximum flow problem: the most traffic that can move from a source to a sink without exceeding any link's capacity.
- Minimum-cost flow problem: meeting demands at the least shipping cost.
- Minimum spanning tree: the cheapest set of links that connects every node.
- Network design: which links to build at all, subject to budget, capacity and redundancy rules. This is usually a mixed-integer problem, because a link is either built or not.
Here is a fictional example. Connect four sites with leased lines at these monthly costs: HQ-DC1 4, DC1-DC2 3, HQ-DC2 6, DC1-Branch 5, DC2-Branch 7, HQ-Branch 9. To find the minimum spanning tree, take links from cheapest to most expensive and skip any link that would close a loop (Kruskal's method). Take DC1-DC2 (3), then HQ-DC1 (4), then DC1-Branch (5). All four sites are now connected for a total of 12, and every remaining link would close a loop.
Second run: require redundancy. Add a rule that every site must stay connected if any single link fails. A tree fails that test, because cutting any of its links splits the network. Every site now needs at least two links. With four sites, the cheapest way to give each site two links is a single loop through all four. The loop HQ-DC1-Branch-DC2-HQ costs 4 + 5 + 7 + 6 = 22, the cheapest of the three possible loops. The other two cost 23. One added constraint raised the cost from 12 to 22, and it also turned the design question into a small traveling salesman problem.
The traveling salesman problem: when exact search gives way to heuristics
In the traveling salesman problem (TSP), you have a set of locations and a cost for each connection, and you want the cheapest closed tour. The exam uses the traditional name. Current documentation and course notes usually call it the traveling salesperson problem: the University of Illinois lecture notes use that name, and so does OR-Tools.[7][3] Both names mean the same problem. A cycle that visits every vertex exactly once is called a Hamiltonian cycle, and TSP asks for the cheapest one.[7] OR-Tools files it under routing, the family of problems that find the best routes for a fleet of vehicles through a network.[3] Delivery routes, technician visits, the order a drill visits holes on a circuit board and the order a warehouse picker visits shelves are all versions of it.
The constraint is what makes TSP hard: every city exactly once, then back to the start. With symmetric costs and n cities there are (n - 1)! / 2 distinct tours:
| Cities (n) | Distinct tours, (n - 1)! / 2 |
|---|---|
| 4 | 3 |
| 10 | 181,440 |
| 15 | 43,589,145,600 |
| 20 | about 6.1 × 1016 |
TSP is NP-complete, so no algorithm is expected to solve every instance exactly in polynomial time.[7] NP stands for nondeterministic polynomial time. In practice this means solve times can explode as the number of cities grows. Exact methods, such as integer programming with cutting planes, can prove optimality for surprisingly large instances, but run time is not guaranteed. In practice, local search heuristics are widely used and perform very well.[7] A heuristic is a method that usually finds a good answer quickly without proving it is the best.
Here is a fictional four-city example:
| From / to | A | B | C | D |
|---|---|---|---|---|
| A | 0 | 10 | 15 | 20 |
| B | 10 | 0 | 35 | 25 |
| C | 15 | 35 | 0 | 30 |
| D | 20 | 25 | 30 | 0 |
Exhaustive search checks all three tours. A-B-C-D-A costs 10 + 35 + 30 + 20 = 95. A-B-D-C-A costs 10 + 25 + 30 + 15 = 80. A-C-B-D-A costs 15 + 35 + 25 + 20 = 95. The optimum is 80.
Now improve a poor tour with 2-opt instead. The 2-opt heuristic removes two edges, xy and zw, and reconnects the tour as xz and yw (or xw and yz) whenever that shortens it.[7] Start from A-B-C-D-A (95). Remove B-C (35) and D-A (20), which total 55. Reconnect as B-D (25) and C-A (15), which total 40. The section between them is traversed in reverse, giving A-B-D-C-A at 95 - 55 + 40 = 80. Now try every other pair of non-adjacent edges in the new tour. Swapping A-B and D-C for A-D and B-C costs 55 instead of 40, and swapping B-D and C-A for B-C and D-A also costs 55 instead of 40. No swap helps, so 2-opt stops. Here its local optimum is the global one. On larger instances, a tour with no improving 2-opt swap can still be beaten, which is why practical solvers combine local moves with restarts and other metaheuristics.
Finding local maxima or minima
The unconstrained side of the objective starts with calculus. A global minimum is a point whose value is no larger than at any other point. A local minimum is only no larger than at nearby points. The Rutgers notes draw this distinction early because the methods behave so differently on the two.[4] Local and global maxima are defined the same way.
For a smooth function the procedure has three steps. First, find stationary points, where the derivative (or, with several variables, every component of the gradient) is zero. Second, classify each one. A positive second derivative means a local minimum and a negative one means a local maximum. With several variables, a Hessian (the matrix of second derivatives) whose eigenvalues are all positive means a local minimum, all negative means a local maximum, and mixed signs mean a saddle point. Third, compare candidates and check what happens far away.
Worked example: f(x) = x3 - 3x.
- f'(x) = 3x2 - 3 = 0 gives x = 1 or x = -1.
- f''(x) = 6x. At x = 1, f'' = 6 > 0, so this is a local minimum with f(1) = -2. At x = -1, f'' = -6 < 0, so this is a local maximum with f(-1) = 2.
- Far away, f goes to minus infinity as x falls and to plus infinity as x rises. Neither stationary point is global. In fact this unconstrained problem has no global minimum or maximum at all.
Second run: restrict x to the interval from -2 to 3. Now the endpoints join the candidate list:
| Candidate x | Why it is a candidate | f(x) |
|---|---|---|
| -2 | Left boundary | -2 |
| -1 | Stationary point (local maximum) | 2 |
| 1 | Stationary point (local minimum) | -2 |
| 3 | Right boundary | 18 |
On the interval, the global maximum is 18 at the boundary x = 3. The global minimum, -2, is a tie between the boundary x = -2 and the interior point x = 1. Adding constraints changed which points matter, which is the boundary-case lesson again.
When derivatives cannot be solved by hand, gradient descent steps downhill: xnew = x - η f'(x), where η (eta) is the step size or learning rate. With η = 0.1 on the same function:
| Start | Step 1 | Step 2 | Step 3 | Where it heads |
|---|---|---|---|---|
| x = 2 (f' = 9) | 1.1 | 1.037 | 1.014 | The local minimum at x = 1 |
| x = -1.5 (f' = 3.75) | -1.875 | -2.630 | further left | Downhill forever: no minimum on that side |
The same algorithm with the same settings succeeds or fails depending only on where it starts. Convexity decides whether that can happen. A function is convex if every chord of its graph, the straight segment joining two points on the curve, lies on or above the graph.[5] If f is convex, gradient descent can only stop at a global minimum.[5] With a non-convex function, gradient descent can stop at a local minimum that is worse than the global one.[5] Squared-error linear regression and logistic regression have convex losses. Neural networks do not.
Even so, gradient descent is often a surprisingly good heuristic for non-convex problems.[5] Practitioners improve the odds with several random starts, momentum, the noise of stochastic mini-batches and careful initialization. To find a maximum instead, climb with gradient ascent or minimize -f.
The upshot: for an unconstrained smooth problem, find where the gradient is zero and classify each point with second derivatives. Trust a local minimum as global only when the function is convex. Once constraints exist, add the boundary points to the candidate list.
Bandit problems: optimizing while you learn
A slot machine is nicknamed a one-armed bandit. A course note from the University of Washington explains the name: "They are called bandits because they steal your money."[8] In the multi-armed bandit problem you face K slot machines (arms) and may pull T times in total. Each pull of arm i pays a random reward from a distribution you do not know. You must estimate every arm's expected payoff while also maximizing your total payoff.[8] Every pull is a choice between two goals, known as the exploration-exploitation tradeoff:
- Exploitation: pull the arm that currently looks best.
- Exploration: pull arms you have tried less often, in case one of them is better.[8]
The score is regret: the gap between the best possible expected reward, from always pulling the best arm, and the reward you actually collected.[8] If p* is the best arm's expected reward per pull:
Regret(T) = T × p* - Reward(T)
Minimizing regret and maximizing reward are the same goal. Regret is used because it makes strategies easy to compare over time.
Why does CompTIA list bandits under unconstrained optimization? No fence restricts the choice: you may pull any arm at any time. The difficulty is uncertainty, not feasibility. Research does study variants with budgets, such as bandits with resource constraints, so treat the exam's grouping as a classification for the test, not a law.[6]
Worked example: three ad banners. The true click-through rates are 0.040 (A), 0.050 (B) and 0.030 (C). These are fictional, and the advertiser does not know them. There are 30,000 impressions to serve. The best possible result is 30,000 × 0.050 = 1,500 expected clicks.
| Strategy | Expected clicks | Regret |
|---|---|---|
| Always show B (impossible without knowing the rates) | 1,500 | 0 |
| Equal split throughout: 10,000 impressions each | 400 + 500 + 300 = 1,200 | 300 |
| Explore then commit: 1,000 each, then the rest to the apparent leader, if that is B | 120 + 27,000 × 0.050 = 1,470 | 30 |
| Explore then commit, but A looked best by chance | 120 + 27,000 × 0.040 = 1,200 | 300 |
How likely is that wrong commitment? After 1,000 impressions each, the standard error of the difference between B's and A's observed rates is the square root of (0.05 × 0.95 / 1,000 + 0.04 × 0.96 / 1,000), about 0.0093. The true gap of 0.010 is only about 1.08 standard errors. Under a normal approximation, A outscores B roughly 14 percent of the time (ignoring the small chance that C wins). So the expected regret of explore-then-commit is about 0.86 × 30 + 0.14 × 300 ≈ 68. That beats the equal split, but it carries a real risk of locking in the wrong banner.
Adaptive algorithms reduce that risk because they never stop checking:
- Epsilon-greedy: with probability 1 - ε show the current leader, and with probability ε show a random arm. With ε = 0.1 and B leading, the expected click rate is 0.9 × 0.050 + 0.1 × (0.040 + 0.050 + 0.030) / 3 = 0.049. That costs 0.001 clicks of regret per impression for as long as it runs, but a wrong early leader gets corrected.
- Upper confidence bound (UCB1): show the arm with the highest meani + √(2 ln t / ni), where t is the total number of pulls so far and ni is arm i's pull count. The bonus is large for rarely tried arms and shrinks as evidence builds up.
- Thompson sampling: keep a Beta(1 + clicks, 1 + non-clicks) belief for each arm, draw one random sample from each belief, and show the arm with the highest draw. Arms are chosen in proportion to how likely each is to be best.
Bandit or A/B test? Both compare variants, but they buy different things. Lesson 10 covers the A/B test as a hypothesis test, and the Atlas Data+ course reviews the hypothesis-testing basics behind it. Choose a bandit when you just want to maximize reward, typically revenue or engagement, without needing to interpret every result.[8] Bandits also let you add or remove arms in the middle of an experiment, which a fixed A/B test cannot do.[8] Choose a traditional A/B test when you need statistical confidence about every variant, including the losers, when you track several metrics, or when the reward is not immediate.[8] A drug trial whose outcome arrives months later cannot steer the next patient's assignment. Online advertising is a natural bandit setting, because ad click probabilities are unknown in advance but can be learned over time.[6]
The one-armed bandit problem is the simplest member of the family. One arm has an unknown payoff, and the alternative is a known, fixed payoff. Each round you either pull the unknown arm again or retire to the known option, usually for good. Picture a bank with a fraud rule whose catch rate is well measured over years and one untried new rule. The question is how long to keep testing the new rule before falling back. The answer depends on how many rounds remain. With a long horizon, it can pay to keep trying an arm whose current estimate is slightly below the known option, because what you learn is worth more future pulls. With only a few rounds left, you take the sure thing.
Comparing the concepts side by side
| Concept | Constrained? | Decision variables | Objective | Typical method |
|---|---|---|---|---|
| Resource allocation | Yes | Amounts per use | Total value | Linear or mixed-integer solver |
| Simplex method | Yes | Continuous, linear | Linear | Pivot between corners |
| Non-linear solver | Either | Continuous | Curved | Gradient-based, sequential quadratic programming, interior point |
| Pricing | Usually | Prices | Revenue or profit | Calculus or non-linear solver; bandits if demand is unknown |
| Bundling | Yes | Bundle contents and prices | Revenue | Integer programming; knapsack-style packing |
| Scheduling | Yes | Start times, machine assignments | Makespan or lateness | Constraint programming, mixed-integer solver |
| Network topology | Yes | Links built, flow on each link | Cost or throughput | Graph algorithms, mixed-integer solver |
| Traveling salesman | Yes | Visiting order | Tour length | Heuristics such as 2-opt; exact integer programming for proof |
| Local maxima or minima | No | Continuous | Any smooth function | Derivative tests, gradient descent |
| Multi-armed bandit | No (on this exam) | Which arm to pull next | Total reward, or equivalently low regret | Epsilon-greedy, UCB, Thompson sampling |
| One-armed bandit | No (on this exam) | Continue or retire | Total reward | Stopping rule weighing information against the known payoff |
Exam questions describe a situation and expect you to name the concept. These cues map stem language to answers, including the pairs people confuse:
| The stem says | It points to | Commonly confused with |
|---|---|---|
| Maximize profit; costs and limits are linear; budget or capacity | Linear solver for resource allocation | Non-linear solver, needed only if something curves |
| Pivot, basic feasible solution, corner point, slack variable | Simplex method | Gradient descent, which follows slopes rather than corners |
| Price, demand curve, elasticity, revenue equals price times quantity | Pricing with a non-linear solver | Linear solver |
| Which products to sell together; one price for a package | Bundling | Single-item pricing |
| Visit every location once and return; shortest loop | Traveling salesman (salesperson) | Shortest path, which only goes from one point to another |
| Jobs, machines, precedence, deadlines, makespan | Scheduling | Resource allocation with no time dimension |
| Nodes, links, capacity, flow, cheapest way to connect sites | Network topology | Traveling salesman |
| Optimum at the limit, at capacity, infeasible, unbounded, tie | Boundary cases | Local minimum |
| Explore versus exploit, regret, shift traffic toward the winner during the test | Multi-armed bandit | A/B test with a fixed split |
| One unknown option against a known payoff; when to stop trying | One-armed bandit | Multi-armed bandit |
| Gradient equals zero, Hessian, stuck, different results from different starts | Finding local maxima or minima | Simplex method |
Common misconceptions
- 'The simplex method searches the inside of the feasible region.' It moves along edges from corner to corner, using basic feasible solutions. Interior-point methods are the ones that travel through the inside.
- 'When gradient descent stops, it has found the best model.' That holds only for convex functions. On a non-convex loss it can stop at a worse local minimum, and with a poor start on an unbounded function it may never stop.
- 'A multi-armed bandit is just a faster A/B test.' They answer different questions. A bandit maximizes reward during the experiment and gives up clean estimates of the losing variants. An A/B test pays some reward to buy statistical confidence about every variant.
- 'Infeasible or unbounded means the solver is broken.' Both describe the model. Infeasible means the constraints contradict each other. Unbounded usually means a constraint is missing.
- 'Rounding the LP answer gives the best whole-number plan.' A rounded point can break a constraint or miss the integer optimum. Use a mixed-integer solver when the variables must be whole numbers.
- 'Unconstrained means the real situation has no limits.' It means the model places no restrictions on the variables. Limits may be absent, may never bind, or may be folded into the objective as penalties, as regularization does for model weights.
What to remember
- Every optimization model names decision variables, an objective and constraints. To maximize f, minimize -f.
- If a linear program has an optimum, at least one optimum is a corner of the feasible region. The simplex method, developed by Dantzig in 1947, moves between basic feasible solutions using an entering variable and the minimum ratio test.
- In the final simplex tableau, the z-row coefficients on slack variables are shadow prices. A constraint with slack at the optimum has a shadow price of zero.
- When one objective coefficient changes enough that the value ratio passes the trade-off rate of a binding constraint, the optimum jumps to another corner. At exactly that rate, there is a tie along an edge.
- With linear demand q = a - bp, revenue peaks at p = a / (2b). A capacity cap below that demand pushes the best price up to the boundary, and the cap's marginal value is its Lagrange multiplier.
- The traveling salesman (salesperson) problem seeks the cheapest Hamiltonian cycle. It has (n - 1)! / 2 tours for n symmetric cities, it is NP-complete, and it is usually attacked with heuristics such as 2-opt.
- For a convex function every local minimum is global. On non-convex functions gradient descent can stop at different local minima depending on where it starts.
- Bandit regret is T × p* minus the reward collected. Bandits trade exploration against exploitation to maximize reward, while A/B tests buy confidence about every variant. A one-armed bandit pits one unknown arm against a known payoff.
- Whole-number decisions in scheduling, bundling and network design need mixed-integer or constraint programming solvers, not rounded linear answers.
Sources
- Michel Goemans. (2015). Linear Programming Notes (18.310). MIT Department of Mathematics. math.mit.edu
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Google Developers. (n.d.). Get Started with OR-Tools for Python. developer.google.com
- Cowan. (n.d.). Optimization Notes (CS674). Rutgers University. people.cs.rutgers.edu
- Tim Roughgarden and Gregory Valiant. (n.d.). Gradient Descent notes (CS168). Stanford University. web.stanford.edu
- Aleksandrs Slivkins. (2019). Introduction to Multi-Armed Bandits. arXiv. arxiv.org
- Chandra Chekuri. (2009). Lecture 2 (Traveling Salesman Problem and approximation). University of Illinois Urbana-Champaign. courses.grainger.illinois.edu
- University of Washington. (2020). CSE 312 Section 9.8: Multi-armed bandits. courses.cs.washington.edu
- Key terms
- Constrained optimization
- Finding the best value of an objective function while the decision variables must satisfy rules such as budgets, capacities or deadlines, which restrict the choice to a feasible region.
- Feasible region
- The set of all assignments of the decision variables that satisfy every constraint of an optimization model at once.
- Simplex method
- An algorithm developed by George Dantzig in 1947 that solves linear programs by moving from one basic feasible solution (a corner of the feasible region) to a better neighboring one until no improvement is possible.
- Shadow price
- The change in the optimal objective value per additional unit of a constrained resource, valid within a range. It is zero for a constraint that has slack at the optimum.
- Traveling salesman problem
- Also called the traveling salesperson problem: finding the lowest-cost closed tour that visits every location exactly once and returns to the start. It is NP-complete and is usually solved with heuristics such as 2-opt.
- Local minimum
- A point whose function value is no larger than at nearby points but may be larger than the global minimum. For convex functions every local minimum is also global.
- Multi-armed bandit
- A sequential decision problem in which you repeatedly choose among several options with unknown random payoffs, balancing exploration of uncertain options against exploitation of the apparent best one.
- Regret
- In bandit problems, the expected reward from always choosing the best option minus the reward actually collected. For Bernoulli arms over T rounds it equals T times p* minus the total reward.
- One-armed bandit
- A bandit problem with one option of unknown payoff and a known fixed alternative, where the decision is how long to keep trying the unknown option before retiring to the known one.
- Convex function
- A function whose graph lies on or below every straight chord joining two of its points, so any local minimum is a global minimum.
Natural Language Processing
- Trace a text pipeline from tokenization and text preparation (stop words, stemming, lemmatization, part-of-speech tagging, string indexing, augmenters) to a document term matrix, and explain what each step keeps and what it loses.
- Compute TF-IDF weights and Levenshtein edit distance by hand, and predict how a change in the corpus or the candidate list changes the result.
- Compare bag of words, LDA topic models, static word embeddings (word2vec, GloVe) and contextual embeddings from large language models, including how each one handles disambiguation.
- Match NLP applications (sentiment analysis, NER, auto-tagging, question answering and dialogue, text generation, summarization, matching models, speech recognition and generation) to a business need, and say whether each is mainly NLU or NLG.
ELIZA in 1966, and a support inbox in 2026
In 1966 Joseph Weizenbaum's program ELIZA replied to a user who typed "I need some help" by asking what it would mean to them if they got some help. Jurafsky and Martin describe ELIZA as an early natural language processing system that held a limited conversation by imitating a Rogerian psychotherapist.[1] It understood nothing. It matched word patterns such as I need X and rewrote them into a reply.[1] Even so, many people who used it came to believe that it really understood them.[1]
Natural language processing (NLP) is the field that turns human language into something a computer can calculate with, and turns results back into language. Sixty years after ELIZA, the core problem is the one Weizenbaum's program avoided. Text arrives as a string of characters. Models need numbers. The meaning you care about lives in word choice, word order and context. Each technique in this objective makes a different trade between how cheaply text becomes numbers and how much meaning survives the conversion.
To keep that trade concrete, we follow one fictional case from raw text to a working system. Kestrel Home is an invented company that sells dishwashers, dryers and camera drones. Last quarter its support team received 52,000 written messages and 9,000 recorded phone calls. The head of support asked the data science team for three things. First, the recurring problems, ranked by volume. Second, every message that names a product or a date routed to the right team with those fields filled in. Third, a one-paragraph weekly summary for executives. Here are five messages from the inbox.
| ID | Channel | Text as received |
|---|---|---|
| T-1041 | Dishwasher wont drane. E24 code again, 3rd time since March. | |
| T-1042 | Chat | The KD-450 is not draining and the error code is E24. |
| T-1043 | Review | Love the drone!! battery charge lasts forever |
| T-1044 | Phone call, machine transcript | the dish washer will drain |
| T-1045 | You charged my card twice for the KD-450 on 3 October. |
The caller in T-1044 actually said "the dishwasher will not drain". The transcription system dropped one word and turned a complaint into its opposite. That error comes back when we measure speech recognition.
Exam objectives: DY0-001 objective 5.2, Explain the use and importance of natural language processing (NLP) concepts.[2] The objective lists tokenization and bag of words, word embeddings, n-grams, term frequency-inverse document frequency (TF-IDF), the document term matrix, edit distance, and large language models with word2vec and GloVe. It also lists text preparation (lemmatization, stop words, augmenters, string indexing, stemming, part-of-speech tagging), topic modeling with Latent Dirichlet Allocation, and disambiguation. Finally it lists NLP applications: sentiment analysis, question-and-answer and dialogue, named-entity recognition (NER), auto-tagging, text generation, matching models, speech recognition and generation, text summarization, natural language understanding (NLU) and natural language generation (NLG).
The work splits into four stages, and the rest of the lesson follows them in order. First, cut the text into tokens and clean them. Second, turn tokens into numbers: counts, weights or vectors. Third, model those numbers as topics, embeddings or language models. Fourth, build applications on top.
Tokenization: deciding what counts as a word
Tokenization splits a string into units called tokens. Tokens are usually words, pieces of words or punctuation marks. That sounds trivial until you try it on T-1041. If you split on spaces, the token is drane. with the full stop attached, so it never matches drane anywhere else. 3rd, E24 and KD-450 each force a decision: keep the string as one token, split it, or drop it?
Libraries make those decisions for you unless you look. scikit-learn's TfidfVectorizer, a standard Python text vectorizer, lowercases text by default and uses no stop-word list unless you supply one.[3] Its default token pattern keeps tokens of two or more alphanumeric characters and treats all punctuation as a separator.[3] Here is what that does to two Kestrel messages:
T-1041: dishwasher wont drane e24 code again 3rd time since march
T-1042: the kd 450 is not draining and the error code is e24
Read the output closely. The hyphen split KD-450 into kd and 450, so the product name no longer exists as a feature. A one-character word such as I or a would silently vanish. wont survives only because the customer left out the apostrophe. Had they written won't, the pattern would keep won and drop the single t. None of these is a bug. Each is a modeling choice that someone should make on purpose, for example by writing a custom token pattern that keeps model numbers in one piece.
Large language models tokenize differently. They use subword tokenizers, most often Byte-pair encoding (BPE). BPE learns a vocabulary of frequent word pieces from simple statistics of letter sequences in a training corpus.[1] A common word stays whole. A rare or misspelled word, such as drane, is broken into smaller pieces the model already knows. So a modern model never meets a completely unknown word, at the cost of tokens that a person would not recognize as words. Both approaches rest on regular expressions (RegEX), the pattern language tokenizers use to describe what a token looks like. Languages written without spaces between words, such as Chinese and Japanese, make the word-splitting decision harder still.
So what?: tokenization is the first modeling decision, not a clerical step. If a product code is split or a negation is dropped here, no later model can recover it.
Stop words: the commonest words, and when to keep them
Stop words are very frequent words, such as the, and and of, that are often removed before modeling. Any word count shows why. Jurafsky and Martin count a Shakespeare corpus with a one-line Unix pipeline and find the 27,378 times, and 26,084 times and i 22,538 times at the top of the list.[1] In every corpus the top of the list looks like this: short function words such as articles, pronouns and prepositions. They say little about what a particular document is about. Dropping them shrinks the vocabulary and stops them from dominating counts and topics.
You can get a stop-word list in two ways. You can use a fixed list for the language, or you can let the corpus define one. scikit-learn's max_df parameter ignores any term that appears in more than a chosen share of documents. Its documentation notes that setting max_df to a value in the range 0.7 to 1.0 can detect stop words automatically.[3] It does this by filtering terms on their document frequency within the corpus.[3] At Kestrel, dishwasher might appear in a large share of messages. For a model that only ever sees dishwasher tickets, it behaves like a stop word even though no English list contains it.
Now the trap. Many general-purpose English stop-word lists include not, no and nor. Remove them from T-1042 and "is not draining" becomes "draining". A complaint about a fault now reads like a description of normal operation. For topic modeling, search and document clustering, a stop-word list usually helps. For sentiment analysis, intent detection, or any task where negation flips the meaning, keep the negators or skip stop-word removal altogether. Transformer-based models are normally given the full text, because they learn what function words contribute.
Stemming and lemmatization: two ways to merge word forms
Kestrel's tickets contain drain, drains, drained and draining. To a counting model these are four unrelated columns, so the evidence for one complaint is split four ways. Two techniques merge them.
Stemming cuts affixes off words using fixed rules and keeps whatever is left. The idea is old: J. B. Lovins published a stemming algorithm in 1968, and Martin Porter's 1980 algorithm became the standard rule set for English. A stemmer is fast and needs no dictionary. But its output need not be a real word, and its rules cannot tell when two words that share a stem are unrelated.
Lemmatization reduces each word to its lemma, the dictionary form you would look up. was becomes be, batteries becomes battery, and the adjective better becomes good. To do this, a lemmatizer needs a dictionary and the word's part of speech. meeting as a noun stays meeting, but meeting as a verb becomes meet.
| Word (part of speech) | Stem | Lemma | What it shows |
|---|---|---|---|
| draining (verb) | drain | drain | Both merge regular forms |
| batteries (noun) | batteri | battery | A stem need not be a word |
| was (verb) | wa | be | Only a dictionary knows irregular forms |
| better (adjective) | better | good | Comparatives need a dictionary |
| meeting (noun) | meet | meeting | The lemma depends on the part of speech |
| university, universe | univers, univers | university, universe | Overstemming merges unrelated words |
The last row shows the classic stemming failure, called overstemming: two unrelated words collapse to the same stem. The opposite failure, understemming, leaves related forms apart. An example is a stemmer that never joins bought and buy. Which should Kestrel use? For a search box, or a bag-of-words classifier with plenty of data, a stemmer's speed and recall usually win, and an occasional collision costs little. For anything a person reads, such as topic labels or extracted keywords, lemmas are worth the extra cost because they are real words.
Part-of-speech tagging: labeling each token's grammatical role
Part-of-speech tagging (POS tagging) gives each token a grammatical category, such as noun, verb or adjective. English taggers commonly use the Penn Treebank tag set. In that set, NN is a singular noun, NNP a proper noun, VBD a past-tense verb, JJ an adjective, DT a determiner and CD a number. A tagger reading T-1045 produces something like this:
You/PRP charged/VBD my/PRP$ card/NN twice/RB for/IN the/DT KD-450/NNP on/IN 3/CD October/NNP ./.
Tagging is rarely the goal in itself. It feeds other steps. The lemmatizer needs it, as the meeting row showed. Phrase extraction uses tag patterns, such as an adjective followed by a noun, to pull out loud noise or slow drain. Named-entity recognizers commonly use POS tags as input features, alongside word embeddings and the surrounding context.[4] Tags also begin disambiguation. charged tagged VBD next to card describes a billing action, while charge tagged NN after battery describes stored power. Taggers infer each tag from context, so they make more mistakes on short, ungrammatical text such as chat messages. Those mistakes then flow into every step that uses the tags.
String indexing and augmenters: the last steps before a model
Models do arithmetic on numbers, not on strings. String indexing here means mapping each distinct string to an integer position. A vectorizer builds a vocabulary that gives every token a column number. Apache Spark's StringIndexer does the same for a column of category labels. By default it gives index 0 to the most frequent label. For Kestrel the mappings look like this:
vocabulary : {'battery': 0, 'charge': 1, 'dishwasher': 2, 'drain': 3, 'drone': 4, 'e24': 5, ...}
team labels: drainage -> 0.0, billing -> 1.0, drone_battery -> 2.0
Three things go wrong with indexes. First, an index is an identifier, not a quantity. drone_battery is not twice billing, so integer codes must be one-hot encoded or passed to an embedding layer, never treated as magnitudes. Second, the mapping must be fitted on training data and then frozen. If you refit it on new data, every column silently changes meaning. Third, tokens never seen in training need a rule: either an unknown-token slot or being ignored. These are the same encoding habits taught for categorical columns in Atlas's Data+ course, applied to words.
String indexing also covers positions inside a string. A named-entity recognizer reports each entity as a start and end character offset. Python's slice text[34:40] returns the characters at positions 34 to 39, with the end position excluded. Offsets break if the text changes after they were computed, for example when accents or emoji are stripped. Store them against the exact text you annotated.
Augmenters create extra training examples by changing existing text in ways meant to keep its label. Open-source libraries such as nlpaug offer augmenters that work at three levels:
- Character level: insert realistic typos, such as swaps with a neighboring keyboard key (drain to dtain) or optical character recognition errors, so a model copes with messy input.
- Word level: replace words with synonyms from a thesaurus or with nearest neighbors in an embedding space, or randomly insert, swap or delete words.
- Sentence level: paraphrase whole sentences, for example by back-translation (translate into French and back again) or by asking a language model to reword the text.
Augmentation helps most when labeled text is scarce or a class is rare. It is the text counterpart of synthetic oversampling methods such as the Synthetic Minority Oversampling Technique (SMOTE), met earlier in the course. It has two hard rules. The change must not alter the label: randomly deleting not from a negative review creates a positive-sounding example with a negative label, and the model learns the wrong lesson. And augmentation happens after the train-test split, on training data only. If augmented copies of a test message land in training, the model has seen the test, and your scores are inflated.
So what?: every preparation step removes information on purpose. Choose each one by asking what your task needs to keep: negation for sentiment, whole product codes for routing, real words for anything a person will read.
Bag of words, n-grams and the document term matrix
With clean tokens, Kestrel can turn each message into numbers. The Bag-of-words model records how often each token appears in a document and throws away the order. Two short drone reviews show what that costs:
| Review | Unigrams (single tokens) | Bigrams (adjacent pairs) |
|---|---|---|
| R1: battery good, not noisy | battery, good, not, noisy | battery good, good not, not noisy |
| R2: battery noisy, not good | battery, good, not, noisy | battery noisy, noisy not, not good |
R1 is praise and R2 is a complaint, but their unigram bags are identical, so a unigram model must give them the same score. An n-gram is a run of n adjacent tokens: unigrams for n = 1, bigrams for n = 2, trigrams for n = 3. Adding bigrams restores local order, and not good becomes a feature of its own. In scikit-learn this is the ngram_range setting: (1, 2) means unigrams and bigrams together, and (2, 2) means bigrams only.[3]
The price is size. Each increase in n multiplies the number of possible features, and most of them are seen only once. So n-gram models are usually paired with a minimum document frequency (min_df) that drops rare features. Character n-grams, runs of letters rather than words, are a useful variant for misspelled text. drane and drain share the character bigrams dr and ra even though the words differ.
Stack the bags for a whole corpus and you get the Document-term matrix (DTM). It has one row per document, one column per vocabulary term, and in each cell the count of that term in that document. Here is Kestrel's matrix for four messages after tokenizing, lemmatizing and removing stop words.
| Document | battery | charge | dishwasher | drain | drone | e24 | noisy | slow |
|---|---|---|---|---|---|---|---|---|
| D1: e24 dishwasher drain e24 | 0 | 0 | 1 | 1 | 0 | 2 | 0 | 0 |
| D2: dishwasher noisy | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
| D3: drone battery charge | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 |
| D4: dishwasher drain slow | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 |
| Document frequency (df) | 1 | 1 | 3 | 2 | 1 | 1 | 1 | 1 |
Two properties of a DTM matter in practice. First, it is sparse. A real Kestrel vocabulary might hold 40,000 terms while a typical message uses about 30, so more than 99.9 percent of the cells are zero, and libraries store only the nonzero entries. Second, its columns are independent. noisy and loud get separate columns, with no notion that they mean nearly the same thing. Word embeddings exist to fix that second property. The transpose, with terms as rows and documents as columns, is called a term-document matrix and holds the same information.
TF-IDF: weighting a word by how much it tells you
Raw counts treat every term alike. Look at D1. It counts dishwasher once and e24 twice, but dishwasher appears in three of the four documents, so it barely separates D1 from the rest. tf-idf, term frequency-inverse document frequency, fixes this. It multiplies how often a term occurs in this document by how rare the term is across the corpus. The scheme comes from information retrieval, and Blei, Ng and Jordan credit it to Salton and McGill, writing in 1983.[5] They describe it as reducing each document to a vector of real numbers built from ratios of counts.[5]
Define the symbols first. N is the number of documents in the corpus. tf(t, d) is the count of term t in document d. df(t) is the number of documents that contain t at least once. The textbook form, with the natural logarithm ln, is:
idf(t) = ln( N / df(t) )
tfidf(t, d) = tf(t, d) x idf(t)
Work through D1 with N = 4, using the df row of the matrix:
| Term | tf in D1 | df | idf = ln(4 / df) | tf x idf |
|---|---|---|---|---|
| dishwasher | 1 | 3 | ln(1.333) = 0.288 | 0.288 |
| drain | 1 | 2 | ln(2) = 0.693 | 0.693 |
| e24 | 2 | 1 | ln(4) = 1.386 | 2.773 |
The error code now dominates D1's vector, which is what a support analyst wants: e24 is what makes this message different from the others. Now change one input. Suppose the team limits the corpus to dishwasher messages, so the corpus is D1, D2 and D4, and N = 3. dishwasher now appears in all three documents. Its idf is ln(3/3) = ln(1) = 0, so its weight is zero in every document. drain falls to 1 x ln(3/2) = 0.405, and e24 becomes 2 x ln(3) = 2.197. Same word, same message, a different weight, because idf belongs to the corpus, not to the word. A model fitted on one corpus and applied to another carries the first corpus's idf values with it. That is why the vectorizer is fitted on training data and then reused unchanged.
Libraries adjust the textbook formula. scikit-learn's TfidfVectorizer defaults to smooth_idf=True, sublinear_tf=False and norm='l2'.[3] Smoothing adds one to the document counts, as if one extra document contained every term, so no df is ever zero. scikit-learn also adds 1 to every idf, so a term found in every document keeps a small positive weight instead of exactly zero. The l2 norm rescales each row to length 1, so a long complaint and a short one are comparable. After that scaling, the dot product of two rows equals their cosine similarity:
cos(a, b) = (a . b) / ( ||a|| x ||b|| )
Here a . b is the dot product of vectors a and b, and ||a|| is the length of a. For count and TF-IDF vectors, which contain no negative numbers, cosine similarity runs from 0 (no shared terms) to 1 (same direction). It is the usual way to find the existing message or help article closest to a new one.
So what?: TF-IDF rewards terms that are frequent here and rare elsewhere. The weights are relative to a corpus, so changing the corpus changes the weights even when the document is identical.
Edit distance: should drane become drain?
T-1041 says drane. Kestrel's vocabulary has no such word, so the team wants to map misspellings to the nearest known word. Edit distance measures how similar two strings are by the number of edits (insertions, deletions and substitutions) needed to turn one into the other.[1] When each edit costs 1, the result is the Levenshtein distance. It is computed by dynamic programming. Let D(i, j) be the distance between the first i characters of the source and the first j characters of the target. Then:
D(i, 0) = i D(0, j) = j
D(i, j) = min( D(i-1, j) + 1, delete source[i]
D(i, j-1) + 1, insert target[j]
D(i-1, j-1) + (0 if source[i] = target[j] else 1) ) match or substitute
Fill the table one row at a time. Each cell needs only three neighbors: the cell above, the cell to the left, and the cell diagonally above-left. Here the source drane runs down the rows and the target drain runs across the columns:
| Source / target | (empty) | d | r | a | i | n |
|---|---|---|---|---|---|---|
| (empty) | 0 | 1 | 2 | 3 | 4 | 5 |
| d | 1 | 0 | 1 | 2 | 3 | 4 |
| r | 2 | 1 | 0 | 1 | 2 | 3 |
| a | 3 | 2 | 1 | 0 | 1 | 2 |
| n | 4 | 3 | 2 | 1 | 1 | 1 |
| e | 5 | 4 | 3 | 2 | 2 | 2 |
The bottom-right cell is 2. Trace the path back to see why. d, r and a match at no cost, which is the diagonal of zeros. From the 0 at row a, column a, step right to the 1 at column i: that is an insertion of i. Step diagonally to the 1 at row n, column n: n matches n at no cost. Step down to the 2 at row e: the final e is deleted. Two edits in total.
Now change one input: add Kestrel's other product line to the candidate list. Turning drane into drone needs a single substitution, a to o, so its distance is 1. A spelling corrector that simply picks the nearest candidate rewrites "Dishwasher wont drane" as "Dishwasher wont drone". The arithmetic is right and the correction is wrong, because edit distance counts characters and knows nothing about meaning, context or which words are common. Practical correctors combine the distance with how likely each candidate is in context, for example how often drain appears near dishwasher in the corpus. Another fix is to restrict the candidates to the product category already detected.
Edit distance turns up wherever strings must be compared. Fuzzy matching of product codes uses it: KD450 and KD-450 are one insertion apart. A common variant, Damerau-Levenshtein distance, counts a swap of two adjacent letters as one edit, so hte to the costs 1 instead of 2. Run over words instead of characters, the same algorithm aligns a speech transcript with a reference transcript. In speech recognition, that alignment is how word error rate is computed.[1] Kestrel's call T-1044 makes the calculation concrete:
Reference : the dishwasher will not drain (5 words)
Hypothesis: the dish washer will drain
Alignment : the = the
dishwasher -> dish substitution (S)
(none) -> washer insertion (I)
will = will
not -> (none) deletion (D)
drain = drain
WER = (S + D + I) / words in reference = (1 + 1 + 1) / 5 = 0.60
A word error rate (WER) of 60 percent on one call is poor, but notice what the metric cannot see. Splitting dishwasher into two words is harmless to a reader. Deleting not reverses the complaint. WER weighs the two errors equally. And because its denominator is the length of the reference, WER can exceed 100 percent when a system inserts many words.
So what?: edit distance measures surface form, not meaning. It is ideal for typos, codes and transcript alignment, and it needs context or word frequency before it can safely choose between candidates.
Topic modeling with Latent Dirichlet Allocation
The head of support's first request, recurring problems ranked by volume, has no labels to learn from. Nobody has tagged 52,000 messages. Topic modeling finds themes in an unlabeled corpus, and the standard model is Latent Dirichlet allocation (LDA), introduced by David Blei, Andrew Ng and Michael Jordan in 2003.
LDA is a generative model. It tells a story about how documents could have been written, then works backward from the observed words to the most plausible version of that story. With K topics and a vocabulary of V words, the story is:
- Each topic k is a probability distribution over the V words, written βk (beta). Topic 0 might put high probability on drain, e24 and pump.
- Each document d has its own topic proportions θd (theta), a probability distribution over the K topics. θd is drawn from a Dirichlet distribution with parameter α (alpha). T-1045 might be 70 percent billing and 30 percent drainage.
- For each word position in document d, first draw a topic z from θd, then draw the word from that topic's distribution βz.
The Dirichlet distribution is a distribution over probability vectors, and it controls how concentrated the mixtures are. A small α (below 1) favors documents dominated by a few topics. A large α favors documents spread evenly across many topics. A second prior, usually called η (eta), does the same for how many words each topic concentrates on. Fitting LDA means inferring θ for every document and β for every topic from the observed words alone.
Three features of LDA matter for the exam and for practice. First, it is a bag-of-words model that ignores word order. The models Blei and colleagues compared were all unigram models.[5] Its input is therefore a document-term matrix of raw counts, and scikit-learn's own example feeds it a matrix of token counts like the one its CountVectorizer produces.[6] Second, every document is a mixture. K-means clustering puts each message in exactly one cluster; LDA gives each message a proportion for every topic. Third, LDA is a proper probabilistic model of new documents. Blei and colleagues contrast it with an earlier method, probabilistic latent semantic indexing (pLSI), which offers no natural way to assign a probability to a document it was not trained on.[5] LDA can score next week's messages and assign them topics.
In scikit-learn, LatentDirichletAllocation fits the model with an online variational Bayes algorithm.[6] By default it fits n_components=10 topics with the batch learning method.[6] If you leave both priors unset, each defaults to 1/n_components. The documentation adds that on large datasets the online update is generally much faster than the batch update.[6] A fit looks like this:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
counts = CountVectorizer(min_df=5, max_df=0.7, stop_words='english')
X = counts.fit_transform(messages) # document-term matrix of counts
lda = LatentDirichletAllocation(n_components=12, learning_method='online',
random_state=0)
doc_topics = lda.fit_transform(X) # one row of 12 proportions per message
| Topic | Top words by probability | Label a person gave it | Share of messages |
|---|---|---|---|
| 0 | drain, e24, water, pump, filter | Drainage fault | 18% |
| 3 | delivery, driver, window, reschedule, date | Delivery scheduling | 14% |
| 5 | charge, card, refund, twice, invoice | Billing errors | 11% |
| 8 | battery, drone, charge, flight, minute | Drone battery life | 9% |
The share column is the average of each topic's proportion across all messages, which gives the ranking the head of support asked for. Notice that charge appears in two topics. LDA lets a word belong to several topics, and the rest of a message decides which topic explains it. That is a crude form of disambiguation.
Choosing K is the hard part, and the model will not do it for you. The usual numeric guide is held-out perplexity, which scikit-learn defines as exp(-1 x log-likelihood per word), so lower is better.[6] Perplexity and human judgments of topic quality do not always agree, so teams also read the top words, compute topic coherence scores, and ask whether each topic is something a team could act on. Other failure modes are common. Without stop-word removal, the top words of every topic are the and and. Very short texts such as chat lines hold too few words to estimate a mixture well. Different random seeds can produce different topics, so fix the seed and check stability. And topics have no names: a person labels them, and that label is a judgment, not a model output.
One acronym trap: LDA also stands for linear discriminant analysis, a supervised classifier. scikit-learn's page for the topic model even lists that classifier in its See also section. If a question mentions topics, documents and word distributions, it means Latent Dirichlet Allocation.
So what?: LDA turns an unlabeled corpus into ranked themes, with each document a mixture of topics. You still choose K, read the topics, and name them yourself.
Word embeddings: word2vec and GloVe
The document-term matrix gives noisy and loud separate columns, so a review that says one and a review that says the other have a cosine similarity of zero. A Word embedding fixes this by representing each word as a real-valued vector.[7] Unlike a DTM row, the vector is dense, usually somewhere between 50 and a few hundred dimensions, and every dimension is used by every word. The vectors are learned from the distributional hypothesis: words used in similar contexts tend to have similar meanings, so a model trained on context maps semantically similar words to geometrically close vectors.[8] Google's machine learning course shows this with the training sentence "They rode a burro down into the Grand Canyon" and a matching sentence about a horse, which place burro and horse in similar contexts.[9]
Word2vec, from Tomas Mikolov and colleagues in 2013, learns vectors by prediction over a small sliding window. The GloVe paper summarizes its two architectures, skip-gram and continuous bag-of-words (CBOW), as simple single-layer models built on the inner product of two word vectors.[7] Skip-gram uses the center word to predict each word around it. CBOW uses the surrounding words to predict the center word. For a center word c and an observed context word o, skip-gram's probability is a softmax over the whole vocabulary:
P(o | c) = exp(u_o . v_c) / (sum over every vocabulary word w of exp(u_w . v_c))
Here v_c is the center word's vector and u_o is the context word's vector. Training nudges the vectors so that real context pairs get high dot products. Summing over the whole vocabulary is expensive, so practical versions approximate the denominator. Negative sampling, for example, contrasts each real pair with a few randomly chosen words.
GloVe (Global Vectors), from Jeffrey Pennington, Richard Socher and Christopher Manning at Stanford in 2014, starts from the other end. It first counts, over the whole corpus, how often each word appears near each other word, building a word-word co-occurrence matrix X. It then fits word vectors by weighted least squares, training only on the nonzero cells of that matrix rather than on the whole sparse matrix or on individual context windows.[7] The objective asks that the dot product of two word vectors, plus bias terms, approximate the logarithm of their co-occurrence count:
J = sum over word pairs (i, j) of f(X_ij) x ( w_i . w~_j + b_i + b~_j - ln X_ij )^2
Here w_i and w~_j are the two words' vectors, b_i and b~_j are bias terms, and X_ij is the co-occurrence count. The weighting function f limits the influence of very frequent pairs and gives zero weight to pairs never seen together. In short, GloVe uses global counts like the older matrix-factorization methods, and learns compact vectors like the window-based ones. Its authors reported 75 percent accuracy on a word analogy task, the kind that asks man is to king as woman is to what?[7]
Embeddings can also come from plain linear algebra. Principal component analysis (PCA) has been used to create word embeddings by collapsing correlated dimensions of bag-of-words vectors.[8] Latent semantic analysis does the same with a singular value decomposition (SVD) of a term-document matrix. Both are the matrix factorizations met earlier in the course, applied to text.
| Query word | Nearest neighbors (cosine similarity) |
|---|---|
| drain | pump 0.71, clog 0.68, water 0.63, filter 0.60 |
| noisy | loud 0.82, rattling 0.74, grinding 0.70, quiet 0.66 |
| charge | battery 0.69, refund 0.58, card 0.55, recharge 0.54 |
Two rows deserve a second look. quiet sits close to noisy because antonyms share contexts: both describe the same machines in the same sentence frames. Embedding similarity means related, not synonymous. And charge is pulled between batteries and billing because one vector has to serve both senses.
The exam objective lists word2vec and GloVe under large language models. They are not LLMs. They are static word embeddings: each word gets one fixed vector, learned by a shallow model, and neither model generates text. They are ancestors of the token embeddings inside an LLM, which may be why the objectives group them there. Treat them as embedding methods, whatever heading they appear under.
| Representation | Vector size | Dense or sparse | Context used | Same vector for a word in every sentence? |
|---|---|---|---|---|
| Bag-of-words counts (DTM row) | Vocabulary size | Sparse | None; order discarded | Not applicable: one column per word |
| TF-IDF (weighted DTM row) | Vocabulary size | Sparse | Corpus-wide document frequencies | Not applicable |
| Word2vec | Chosen, often 100-300 | Dense | Local window around each occurrence | Yes (static) |
| GloVe | Chosen, often 50-300 | Dense | Global co-occurrence counts | Yes (static) |
| Contextual embedding (transformer, LLM) | Fixed by the model | Dense | The whole input sequence, through attention | No: a new vector for each occurrence |
Disambiguation, contextual embeddings and large language models
T-1043 praises a drone whose battery charge lasts forever. T-1045 complains that Kestrel charged a card twice. A static embedding gives charge the same vector in both messages. Static embeddings assign a single representation per word, while contextual embeddings give a word different representations depending on its context.[8] Google's course uses orange as its example. With one static vector trained on word2vec's data, orange always stays closer to other colors than to juice, whatever sentence it appears in.[8]
Word-sense disambiguation is the task of choosing which meaning of an ambiguous word is in use in a given sentence. IBM uses the homonym mean to show why labeled training data helps NLU systems learn such nuance: supervised examples guide a system to read the word one way in a statistical context and another way in a personality assessment.[10] Choosing between those readings is exactly the disambiguation problem. A related task, entity disambiguation or entity linking, decides which real-world thing a name refers to. Is Kestrel the company or the bird? Which of two customers named J. Smith is this message about? Systems often answer by linking the mention to an identifier in a knowledge base. Classic methods compare the words around the ambiguous term with words associated with each sense. Supervised methods train a classifier on labeled examples. Modern systems read the sense off a contextual embedding.
A contextual embedding gives a word a different vector in each sentence. Transformer models build them with a self-attention layer, which weighs how relevant every other word in the sequence is to each word.[8] The standard form is scaled dot-product attention. Each token's embedding is multiplied by three learned weight matrices to give a query vector, a key vector and a value vector, stacked for the whole sequence into matrices Q, K and V:
Attention(Q, K, V) = softmax( Q K^T / sqrt(d_k) ) V
Read it from the inside out. Q K^T is a table of dot products: how well each token's query matches every other token's key. Dividing by the square root of d_k, the length of a key vector, keeps those scores from growing with the dimension and saturating the softmax. The softmax turns each row into weights that sum to 1. Multiplying by V gives each token a weighted average of the other tokens' values. In T-1045, charged can put heavy weight on card, so its output vector moves toward the billing sense. Transformers also add position information so that word order counts. BERT, an influential transformer, learns these representations by masking part of its input sequence and predicting the hidden parts.[8] Disambiguation becomes a by-product of the representation.
A Large language model (LLM) is a transformer language model with a very large number of parameters, trained on a very large text corpus to predict tokens. A generative LLM rests on the chain rule of probability, which factors the probability of a token sequence into one next-token prediction per position:
P(w_1, w_2, ..., w_n) = P(w_1) x P(w_2 | w_1) x ... x P(w_n | w_1, ..., w_(n-1))
training loss = - sum over t of ln P(w_t | w_1, ..., w_(t-1))
Training minimizes that loss, the cross-entropy of the true next token. Take the exponential of the average loss per token and you get perplexity, the same quantity used to compare LDA models. Three things follow from this design. Its input is subword tokens from a learned vocabulary such as BPE, not whole words. Its internal representations are contextual embeddings, so disambiguation, sentiment and entity types emerge from training rather than from hand-built features. And because it generates text by repeatedly sampling a likely next token, one model can do understanding tasks (classify this message) and generation tasks (draft a reply). You steer it with instructions in a prompt or with a small amount of fine-tuning.
The costs are just as concrete. Inference is slow and expensive next to a TF-IDF model. Outputs can be fluent and false, which is usually called hallucination. Results vary between runs unless sampling is controlled. And customer messages contain personally identifiable information (PII), so sending them to an outside provider is a data governance decision, not just an engineering one. Atlas's Security+ course covers data classification and data protection controls in more depth.
So what?: static vectors give one point per word, so they cannot separate senses. Contextual embeddings give one point per occurrence, which is what makes disambiguation, and much of what LLMs do, possible.
NLU, NLG and the applications Kestrel ships
Two umbrella terms organize the applications. Natural-language understanding (NLU) is a branch of NLP, the broader field of enabling computers to understand and communicate in human language.[10] NLU transforms unstructured speech or text into a structured representation of its content and meaning.[10] It combines syntactic analysis of the words in a sentence with semantic analysis of what is meant. Natural-language generation (NLG) runs the other way. It produces fluent text from data or from an internal representation, as in a weekly summary built from ticket counts or a drafted reply. A simple test sorts most applications: if the output is a label, a score, a span or a structured record, the application is mainly NLU; if the output is new language, it is mainly NLG.
| Application | Input to output | Typical approach | Kestrel's use | Common failure |
|---|---|---|---|---|
| Sentiment analysis (NLU) | Text to polarity or emotion score | Classifier on TF-IDF n-grams, or a fine-tuned transformer | Move angry messages up the queue | Negation, sarcasm, words whose tone depends on the domain |
| Named-entity recognition (NLU) | Text to labeled spans | Sequence labeling with word, POS and context features, or a fine-tuned transformer | Fill product and date fields for routing | Product names never seen in training; wrong span boundaries |
| Auto-tagging (NLU) | Document to a set of tags | Multi-label classifier, or rules over entities and topics | Tag each message by team and product | Tag set goes stale as products change |
| Question answering and dialogue (NLU to read the question and track the conversation, NLG to write the reply) | Question or conversation turn to reply | Retrieve passages, then extract or generate a reply; track state across turns | Chat assistant that answers from help articles | Confident replies the retrieved text does not support |
| Text generation (NLG) | Prompt or data to new text | Language model, or templates for fixed formats | Draft replies for agents to edit | Fluent but wrong facts; wrong tone |
| Text summarization (extractive is closer to NLU, abstractive is NLG) | Long text to short text | Extractive: select sentences. Abstractive: write new ones | Weekly executive paragraph | Abstractive output that says things the source never said |
| Matching models (NLU) | Two texts to a match score | Lexical: TF-IDF cosine, edit distance. Semantic: embedding cosine | Link a new ticket to a known issue; remove duplicates | Threshold set without measuring precision and recall |
| Speech recognition (input side, feeding NLU) and speech generation (output side, voicing NLG) | Audio to text; text to audio | Speech recognizer; text-to-speech synthesis | Transcribe calls; read order status aloud on the phone line | Errors pass silently into every later step |
Sentiment analysis applies machine learning models to identify the mood and emotion in a piece of content, such as social media posts or product reviews.[10] The bigram point applies directly: a unigram model cannot separate R1 from R2. Domain matters too. A word that praises one product can condemn another, so a sentiment model trained on film reviews transfers badly to appliance tickets.
Named-entity recognition (NER) identifies predefined categories of objects in a body of text.[4] The categories can include people, organizations, locations, times, quantities, medical codes, monetary values and percentages.[4] Building a custom recognizer starts with a dataset of annotated text. For T-1045, Kestrel's custom model returns each entity as a span of character offsets, which is where string indexing comes back:
text = 'You charged my card twice for the KD-450 on 3 October.'
PRODUCT text[34:40] -> KD-450
DATE text[44:53] -> 3 October
Off-the-shelf recognizers know people and places, but they do not know Kestrel's product codes. A PRODUCT label needs annotated examples of Kestrel's own text.
Auto-tagging attaches descriptive tags to documents automatically so they can be routed, filtered and searched. It often builds on other outputs. News aggregators, for example, use NER to group articles by the entities they mention.[4] At Kestrel each message gets a tag for its team and one for its product. Because one message can carry several tags, auto-tagging is usually a multi-label problem, with a separate decision threshold for each tag.
Question answering and Dialogue systems respond to a user's question or conversational turn. ELIZA was a dialogue system with no knowledge at all. Modern virtual assistants such as Alexa and Siri use NLU to work out and carry out what the user asked for.[10] The work splits cleanly. Working out what was asked, which entities it mentions and what it refers to from earlier turns is NLU. Writing the reply is NLG. Extractive question answering, which copies a span out of a document as the reply, is almost entirely NLU. Kestrel's chat assistant retrieves the most relevant help articles for a question, then has a language model answer only from them. Dialogue adds state: in the third turn, the system must remember that it means the KD-450 from the first turn.
Text generation produces new text: drafted replies, product descriptions, even synthetic training examples. Templates still win for fixed formats such as order confirmations, because a template cannot invent facts. Automatic summarization comes in two kinds. Extractive summarization selects the most representative existing sentences, for example those with the highest TF-IDF similarity to the rest of the document. Every sentence is faithful, but the result can read choppily. Abstractive summarization writes new sentences with a generative model. It reads well but can state things the source never said. For the executive summary, Kestrel generates the paragraph from the LDA topic shares and message counts, then checks every number against the data before sending it.
Matching models score whether two pieces of text refer to the same thing or meet the same need. Lexical matchers use TF-IDF cosine or edit distance and excel at near-duplicates and codes. Semantic matchers compare embeddings, so "won't empty" can match a help article titled "Water stays in the tub" even with no shared words. A common two-stage design uses a fast embedding comparison to retrieve candidates, then a slower model that reads both texts together to rerank them. Either way, tune the match threshold on labeled pairs, using precision and recall as you would for any classifier.
Speech recognition turns audio into text, and its output then goes through NLU like any typed message. Speech synthesis, also called text-to-speech, is the generation half: it voices text, often text an NLG step just wrote, as on a phone line that reads out an order status. Recognized text enters the same pipeline as typed messages, so its errors spread. T-1044's missing not would send a drainage complaint to the no-issue pile. Measure WER on a sample of your own calls, and look specifically at errors on negations, numbers and product names, which matter far more than split compound words.
Reading the exam's cues
| The stem says | Think | Do not confuse with |
|---|---|---|
| Dictionary form; output must be a real word; uses part of speech | Lemmatization | Stemming, which cuts suffixes by rule |
| Fast suffix stripping; output may not be a word | Stemming | Lemmatization |
| Rows are documents, columns are terms, cells are counts | Document term matrix | Word-word co-occurrence matrix, used by GloVe |
| Down-weight words that are common across the whole corpus | TF-IDF | Stop-word removal, which deletes words outright |
| Word order lost; not good scored like good | Bag of words; fix with n-grams | Stemming |
| Minimum insertions, deletions and substitutions; spelling; fuzzy match | Edit distance | Cosine similarity of TF-IDF vectors |
| Unlabeled corpus; themes; each document a mixture of themes | Latent Dirichlet Allocation | Linear discriminant analysis; k-means, which gives one cluster per document |
| Predict context words from a local window | Word2vec (skip-gram or CBOW) | GloVe |
| Global co-occurrence counts; weighted least squares | GloVe | Word2vec |
| Same word, different meaning in different sentences | Disambiguation; contextual embeddings | Static embeddings, which cannot separate senses |
| Predict the next token; self-attention; prompt | Large language model | Word2vec and GloVe, which give static vectors and generate nothing |
| Extract people, organizations, dates, amounts | Named-entity recognition | POS tagging, which labels grammar, not entity type |
| Extra labeled sentences made by synonym swaps or typos | Augmenters | SMOTE, which interpolates numeric feature vectors |
| Map category strings to integer IDs | String indexing | Tokenization |
| Accuracy of a transcript | Word error rate, from edit distance over words | Character-level accuracy |
| Turn text into structured meaning | NLU | NLG |
| Produce text from data or a representation | NLG | NLU |
Common misconceptions
- "Always remove stop words." Standard lists include not and no. Removing them reverses negative messages, so sentiment and intent models usually keep them, and transformer models take the full text.
- "Stemming and lemmatization are interchangeable." A stemmer applies suffix rules and can output non-words (batteri) or merge unrelated words (universe, university). A lemmatizer uses a dictionary and the part of speech and returns real words.
- "Word2vec and GloVe are large language models." The objective lists them under that heading, but they are static word embeddings from shallow models: one vector per word, no text generation, no sentence context.
- "A high TF-IDF weight means a word is frequent." It means frequent in this document and rare in the corpus. In the textbook formula, a word found in every document has idf ln(1) = 0, however often it appears.
- "LDA in an NLP question means linear discriminant analysis." In topic modeling, LDA is Latent Dirichlet Allocation, an unsupervised generative model. The classifier shares only the initials.
- "A low word error rate means the transcript is safe to analyze." WER counts every word error equally, and one dropped not can reverse a complaint.
The short version
- Tokenization choices are modeling choices. scikit-learn's default pattern keeps tokens of two or more alphanumeric characters, so KD-450 splits into kd and 450. LLMs use learned subword vocabularies such as BPE.
- Stop-word removal shrinks the vocabulary but can delete negation. A max_df threshold finds stop words specific to your corpus.
- Stemming strips suffixes by rule and can produce non-words. Lemmatization returns dictionary forms and needs part-of-speech tags.
- A document term matrix has one row per document and one column per term. Bag of words discards order; n-grams restore local order at the cost of many more features.
- In its textbook form, TF-IDF = tf x ln(N / df). A term in every document gets idf 0, and every weight changes when the corpus changes.
- Levenshtein edit distance counts insertions, deletions and substitutions using dynamic programming, and it ignores meaning. Over words, it gives word error rate = (S + D + I) / reference words.
- LDA models each document as a mixture of topics and each topic as a distribution over words, fitted on bag-of-words counts. The analyst chooses K and labels the topics.
- Word2vec learns static vectors by predicting context in a local window. GloVe fits vectors to global co-occurrence counts. Neither is an LLM, and neither separates word senses.
- LLMs are transformers trained to predict the next token, and self-attention, softmax(QK^T / sqrt(d_k))V, gives each occurrence its own contextual vector. NLU applications (sentiment, NER, auto-tagging, matching) output labels or structure; NLG applications (generation, abstractive summaries, replies) output new text.
Sources
- Daniel Jurafsky and James H. Martin. (2025). Words and Tokens (SLP3 Chapter 2, Aug 2025 draft). Stanford University. web.stanford.edu
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- scikit-learn. (n.d.). sklearn.feature_extraction.text.TfidfVectorizer. scikit-learn.org
- IBM. (n.d.). What is named entity recognition? ibm.com
- David M. Blei, Andrew Y. Ng, Michael I. Jordan. (2003). Latent Dirichlet Allocation (PDF). Journal of Machine Learning Research / Columbia University. cs.columbia.edu
- scikit-learn. (n.d.). LatentDirichletAllocation. scikit-learn.org
- Jeffrey Pennington, Richard Socher, Christopher D. Manning. (2014). GloVe: Global Vectors for Word Representation. ACL Anthology (EMNLP 2014). aclanthology.org
- Google for Developers. (n.d.). Embeddings: Obtaining embeddings. developers.google.cn
- Google for Developers. (n.d.). Embeddings: Embedding space and static embeddings. developers.google.cn
- IBM. (n.d.). What is natural language understanding (NLU)? ibm.com
- Key terms
- Tokenization
- Splitting a string of text into units called tokens, such as words, subword pieces or punctuation, so that a model can count or embed them.
- Bag of words
- A text representation that records how often each token appears in a document and discards word order.
- Document term matrix
- A matrix with one row per document and one column per vocabulary term, where each cell holds the count or weight of that term in that document; usually very sparse.
- TF-IDF
- Term frequency-inverse document frequency: a weight equal to a term's count in a document times the log of (number of documents / number of documents containing the term), so terms rare in the corpus score higher.
- Lemmatization
- Reducing a word to its dictionary form (lemma) using a vocabulary and the word's part of speech, for example was to be and better to good.
- Stemming
- Removing word endings with fixed rules to merge related forms quickly; the result may not be a real word, for example batteries to batteri.
- Edit distance
- The minimum number of insertions, deletions and substitutions needed to turn one string into another; with unit costs it is the Levenshtein distance.
- Latent Dirichlet Allocation
- An unsupervised generative topic model that treats each document as a mixture of topics and each topic as a probability distribution over words, fitted on word counts.
- Word embedding
- A dense vector of real numbers representing a word, learned from the contexts it appears in, so that related words have nearby vectors; word2vec and GloVe produce static embeddings.
- Named-entity recognition
- An NLP task that finds spans of text referring to predefined categories such as people, organizations, places, dates and amounts, and labels each span with its category.
Computer Vision
- Choose among image classification, object detection, semantic and instance segmentation, optical character recognition and tracking for a scenario, and compute Intersection over Union to score a detection.
- Explain how tracking-by-detection keeps object IDs across frames and why occlusion longer than a tracker's memory causes identity switches.
- Explain why sensor fusion makes estimates more robust, and compute an inverse-variance fused estimate when one sensor's uncertainty changes.
- Select data augmentation techniques (flipping, rotation, scaling, cropping, filter application, spurious noise, holes, masking, occlusion) that keep labels true, and apply them to the training set only.
Track 17 walks behind a pallet stack
At 02:14:06 on a night shift, camera 3 on a forklift mast logged a worker as track 17. It lost him behind a stack of pallets and picked him up 1.3 seconds later as a brand-new track 23, standing 4.1 meters from the forks. The yard, the camera and the log are a fictional example built for this lesson, but every line is the kind of record a real yard-safety system writes. The system has three jobs. A detector finds people in each video frame. A tracker gives each person a lasting ID number. An alarm sounds when a tracked person comes within 3 meters of the moving forklift.
02:14:06.200 frame 4812 track 17 person score 0.91 box [412,188,468,340] range 9.6 m
02:14:06.233 frame 4813 track 17 person score 0.88 box [415,188,471,341] range 9.5 m
02:14:06.266 frame 4814 track 17 person score 0.52 box [419,190,452,338] range 9.5 m
02:14:06.300 frame 4815 track 17 NO MATCH (coasting 1 of 30)
...
02:14:07.300 frame 4845 track 17 DELETED (missed more than 30 frames)
02:14:07.633 frame 4855 track 23 person score 0.47 box [520,192,575,344] range 4.1 m NEW
02:14:07.666 frame 4856 ALARM suppressed: track 23 age 1 frame < min_age 3
Read the log from the top. In frames 4812 and 4813 the detector is confident, with scores near 0.9, and the box has a normal person shape, about 56 pixels wide and 152 tall. In frame 4814 the score drops to 0.52 and the box narrows to 33 pixels. The worker is half hidden, so the detector sees only half of him. From frame 4815 on, the detector finds nothing, and the tracker "coasts": it keeps predicting where track 17 should be, with no detection to confirm it. Its rule deletes a track once it has gone more than 30 frames in a row without a match, which is one second at 30 frames per second. The worker stays hidden for 40 frames, from 4815 to 4854, so the track is deleted at frame 4845, ten frames before he steps out. When he reappears, the tracker treats him as a stranger, and a newborn track must survive 3 frames before it may trigger an alarm. For those frames the person closest to the forks is invisible to the safety logic.
Before deployment the detector had scored well on a held-out set of daytime photographs. Nothing in that score warned about this night. The failure has four separate causes, and each one is a concept in this lesson:
- The detector's confidence collapsed when the worker was partly hidden, and its training photos rarely showed partly hidden people at night. That is a data augmentation problem.
- The tracker forgot him after one second. That is a tracking problem, specifically occlusion handling.
- The range estimate came from the camera alone, at night, when a camera sees least. That is a sensor fusion problem.
- A box is a coarse answer. It says roughly where the person is, not which pixels are the person and which are pallet. Whether that matters is a choice between object detection and image segmentation.
The yard also reads the shipping labels on pallets, which brings in optical character recognition. By the end of the lesson you will be able to repair each line of that log, and to recognize which concept an exam scenario is describing.
Exam objectives: 5.3 Explain the use and importance of computer vision concepts. The objective lists optical character recognition, object/semantic segmentation, object detection, tracking and sensor fusion, then data augmentation with nine techniques: flipping, filter application, rotation, occlusion, spurious noise, scaling, holes, masking and cropping.[1]
An image is a grid of numbers, and the tasks differ in what they return
A color image is stored as a three-dimensional array: height by width by channels. A 640 by 480 frame with red, green and blue (RGB) channels holds 640 x 480 x 3 = 921,600 numbers, usually integers from 0 to 255. Every computer vision task takes that grid in. What separates the tasks is the shape of the answer that comes out.
Amazon's SageMaker documentation draws the first lines cleanly. An image classifier looks only at whole images and assigns each one to a category.[2] An object detector finds every instance of the classes it knows and marks each one's location and scale with a rectangular bounding box.[2] Semantic segmentation works at the finest grain of all, the individual pixel.[2]
| Task | Question it answers | Output | Labeling effort | Typical metric |
|---|---|---|---|---|
| Image classification | What is in this image? | One label, or label probabilities, per image | One label per image | Accuracy, F1 |
| Object detection | Which objects are where? | Class, confidence score and box for each object | Draw a box per object | Mean average precision (mAP) at an Intersection over Union (IoU) threshold |
| Semantic segmentation | Which class does each pixel belong to? | A mask the size of the image, one class per pixel | Paint every pixel | Per-class IoU, mean IoU |
| Instance (object) segmentation | Which pixels belong to which individual object? | One mask per object, with class and score | Outline every object | Mask average precision |
| Optical character recognition (OCR) | What text is written here, and where? | Words and lines with positions and confidence | Transcribe text and mark its region | Character and word error rates |
| Tracking | Is this the same object as in the last frame? | IDs that persist across frames, with trajectories | Box plus ID in every frame | Identity switches; multiple object tracking accuracy (MOTA) |
Worth holding on to: name the task by its output. One label per image is classification. A class, score and box per object is detection. A class per pixel is semantic segmentation. A separate mask per object is instance segmentation. Text with positions is OCR. IDs that persist across frames is tracking.
Object detection: boxes, confidence scores and Intersection over Union
An object detector returns a list. Each entry has a class, a confidence score between 0 and 1, and a box. Here is a fictional output for one frame:
[
{"class": "person", "score": 0.91, "box": [412, 188, 468, 340]},
{"class": "person", "score": 0.63, "box": [409, 182, 470, 345]},
{"class": "forklift", "score": 0.97, "box": [ 40, 150, 330, 420]}
]
The box format here is [x_min, y_min, x_max, y_max] in pixels. The origin is the top-left corner and y grows downward, the usual convention for images. Other tools store [x, y, width, height], or the box center plus its size, or coordinates divided by the image size so they run from 0 to 1. Mixing two formats is one of the most common bugs in detection code: the numbers look plausible and the boxes land in the wrong place.
To score a detector, you must decide whether a predicted box "found" a ground-truth box, which is the box a human annotator drew. The standard measure is Intersection over Union (IoU): the area where the two boxes overlap, divided by the area they cover together.
IoU(A, B) = area(A ∩ B) / area(A ∪ B)
= I / (area(A) + area(B) - I)
where * means multiply, and the intersection area is
I = max(0, min(xmax_A, xmax_B) - max(xmin_A, xmin_B))
* max(0, min(ymax_A, ymax_B) - max(ymin_A, ymin_B))
IoU runs from 0, no overlap, to 1, identical boxes. The max(0, ...) clamp matters. If two boxes do not overlap, the raw differences are negative, and without the clamp two negative numbers multiply into a positive "overlap".
Worked example. A ground-truth box is [100, 100, 200, 200], so its area is 100 x 100 = 10,000 square pixels. The prediction is [120, 110, 220, 210], also 10,000.
- Overlap width: min(200, 220) - max(100, 120) = 200 - 120 = 80.
- Overlap height: min(200, 210) - max(100, 110) = 200 - 110 = 90.
- Intersection: I = 80 x 90 = 7,200.
- Union: 10,000 + 10,000 - 7,200 = 12,800. You subtract I once because adding the two areas counted the overlap twice.
- IoU = 7,200 / 12,800 = 0.5625.
Under the common rule that a match needs the same class and an IoU of at least 0.5, this prediction is a true positive.
Now change one input. The prediction drifts to [140, 120, 240, 220]. Overlap width is 200 - 140 = 60 and height is 200 - 120 = 80, so I = 4,800. The union is 20,000 - 4,800 = 15,200, and IoU = 0.316. The box still touches the object, but at a 0.5 threshold it counts twice against the model. The prediction is a false positive, and the ground-truth object it failed to match is a false negative. A shift of 20 pixels changed the verdict, which is why detection results always state their IoU threshold.
From those matches you get precision and recall exactly as in Lesson 2. Each ground-truth box may be matched only once, so a second box on an already matched object is a false positive. Average precision is the area under the precision-recall curve for one class as the confidence threshold sweeps from high to low. Mean average precision (mAP) averages it across classes. Some benchmarks also average across several IoU thresholds between 0.50 and 0.95, which rewards tight boxes over roughly placed ones. IoU also appears inside training: one line of research turned it into a loss for fitting the box coordinates themselves.[3]
Detectors propose many overlapping candidate boxes for the same object, and non-maximum suppression (NMS) cleans them up. Sort the boxes of one class by score and keep the highest. Delete every remaining box whose IoU with the kept box exceeds a threshold, often 0.5. Repeat with the next highest survivor. In the fictional output above, the 0.91 person box [412, 188, 468, 340] lies entirely inside the 0.63 box [409, 182, 470, 345]. So the intersection equals the smaller area, 56 x 152 = 8,512, and the union equals the larger area, 61 x 163 = 9,943. IoU is 0.856, far above 0.5, so NMS deletes the 0.63 box as a duplicate.
NMS has a cost in crowds. Two workers walking shoulder to shoulder can produce boxes with IoU above 0.5, and NMS then deletes a real person. Raising the threshold keeps both people but lets more duplicates through. No setting is free; you tune the trade-off on validation data that looks like the deployment.
Semantic segmentation and object segmentation: labeling pixels
A box around a person standing next to a pallet includes a lot of pallet. For an alarm that only needs "someone is about 4 meters away", that is fine. For measuring a tumor's area on a scan, finding the exact edge of a drivable road, or telling a robot gripper where an object's surface ends, it is not.
Semantic segmentation tags every pixel with a class from a predefined set of classes.[2] Its output, called a segmentation mask, is a single-channel image with the same shape as the input, where each pixel's value is a class number.[2] Because every pixel is classified, the mask also captures the shapes of objects, which a box cannot.[2] AWS names self-driving vehicles, medical imaging diagnostics and robot sensing as applications that depend on this kind of scene understanding.[2]
Here is a fictional 6 by 10 mask with classes 0 = background, 1 = person and 2 = forklift. Two people stand side by side on the left. The right-hand grid shows the same scene with a separate ID for each person.
semantic mask (class) instance mask (person ID)
0 1 1 0 1 1 0 0 0 0 0 1 1 0 2 2 0 0 0 0
0 1 1 1 1 1 0 2 2 2 0 1 1 1 2 2 0 0 0 0
0 1 1 1 1 1 0 2 2 2 0 1 1 1 2 2 0 0 0 0
0 1 1 0 1 1 0 2 2 2 0 1 1 0 2 2 0 0 0 0
0 1 0 0 0 1 0 2 2 2 0 1 0 0 0 2 0 0 0 0
0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 2 0 0 0 0
In the semantic mask the two people touch, so their pixels merge into one region of 1s. The model knows those pixels are "person", but it cannot tell you there are two people. Instance segmentation, which the exam objective calls object segmentation, solves that. It produces a separate mask for each individual object, so you can count people and measure each one. Think of it as object detection with a pixel mask in place of each box. Practitioners also use the term panoptic segmentation for the combination: every pixel gets a class, and pixels that belong to countable things, such as people and forklifts, also get an instance ID. Uncountable regions such as floor or sky get a class only.
Two practical details follow from the per-pixel format. First, annotation masks must store class numbers exactly. SageMaker expects its annotations as uncompressed Portable Network Graphics (PNG) images.[2] A lossy format such as Joint Photographic Experts Group (JPEG) compression would smear the boundary between class 1 and class 2 into in-between values that are not classes at all.
Second, the metric must survive class imbalance. If 95 percent of the pixels in a yard image are floor, a model that predicts "floor" everywhere scores 95 percent pixel accuracy and finds no people. The usual metrics compute IoU for each class over its pixels, then average across classes (mean IoU), so the person class counts as much as the floor. The Dice coefficient, 2I / (|A| + |B|), where |A| and |B| are the pixel counts of the two masks, is closely related: Dice = 2 IoU / (1 + IoU). On a single mask, the two always rank models the same way.
Choose between detection and segmentation by the decision the output feeds. Segmentation labels cost far more to make, because an annotator must paint or outline every object instead of dragging one rectangle, and the models are usually heavier. Pay that cost when shape, area or exact boundaries drive the decision.
Worth holding on to: semantic segmentation labels pixels by class and merges touching objects of the same class. Instance (object) segmentation separates the individuals. Measure both with per-class IoU, never with raw pixel accuracy on imbalanced scenes.
Optical character recognition: reading the pallet label
Every pallet in the yard carries a printed label, and the receiving office still types the labels into the warehouse system by hand. Optical character recognition (OCR) turns pixels of printed or handwritten text into machine-readable characters. Microsoft's documentation notes that it is also called text recognition or text extraction.[4]
Modern OCR runs in two stages. A text detection stage finds where text is, usually as boxes or polygons around lines and words, rotated where needed. A recognition stage then reads each region and outputs a sequence of characters. Microsoft's Read engine, for example, returns text as words, lines, and paragraphs or blocks.[4] It gives each page, line and word a location and a confidence score.[4] A fictional result for one label might look like this:
| Line | Recognized text | Confidence | Polygon (pixels) |
|---|---|---|---|
| 1 | SHIP TO: DOCK 14 | 0.99 | (212,40) (498,41) (498,72) (212,71) |
| 2 | PO 448-20317 | 0.97 | (212,88) (431,89) (431,118) (212,117) |
| 3 | LOT B7-0O4 | 0.58 | (212,134) (390,135) (390,163) (212,162) |
| 4 | WT 412 KG | 0.94 | (212,180) (365,180) (365,209) (212,209) |
Line 3 shows the classic OCR failure. A digit zero and a capital letter O look nearly identical, and the engine has read one of each, with low confidence. Nothing in the pixels alone settles it. The fix is downstream logic that knows the domain. Suppose lot numbers always follow the pattern letter, digit, hyphen, three digits. A regular expression (RegEx) such as ^[A-Z][0-9]-[0-9]{3}$ rejects "B7-0O4", and the system can either substitute the only valid reading, B7-004, or send the label to a person. Route low-confidence lines to human review, and log how often reviewers correct the machine: that correction rate is your real-world accuracy.
Resolution is the next thing to check, because OCR cannot read characters the image never resolved. Microsoft's Read documentation gives a minimum text height of 12 pixels in a 1,024 by 768 image, which it equates to about 8-point type at 150 dots per inch (DPI).[4] Apply that to the yard. If the label's capital letters span 8 pixels in the mast camera's frame, they are below the floor. Enlarging the crop in software makes the letters taller in pixels but adds no detail the sensor never captured. The reliable fixes are optical: a closer or higher-resolution camera, a zoom lens, or a dedicated label scanner at the dock door.
Microsoft offers one OCR edition for general, non-document images such as signs, posters and product labels.[4] It offers another, optimized for text-heavy scanned and digital documents.[4] That split reflects a real difference. Document OCR expects flat pages, many lines and a reading order. Scene-text OCR expects a few words at odd angles, under uneven light, on curved or shiny surfaces. A model that is good at one is not automatically good at the other.
Two boundaries keep OCR in its place. First, it transcribes; it does not understand. Pulling the purchase-order number out of the text as a field, or recognizing that "DOCK 14" is a location, is a natural language processing (NLP) step, such as the named-entity recognition (NER) of Lesson 26. Second, OCR earns its keep mainly by removing or sharply reducing manual data entry.[4] So measure it the way the business feels it: errors per thousand labels, and hours of typing saved.
Tracking: turning detections into identities
A detector treats each frame as a fresh photograph. It can report a person at [412, 188, 468, 340] in frame 4812 and a person at [415, 188, 471, 341] in frame 4813, but not that they are the same person. Object tracking supplies that continuity. It lets a system compute speed and direction, count unique people instead of detections, and raise an alarm about one person's path. The dominant design is tracking-by-detection, and the title of one well-known tracker, ByteTrack, states the idea outright: multi-object tracking by associating every detection box.[3]
Each new frame runs through four steps:
- Predict. A motion model moves each existing track forward to where it should be now. The usual tool is the Kalman filter. Trackers discussed in the DFR-FastMOT paper combine a camera with LiDAR (light detection and ranging, a sensor that measures distance by timing laser pulses) and use a Kalman filter to follow objects by estimating their trajectories.[5] The filter keeps a state, such as position and velocity, plus its uncertainty, and it grows that uncertainty every time it predicts without a measurement.
- Associate. Build a cost matrix between predicted tracks and new detections, commonly 1 - IoU, sometimes mixed with an appearance distance from a small neural network. Solve it as an assignment problem, classically with Harold Kuhn's Hungarian method.[5] That method finds the one-to-one pairing with the lowest total cost. Refuse any pair whose IoU falls below a gate, say 0.3, even if it is the best available.
- Update. Each matched track corrects its prediction toward the detection, and its uncertainty shrinks.
- Manage. An unmatched detection starts a tentative track that must be confirmed over a few frames. An unmatched track coasts on predictions and is deleted once its run of consecutive missed frames exceeds a limit, often called max_age. In the convention used here, each frame's matching runs before that check, so a track survives a gap of up to max_age frames and is deleted on the next missed frame.
Association can be very simple. One published tracker performs tracking-by-detection at high speed without using any image information.[5] Without image content, association has to rest on geometry, and the natural choice is box overlap. That works when the frame rate is high and objects move little between frames, so each object's consecutive boxes overlap strongly.
Worked example. Two tracks enter frame t. Track 5's predicted box is [100, 100, 160, 220] and track 9's is [400, 120, 460, 240]. The detector returns D1 = [405, 125, 465, 245] and D2 = [104, 98, 164, 218]. Every box is 60 by 120 pixels, so each area is 7,200.
| Track | D1 | D2 |
|---|---|---|
| Track 5 | 0.00 | 0.85 |
| Track 9 | 0.78 | 0.00 |
For track 5 and D2, the overlap width is min(160, 164) - max(100, 104) = 56 and the height is min(220, 218) - max(100, 98) = 118. So I = 6,608, the union is 14,400 - 6,608 = 7,792, and IoU = 0.85. Track 9 and D1 give I = 55 x 115 = 6,325, a union of 8,075 and IoU = 0.78. The cross pairs do not overlap. The pairing with the lowest total cost, (1 - 0.85) + (1 - 0.78) = 0.37, matches track 5 with D2 and track 9 with D1. The detector's numbering means nothing: D1 is not "the first track". IDs come only from association.
Now change one input. In frame t + 1, track 5 walks behind a rack, and only one detection appears, next to track 9's prediction. Track 9 matches it. Track 5 has nothing to match, so it coasts. If the person stays hidden longer than max_age frames, the track is deleted, and when the person reappears the tracker starts a new ID. That is an identity switch, and it is exactly what happened to track 17 in the opening log.
The research literature names occlusion, an object that stays hidden for a run of frames, as one of the well-known challenges of multi-object tracking (MOT).[5] Trackers store object information such as trajectories in memory so they can recover objects after occlusion.[5] Many keep only a short-term memory to save computation.[5] As a result they lose objects in some occlusions, particularly long ones.[5] The same paper reports that learning-based trackers also fail under prolonged occlusion.[5]
The fixes trade one error for another:
- Longer memory. Track 17's gap was 40 frames, so under the deletion rule above a max_age of 40 would just bridge it, and 45 would leave a margin. But a track kept alive on prediction alone drifts, and it may grab the next person who steps out from behind the rack.
- Appearance cues. A learned description of clothing and body shape, often called re-identification, lets the tracker recognize the returning person even after it deleted the track. It costs extra computation per detection.
- Keeping weak boxes. ByteTrack's idea of associating low-confidence boxes as well helps at the edges of an occlusion. The 0.52 box in frame 4814 and the 0.47 box in frame 4855 are weak, but they are real people, and a tracker that discards everything under 0.6 loses them. The cost is more false tracks from weak false detections.
- Another viewpoint. A second sensor that sees the gap the camera cannot is the fourth option, and it leads to sensor fusion.
Tracking quality is reported with metrics that count identity errors, not just detection errors. Multiple object tracking accuracy (MOTA) combines them: MOTA = 1 - (FN + FP + IDSW) / GT. The sums run over all frames; FN is missed objects (false negatives), FP is false detections (false positives), IDSW is identity switches, and GT is the number of ground-truth objects.
Worth holding on to: a tracker is predict, associate, update, manage. An occlusion longer than the tracker's memory becomes an identity switch, so the fix is longer memory, appearance cues, weak-box association or another sensor, each with its own cost.
Sensor fusion: when the camera goes dark
Sensor fusion combines measurements from several sensors into one estimate that is more accurate, or more robust, than any single sensor gives. The case for it is that sensors fail in different conditions. A camera's effective resolution drops in night scenes.[5] That is the condition in the opening log. A Lidar unit (light detection and ranging) fires its own laser pulses and times their return. It measures distance directly and works in the dark, producing a point cloud, a set of 3D points. Whole detector families, such as PointPillars, work directly on point clouds.[3] Fusion systems combine camera and LiDAR, and some add an inertial measurement unit (IMU) and the Global Positioning System (GPS) to track objects in three dimensions, including their orientation.[5]
| Sensor | What it measures | Strong when | Weak when |
|---|---|---|---|
| Camera | Color, texture, text, dense detail | Good light; classifying and reading | Darkness, glare; no direct depth from one camera |
| LiDAR | 3D points with direct range | Darkness; precise distance and shape | Fog, heavy rain, dust; sparse at long range; no color or text |
| Radar | Range and speed toward or away from the sensor | Rain, fog, darkness | Coarse angular resolution; weak on shape |
| IMU | Acceleration and rotation rate, many times per second | Short-term motion between other readings | Drifts over time when integrated |
| GPS | Absolute position | Open sky | Indoors, under metal roofs, between tall buildings |
Fusion can happen at three points in the pipeline:
| Level | What is combined | Strength | Weakness |
|---|---|---|---|
| Early (data-level) | Raw data, for example LiDAR points projected onto image pixels as an extra depth channel | The model can exploit fine cross-sensor detail | Needs precise calibration and timing; one failed sensor corrupts the input |
| Middle (feature-level) | Features learned by each sensor's own network | Balances detail with flexibility | Complex to build and train |
| Late (decision-level) | Each sensor's own detections or tracks | Simple and modular; degrades gracefully if one sensor fails | Loses detail that neither sensor resolved alone |
The arithmetic of fusing two measurements shows why fusion beats simply picking the "best" sensor. Suppose two sensors measure the same distance, with independent, unbiased errors. The camera reports xc with variance σc2, and the LiDAR reports xL with variance σL2. Here σ is the standard deviation of each sensor's error in meters, so variance is in square meters. The combination with the smallest variance weights each measurement by the inverse of its variance:
fused = (x_c / σc² + x_L / σL²) / (1/σc² + 1/σL²)
variance of fused = 1 / (1/σc² + 1/σL²)
Same rule in Kalman form:
K = σc² / (σc² + σL²)
fused = x_c + K * (x_L - x_c)
The second form is the measurement update of a Kalman filter, with the camera reading playing the role of the prior. That is why the Kalman filter is the workhorse of fusion: it applies this rule at every time step, with the motion model's prediction as one of the inputs.
Worked example. At night the camera estimates the worker at 20.0 m with σ = 2.0 m, a variance of 4.0. The LiDAR reports 21.0 m with σ = 0.5 m, a variance of 0.25.
- K = 4.0 / (4.0 + 0.25) = 4.0 / 4.25 = 0.941. The LiDAR gets about 94 percent of the weight.
- Fused = 20.0 + 0.941 x (21.0 - 20.0) = 20.94 m.
- Variance = 1 / (1/4.0 + 1/0.25) = 1 / (0.25 + 4.0) = 0.235, so σ = 0.485 m.
The fused σ, 0.485 m, is smaller than the LiDAR's own 0.5 m. Adding a worse sensor still helped, because its errors are independent of the LiDAR's.
Now change one input. A crew starts sanding a floor and the air fills with dust, which scatters laser pulses. The LiDAR's σ rises to 4.0 m, a variance of 16, and it reports 25.0 m. The camera, under the yard lights, still has σ = 2.0 m and reads 20.0 m. Now K = 4.0 / (4.0 + 16) = 0.2, so the LiDAR gets only 20 percent of the weight. Fused = 20.0 + 0.2 x 5.0 = 21.0 m, with variance 1 / (0.25 + 0.0625) = 3.2 and σ = 1.79 m. The weighting flipped toward the camera by itself, because the rule follows the uncertainties. That only works if the system's variance values track reality. A system that kept the LiDAR's clear-air variance of 0.25 in dust would trust the 25 m reading almost completely and be badly wrong.
Three practical failures dominate fusion projects:
- Calibration. To place a LiDAR point onto a camera pixel you need the exact rotation and translation between the two sensors (extrinsic calibration) and the camera's lens model (intrinsic calibration). A bracket knocked out of line by a few degrees silently misaligns everything.
- Time synchronization. If camera frames and LiDAR sweeps are time-stamped 50 ms apart and an object moves at 10 m/s, the two sensors disagree by 0.5 m before any measurement error.
- Correlated errors. The formula assumes independent errors. Two cameras blinded by the same low sun are not independent, and fusing them as if they were gives false confidence.
Data augmentation: manufacturing the hard cases
Return to the detector whose confidence collapsed on a half-hidden worker at night. More real night footage of half-hidden people would be the best fix, but it is slow and expensive to collect and label. Data augmentation is the cheaper complement: during training, apply random but realistic transformations to each image so the model sees more variety than the raw data contains. TensorFlow's tutorial demonstrates it with Keras preprocessing layers such as RandomFlip and RandomRotation, alongside Resizing and Rescaling.[6] It lists further layers, including RandomContrast, RandomCrop and RandomZoom.[6] Lower-level tf.image functions cover flipping left to right, converting to grayscale, adjusting brightness and cropping the center.[6]
Augmentation works by teaching invariance. If a worker seen in a mirror is still a worker, then randomly mirroring training images tells the model that left-right orientation is not evidence. The random transforms differ every epoch, so the model rarely sees exactly the same pixels twice. That acts as a regularizer in the sense of Lesson 12: it makes memorizing individual training images harder.
The governing rule appears as a comment in the tutorial's code: use data augmentation only on the training set.[6] In its pipeline the augmentation function is called with training=True and mapped over the training data alone.[6] Validation and test images are only resized and rescaled, because their job is to estimate performance on the unaltered images the deployed model will see.
Watch the two senses of "scaling". The tutorial's Rescaling layer maps pixel values from 0-255 into the range 0 to 1, and notes how to map them into -1 to 1 instead.[6] That is preprocessing, applied identically to every split. Scaling as an augmentation means randomly resizing or zooming the image content, and that happens to training images only.
| Technique | What it does to the image | Real variation it imitates | What must change in the labels | When it backfires |
|---|---|---|---|---|
| Flipping | Mirrors left-right, or top-bottom | Objects facing the other way; camera on the other side | Boxes and masks mirrored; left and right keypoints swapped | Text; classes defined by direction; top-bottom flips of street scenes |
| Rotation | Turns the image by a random angle | Camera tilt, vibration, rotated documents | Boxes recomputed (they grow); masks rotated | Angles the camera never produces; 6 versus 9 |
| Scaling | Zooms in or out, resizes content | Objects at different distances | Box coordinates multiplied by the scale | Small objects shrunk below what the model can resolve |
| Cropping | Keeps a random or central sub-window | Different framing, partial views | Boxes clipped; boxes mostly outside dropped | Cropping away the object that defines a classification label |
| Filter application | Blur, sharpen, brightness, contrast, color jitter, grayscale | Lighting, focus, motion, different cameras | None | When color or sharpness is the signal, such as traffic-light color |
| Spurious noise | Adds random pixel noise, Gaussian or salt-and-pepper | Sensor grain in low light, dead pixels, transmission errors | None | Noise that buries fine texture the task depends on |
| Holes | Erases random rectangles to a constant or random fill | Missing information; stops reliance on one part | Usually none; drop boxes that are fully erased | Hiding the only distinguishing part in small images |
| Masking | Hides pixels chosen by a purposeful mask: background, a channel, private regions | Redaction, missing channels, shortcut removal | Depends on what the mask hides | Masks applied to one class only, which leak the label |
| Occlusion | Pastes realistic occluders over part of the target | Real objects blocking each other | Follow one box convention: full extent or visible part | Pasting artifacts the model learns to spot |
Worth holding on to: an augmentation is legitimate only if the transformed image is still something the deployed camera could plausibly see, and the label, transformed the same way, is still true.
Flipping, rotation, scaling and cropping move pixels, so they move labels
For classification, a geometric transform leaves the label alone: a flipped forklift is still "forklift". For detection and segmentation, the label has coordinates, so the same random parameters must be applied to the boxes and masks. In the tutorial's usage, the Keras layers transform the image only. Check whether your Keras version can carry bounding boxes along with the pixels; if it cannot, use a library that does, or write the box transforms yourself.
Worked example: a horizontal flip in a 640-pixel-wide frame. The person box is [412, 188, 468, 340]. A flip sends each x to 640 - x, so 412 becomes 228 and 468 becomes 172. A mirror swaps left and right, so the old right edge becomes the new left edge, and the flipped box is [172, 188, 228, 340]. A common bug computes the new x_min as 640 - x_min = 228 and the new x_max as 640 - x_max = 172. That produces a box whose "minimum" exceeds its "maximum". Some libraries silently drop such boxes, and the model then learns from images that contain people but carry no person labels.
Rotation needs more care. Rotating a box's four corners produces a tilted shape, and the axis-aligned box that encloses it is larger than the object, so heavy rotation pads boxes with background. Keep the angles to what the camera could really produce. The tutorial's own demonstration stacks RandomFlip and RandomRotation layers, and its code sets the rotation factor to 0.2.[6] Keras reads that factor as a fraction of a full turn, so 0.2 allows rotations of up to 72 degrees either way. That is fine for showing what the layer does, and unrealistic for a camera bolted to a forklift mast, where a factor near 0.03, about 11 degrees, better matches vibration and uneven ground.
Scaling and cropping change what is in the frame. Zooming out shrinks small objects, and a worker 40 pixels tall who becomes 12 pixels tall may fall below what the detector can resolve. Cropping can cut the object out entirely. For classification that turns the label into a lie: a crop that removes the only bird is no longer a "bird" image. For detection, clip each box to the crop and drop boxes that are mostly outside it.
Filter application and spurious noise change values, not positions
Filter application changes pixel values without moving them. Blurring imitates focus error and motion. Brightness and contrast shifts imitate lighting. Color jitter imitates different cameras and bulbs, and grayscale conversion removes color altogether. Labels do not change. The risk is destroying the signal. If the task is telling a red signal light from a green one, a color jitter strong enough to shift hues makes the label false.
Spurious noise adds random values to pixels. Gaussian noise adds small random amounts everywhere, like the grain a camera produces when it boosts gain in the dark. Salt-and-pepper noise forces scattered pixels to black or white, like dead sensor pixels or transmission errors. Noise teaches the model not to depend on pixel-exact textures. For the yard, darkened images plus Gaussian noise imitate night footage far better than darkening alone, because real low-light frames are both dim and grainy. Neither fully reproduces night. Headlight glare, motion blur from long exposures and infrared lighting still need real examples.
Holes, masking and occlusion: three ways to hide part of an image
All three hide part of the image, and the objective lists them separately. Practitioners use the words loosely, so here is a working distinction you can defend:
- Holes erase random rectangles and fill them with a constant, often black or the dataset's mean color, or with random values. Published versions go by the names Cutout and random erasing. The hole has no realistic content. Its purpose is to stop the model leaning on one distinguishing part, such as a face or a hard hat, by sometimes deleting it.
- Masking hides pixels according to a mask chosen for a purpose rather than at random. Examples are blanking the background so the model cannot use it as a shortcut, dropping a color channel, redacting faces or license plates for privacy, or hiding many patches so a model must reconstruct them, as in masked-image pretraining. The mask is a deliberate decision about what the model may see.
- Occlusion pastes realistic occluders, such as cutouts of pallets, racks or other people, over part of the target. It imitates the way objects really block each other. For the yard this is the most direct remedy, because it produces many training images of half-hidden workers.
Occlusion augmentation forces a labeling decision. Does the person's box cover the whole person, including the hidden parts (an amodal box), or only the visible part? Either convention can be right, but training and evaluation data must use the same one. Pasted cutouts also leave artifacts such as unnaturally sharp edges, which a model can learn to spot, and blending the edges helps.
A training pipeline for a classifier might combine several techniques like this. It is a sketch, so check the layers and defaults in the Keras version you actually run:
augment = keras.Sequential([
layers.RandomFlip("horizontal"), # flipping
layers.RandomRotation(0.03), # small rotation, about 11 degrees
layers.RandomZoom(0.2), # scaling
layers.RandomContrast(0.3), # filter application
layers.GaussianNoise(0.05), # spurious noise
])
train_ds = train_ds.map(lambda x, y: (augment(x, training=True), y))
# val_ds and test_ds: resize and rescale only, never augment
One more trap connects to Lesson 12. Augment after splitting, never before. If you make five augmented copies of each image and then split at random, near-duplicates of training images land in the test set, and the test score measures memory rather than generalization. Split by source image. With video, split by clip or by day, because consecutive frames are themselves near-duplicates.
Back to the yard: one remedy per line of the log
| Symptom in the log | Concept | Remedy | Cost or risk |
|---|---|---|---|
| Score fell to 0.52 as the worker was half hidden | Detection under occlusion | Occlusion and hole augmentation; collect real night footage | Pasting artifacts; labeling convention to settle |
| Track 17 deleted after 30 missed frames of a 40-frame gap | Tracking memory shorter than the occlusion | max_age of 45 frames or more; re-identification; associate low-score boxes | Drifting ghost tracks; wrong re-association |
| Range came from the camera alone at night | Sensor fusion | Fuse LiDAR range with camera detections, weighted by variance | Calibration and time-sync work |
| Validation set held only daytime photos | Evaluation mismatch | Build an unaugmented night validation set | Labeling time |
| Labels still typed by hand at the dock | OCR | Label scanner or closer camera; format checks; human review below a confidence threshold | Hardware cost |
Exam cues: words in the stem and where they point
| Words in the question | Points to | Easily confused with |
|---|---|---|
| Extract text from scanned invoices, signs, license plates | Optical character recognition | NLP, which interprets text after it is extracted |
| Every pixel, pixel-level, exact outline, area of a lesion | Semantic segmentation | Object detection |
| Count and outline each individual, separate overlapping objects | Object (instance) segmentation | Semantic segmentation |
| Locate and classify, bounding box, where in the image | Object detection | Image classification |
| Same object across frames, assign IDs, trajectory, ID switch | Tracking | Detection alone |
| Combine camera with LiDAR, radar, IMU or GPS; robust at night or in fog | Sensor fusion | Model ensembling |
| Overlap between predicted and true box | Intersection over Union | Accuracy |
| Duplicate boxes on the same object | Non-maximum suppression | Tracking |
| Mirror image, left-right | Flipping | Rotation |
| Blur, brightness, contrast, sharpen, grayscale | Filter application | Spurious noise |
| Random pixel noise, grain, salt-and-pepper | Spurious noise | Filter application |
| Zoom, resize, objects at different distances | Scaling | Cropping |
| Random sub-region, partial view of the frame | Cropping | Scaling |
| Random blank rectangles, Cutout, random erasing | Holes | Occlusion |
| Objects partly hidden behind other objects | Occlusion | Holes |
| Hide chosen regions, the background or a channel | Masking | Holes |
Common misconceptions
- "A high validation score on daytime photos means the detector is ready for night shifts." A validation score estimates performance only on data like the validation set. If deployment conditions are missing from it, the score says nothing about them; build a validation set that matches deployment.
- "Augmenting the validation and test sets makes the evaluation tougher and more honest." It makes the evaluation measure images the deployed model will never see. Augment the training set only, and leave evaluation data as the camera produces it.
- "Semantic segmentation can count objects." Touching objects of the same class merge into one region of identical class values. Counting individuals needs instance (object) segmentation or detection.
- "Holes and occlusion are the same augmentation." Holes are blank or random-filled rectangles with no realistic content; occlusion pastes realistic objects that imitate real blocking. They teach related but different lessons.
- "Fusing a noisy sensor with a precise one drags the estimate toward the noisy one." With independent, unbiased errors and correct variances, inverse-variance weighting gives the noisy sensor little weight and still produces a smaller variance than either sensor alone.
- "Enlarging a small crop in software lets OCR read tiny text." Upscaling adds pixels, not detail. Text below the engine's minimum height needs better optics, a closer camera or a dedicated scanner.
Where this leaves us
- Computer vision tasks are named by their output: one label per image (classification), class plus score plus box per object (detection), class per pixel (semantic segmentation), mask per individual (instance or object segmentation), text with positions (OCR), and persistent IDs across frames (tracking).
- IoU is intersection divided by union, I / (area A + area B - I). Boxes [100, 100, 200, 200] and [120, 110, 220, 210] give 7,200 / 12,800 = 0.56, a true positive at a 0.5 threshold.
- Non-maximum suppression keeps the highest-scoring box and deletes same-class boxes whose IoU with it exceeds a threshold, which can also delete real people in crowds.
- Segmentation masks have the same height and width as the image, should be stored losslessly, and are scored with per-class IoU or Dice, not pixel accuracy, when classes are imbalanced.
- OCR detects text regions, then recognizes characters, and returns words and lines with locations and confidence scores. Low-confidence or malformed fields go to format checks and human review, and text below the minimum pixel height needs better optics.
- Tracking-by-detection predicts each track with a motion model such as a Kalman filter, associates detections with a cost matrix solved by the Hungarian method, then updates and manages tracks. An occlusion longer than max_age becomes an identity switch.
- Inverse-variance fusion weights each sensor by 1/σ2. With camera variance 4 and LiDAR variance 0.25, the LiDAR gets 94 percent of the weight; if dust raises the LiDAR's variance to 16, its weight falls to 20 percent.
- Augmentation applies random, label-preserving transforms (flipping, rotation, scaling, cropping, filter application, spurious noise, holes, masking, occlusion) to the training set only, after splitting. Geometric transforms must move boxes and masks with the pixels.
Sources
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Amazon Web Services. (n.d.). Semantic Segmentation Algorithm. docs.aws.amazon.com
- arXiv. (2022). CAMO-MOT: Combined Appearance-Motion Optimization for 3D Multi-Object Tracking with Camera-LiDAR Fusion. arxiv.org
- Microsoft Learn. (n.d.). OCR - Optical Character Recognition. learn.microsoft.com
- arXiv. (2023). DFR-FastMOT: Detection Failure Resistant Tracker for Fast Multi-Object Tracking Based on Sensor Fusion. arxiv.org
- TensorFlow (Google). (n.d.). Data augmentation. tensorflow.org
- Key terms
- Object detection
- A computer vision task that returns, for each object found in an image, a class label, a confidence score and a rectangular bounding box giving the object's location and size.
- Intersection over Union (IoU)
- The area where a predicted box or mask overlaps a reference one, divided by the total area the two cover together; 0 means no overlap and 1 means they are identical.
- Non-maximum suppression
- A clean-up step for object detectors that keeps the highest-scoring box and deletes other boxes of the same class whose IoU with it exceeds a set threshold.
- Semantic segmentation
- Assigning a class label to every pixel of an image, producing a mask with the same height and width as the image; touching objects of the same class merge into one region.
- Instance segmentation
- Also called object segmentation: producing a separate pixel mask for each individual object, so overlapping objects of the same class can be counted and measured one by one.
- Optical character recognition (OCR)
- Converting printed or handwritten text in images into machine-readable characters, usually returning each word and line with its position and a confidence score.
- Tracking-by-detection
- A multi-object tracking method that detects objects in every frame, predicts where existing tracks should be, and assigns detections to tracks so each object keeps a consistent ID over time.
- Sensor fusion
- Combining measurements from different sensors, such as cameras, LiDAR, radar, IMU and GPS, into one estimate that is more accurate or more robust than any single sensor provides.
- Data augmentation
- Applying random but realistic transformations, such as flips, rotations, crops, filters, noise or erased regions, to training examples to increase their variety; validation and test data stay unaltered.
- Occlusion
- One object blocking the view of another; also the augmentation that imitates it by pasting realistic occluding objects over part of a target in training images.
Other Specialized Applications of Data Science
- Explain the purpose of each of the ten applications named in objective 5.4 and match a business scenario to the one that fits it best.
- Tell apart anomaly, event and fraud detection, and heuristics from greedy algorithms, and calculate where a greedy choice or a low base rate gives a poor result.
- Describe how reinforcement learning, signal processing, edge optimization and multimodal learning work, including the ways each one usually fails.
One transaction network, ten questions
In a 2019 survey of graph-based fraud detection, Paul Irofti and two colleagues at the University of Bucharest pointed out that fraud in a network of financial transactions can appear at three scales. It can be a single suspicious edge, such as a spam message. It can be a single node, such as one account. Or it can be a larger subgraph, as when a group of clients runs a money-laundering scheme together.[1] Keep that network in mind, because almost every item in this final objective can be attached to it.
Picture a fictional payments company with a fraud team. In one week the team asks ten different questions. Which accounts are wired together into a ring? Which of 40,000 alerts should twelve investigators open first, when computing the perfect schedule would take longer than the shift? Is there a quick rule for building that schedule one step at a time? Is this payment strange for this customer? Did something change at 02:00, when declined card tests suddenly climbed? Is this payment actually fraud? Should the app allow the payment, ask for a one-time code or block it, learning from what happens afterward? Can the motion sensors and typing rhythm on a phone tell the real owner from a bot? Can the check run on the card terminal itself, in milliseconds, with no round trip to the cloud? And can one model read the transaction record, the photo of an identity document and the text of a support chat together?
Each of those questions belongs to one of the ten applications CompTIA lists for objective 5.4. The verb in the objective is 'explain the purpose'. The exam therefore mainly tests whether you can recognize which tool a situation calls for, why it works and where it breaks. You will not be asked to build a reinforcement learning agent from scratch, but you should be able to say what one needs and how it goes wrong.
Exam objectives: 5.4 Explain the purpose of other specialized applications in data science: graph analysis and graph theory, heuristics, greedy algorithms, reinforcement learning, event detection, fraud detection, anomaly detection, optimization for edge computing, signal processing and multimodal machine learning.[2]
The table below is the whole lesson at a glance. Read each row from left to right: the question the application answers, the data it usually takes in, its core mechanism and the failure you should expect. The rest of the lesson works through the rows, putting together the ones that share a mechanism.
| Application | Question it answers | Typical input | Core mechanism | Typical failure |
|---|---|---|---|---|
| Graph analysis | How are things connected, and who sits where in the network? | Nodes and edges, often with attributes | Centrality, paths, communities, link prediction | A careless edge definition links unrelated entities |
| Heuristics | What is a good-enough answer to a problem too hard to solve exactly in the time available? | An optimization problem | Rules of thumb, local search, metaheuristics | No guarantee of the best answer, and no warning when far from it |
| Greedy algorithms | What is the best next step right now? | Candidates that can be scored one at a time | Take the locally best choice and never undo it | Early commitments block a better overall combination |
| Reinforcement learning | Which sequence of actions earns the most reward over time? | States, actions and rewards from interaction | Learn a policy or value function by trial and error | Badly specified reward; unsafe or costly exploration |
| Event detection | Did something change, and when? | Time series or streams | Change-point tests, burst detection, CUSUM | Alarms come too late or too often |
| Fraud detection | Is this a deliberate deception for gain? | Transactions, accounts, devices, networks | Supervised classifiers, anomaly scores, graph features | Fraudsters adapt; labels arrive late; low base rates destroy precision |
| Anomaly detection | Does this point, context or pattern differ from normal? | Any data with a notion of normal | Statistical limits, density, isolation, reconstruction error | Unusual is not the same as bad |
| Optimization for edge computing | Can the model run fast on a small device, without the cloud? | A trained model plus the device's limits | Quantization, pruning, distillation, compact architectures | Accuracy is lost silently during compression |
| Signal processing | What is in this waveform, and what is noise? | Sampled sensor, audio or radio data | Sampling, Fourier transforms, filtering | Aliasing and leakage corrupt the features |
| Multimodal machine learning | Can one model reason over text, images, audio and tables together? | Two or more data types about the same thing | Fusion of encoders, shared embedding spaces | Missing or misaligned modalities |
The core of it: identify each application by the question it answers. Connections point to graph analysis. 'Good enough, fast' points to a heuristic, and 'best next step' to a greedy algorithm. 'Learn from reward over time' is reinforcement learning. 'Unusual' is anomaly detection, 'changed, and when' is event detection and 'deliberate deception' is fraud detection. 'Small device' is edge optimization, 'waveform' is signal processing and 'several data types at once' is multimodal learning.
Graph theory and graph analysis: when the relationships are the data
Graph theory is the mathematics of networks. A graph G = (V, E) is a set of vertices V, also called nodes, and a set of edges E, each of which joins two nodes. An edge can be directed (account A paid account B) or undirected (A and B logged in from the same device). Edges can carry weights, such as the amount paid, and both nodes and edges can carry attributes, such as account age. Graph analysis is the applied side: building a graph from data and computing on it.
Why not keep everything in a table? Most models you have met treat each row as independent of the others. Leman Akoglu, Hanghang Tong and Danai Koutra argue in their 2014 survey of graph-based anomaly detection that data objects cannot always be treated as independent points in a multi-dimensional space.[3] When objects are related, a graph can capture correlations that run across many hops, which a single row cannot hold.[3] In practice graph and table work together. Irofti's survey found that fraud networks are most often represented as attributed graphs, in which numerical features sit alongside the relational structure.[1]
There are three common ways to store a graph. An edge list is a two-column table of (source, target) pairs, which is how most graph data arrives from a database. An adjacency list maps each node to its neighbors. An adjacency matrix A has one row and one column per node, with Aij = 1 when an edge joins node i to node j and 0 otherwise. The matrix links graph analysis to the linear algebra of Lesson 4. The entry (A2)ij counts the walks of length two from i to j. The leading eigenvector of A gives eigenvector centrality, and with a damping adjustment it gives Google's PageRank. Real graphs are sparse, meaning most possible edges are absent, so libraries store A in sparse formats rather than as a full grid of numbers.
These are the measures you should recognize:
| Measure | What it computes | Typical use |
|---|---|---|
| Degree centrality | The number of edges at a node (in-degree and out-degree if the graph is directed) | Hubs: the busiest accounts, the most-linked web pages |
| Betweenness centrality | How many shortest paths between other pairs of nodes pass through this node | Brokers and bottlenecks: pass-through accounts, critical routers |
| Closeness centrality | The inverse of the average shortest-path distance to all other nodes | Who can reach everyone quickly |
| Eigenvector centrality and PageRank | Importance that comes from being linked to important nodes | Ranking pages, influencers, risky counterparties |
| Clustering coefficient | The share of a node's neighbors that are also linked to each other | Tight-knit groups and closed triangles of collusion |
| Connected components and community detection | Groups of nodes linked more densely inside than outside, found for example by maximizing modularity with the Louvain method | Fraud rings, customer segments, topic clusters |
| Shortest path | The cheapest route between two nodes, found for example with Dijkstra's algorithm when no edge weight is negative | Routing; degrees of separation from a known bad actor |
| Link prediction | How likely it is that a missing edge exists or will form | Recommendations such as 'people you may know'; hidden relationships |
A worked example shows why the choice of measure matters. Below is a fictional network of seven accounts. An edge means the two accounts shared a device in the last 30 days.
edges: A-B, A-C, B-C, C-D, D-E, E-F, E-G, F-GA, B and C form one triangle, and E, F and G form another. D sits alone between them, joined to C and to E. To get each node's degree, count its edges. To get its betweenness, count the pairs of other nodes whose single shortest path runs through it. Every path from {A, B, C} to {E, F, G} has to cross D, which gives 3 × 3 = 9 pairs. Every path from A or B to any of D, E, F or G crosses C, which gives 2 × 4 = 8 pairs. E is placed symmetrically to C, so it also scores 8.
| Account | Neighbors | Degree | Betweenness (pairs) |
|---|---|---|---|
| A | B, C | 2 | 0 |
| B | A, C | 2 | 0 |
| C | A, B, D | 3 | 8 |
| D | C, E | 2 | 9 |
| E | D, F, G | 3 | 8 |
| F | E, G | 2 | 0 |
| G | E, F | 2 | 0 |
Ranked by degree, C and E come out on top. Ranked by betweenness, D comes first, even though it has only two edges. Suppose D is a mule account that money passes through on its way between two groups. A screen based on degree would put it among the least interesting nodes. The measure has to match the behavior you are looking for: hubs show up in degree, brokers in betweenness, and rings in community detection and the clustering coefficient.
What goes wrong? Most failures happen before any algorithm runs, when someone decides what counts as an edge. Link accounts by shared IP (Internet Protocol) address, and an airport's public Wi-Fi joins thousands of strangers into one giant component. Graphs also change over time. An edge from three years ago may mean nothing today, which is why fraud teams often use time-windowed or temporal graphs. Graphs are also large, and exact betweenness is expensive on millions of nodes, so practitioners sample or approximate it. Graph features often feed an ordinary classifier, while graph neural networks learn directly from the structure. In both cases the purpose is the same: get the relationships into the model.
The core of it: graph analysis earns its place when the connections between records carry the signal. Choose the measure that matches the behavior: degree for hubs, betweenness for brokers, communities for rings, shortest paths for closeness to a known bad actor.
Heuristics and greedy algorithms: good answers fast, with no promise
Go back to the investigators: 40,000 alerts, twelve people, an eight-hour shift. Choosing which alerts to open so as to recover the most money is a version of the knapsack problem. Each item (an alert) has a weight (hours of work) and a value (expected recovery), and the goal is the most value that fits within a capacity. Matthew Roughan's operations research lectures at the University of Adelaide note that the knapsack optimisation problem is NP-hard.[4] In plain terms, no known method solves every instance quickly as the instances grow. Heuristics are built for exactly this situation.
Roughan defines a heuristic as a rule of thumb or an educated guess.[4] He then draws the distinction the exam cares about. In optimization, an algorithm is guaranteed to find the optimal solution. A heuristic makes no such guarantee; you only hope it finds a good one.[4] Data scientists use heuristics all the time, often without calling them that. Examples are the elbow rule for choosing k in k-means, trying the square root of the number of features at each random forest split, stopping training early when validation loss stops improving, and routing a delivery van to the nearest stop it has not yet visited. A metaheuristic is a general strategy that can be adapted into a heuristic for many different problems. Simulated annealing, genetic algorithms, tabu search and local search such as hill climbing are the common examples, and Lesson 25 covers optimization more broadly.
A greedy algorithm is one of the most common heuristics.[4] Roughan's recipe is as follows. At each step, list the feasible candidates, rate each one by its value in terms of the objective, take the best, and repeat until no choices remain.[4] A greedy algorithm never goes back on a choice. The same lecture names its weakness: locally good decisions can be globally bad, because the method is short-sighted.[4]
Worked example 1, where greedy gives the best answer. You need to make 63 cents in change from US coins worth 25, 10, 5 and 1 cents, using as few coins as possible. Greedy takes the largest coin that fits each time: 25 (38 cents left), 25 (13 left), 10 (3 left), then 1, 1 and 1. That is six coins, and with this set of coins no combination uses fewer.
Now change one input. Suppose the coins are worth 1, 3 and 4, and you need 6. Greedy takes 4 (2 left), then 1, then 1, which is three coins. But 3 + 3 makes 6 with only two. The greedy rule did not change; the structure of the problem did. The 4 looked best at the first step and ruled out the better pair.
Worked example 2, the knapsack. An investigator has 10 hours and three fictional cases:
| Case | Hours | Expected recovery | Recovery per hour |
|---|---|---|---|
| A | 6 | $30,000 | $5,000 |
| B | 5 | $20,000 | $4,000 |
| C | 5 | $20,000 | $4,000 |
Roughan's lectures present a greedy knapsack heuristic and credit it to George Dantzig.[4] The rule, in its standard form, sorts items by value per unit of weight and takes them in that order while they fit. Here it takes A first (6 hours, $30,000). That leaves four hours, and neither B nor C fits. The total is $30,000. Taking B and C instead uses exactly 10 hours and recovers $40,000. Greedy lost a quarter of the possible value because its first pick, though the most efficient, left an awkward amount of time that nothing else could use.
Greedy is not always a compromise, though. For some problems it is provably exact. The University of Illinois CS 473 lecture notes prove that the greedy method is correct for any matroid, a family of sets with a particular exchange property.[5] One such case is finding the minimum spanning tree of a weighted graph,[5] where the greedy method is known as Kruskal's algorithm. Huffman coding is also greedy: it builds the optimal prefix code by repeatedly merging the two least likely symbols. So is Dijkstra's shortest-path algorithm. The same notes also show where greedy stops working. If you want to schedule as many non-overlapping classes as possible, choosing by earliest finish time works. Once each class carries a different weight, the greedy rule will not always find the best schedule.[5]
You have already met greedy choices elsewhere in data science. Decision trees choose each split greedily (Lesson 15). Forward stepwise feature selection adds the single best feature each round. Greedy decoding in text generation picks the most likely next token each time. Epsilon-greedy action selection appears in reinforcement learning, below. When greedy is not good enough on its own, Roughan notes that it can still build a starting solution to improve on.[4] A common example is a route built greedily and then polished with local search.
| Approach | Guarantee | Speed | Use when |
|---|---|---|---|
| Exact algorithm (for example, integer programming solved to optimality) | Optimal, if it finishes | Running time can grow exponentially with problem size | The instance is small, or the best answer is worth the wait |
| Greedy algorithm | Optimal only for special structures (matroids, minimum spanning trees, Huffman codes) | Very fast, often one sort and one pass | Speed matters, the structure suits it, or you need a starting solution |
| Other heuristics and metaheuristics | None, though often close to optimal in practice | Adjustable: run longer to get better answers | The problem is NP-hard and an exact solver runs out of time |
The core of it: greedy is one kind of heuristic strategy, and not every heuristic is greedy. Greedy commits to the best-looking step and never looks back. On matroid-like problems that makes it exact; on knapsack-like problems it can be badly wrong.
Reinforcement learning: learning from consequences instead of labels
Go back to the payment app deciding whether to allow a payment, challenge it with a one-time code or block it. Nobody can give the app a labeled table of correct decisions, because whether a decision was right depends on what happened next. A challenge that stops a fraudster is good. A challenge that makes a genuine customer abandon a purchase costs money and goodwill. Reinforcement learning (RL) is the branch of machine learning built for this kind of problem. An agent takes an action. The environment responds with a new situation and a numerical reward. Over many rounds, the agent learns which actions pay off. Tim Miller's open textbook from the University of Queensland, Mastering Reinforcement Learning, describes its aim as giving readers enough foundation to design and implement agents that learn in this way.[6]
| Term | Meaning | In the payment example |
|---|---|---|
| Agent | The learner and decision maker | The risk engine |
| Environment | Everything the agent interacts with | Customers, fraudsters, the payment network |
| State s | What the agent observes now | Amount, device, account history, time of day |
| Action a | A choice available in that state | Allow, challenge or block |
| Reward r | Numerical feedback after an action | +1 for a completed genuine payment, -50 for a fraud loss, -2 for an abandoned checkout |
| Policy π (pi) | The rule that maps states to actions | Challenge new devices on payments over $500 |
| Action value Q(s, a) | Expected future reward from taking action a in state s and then following the policy | The long-run payoff of challenging this kind of payment |
| Discount factor γ (gamma) | A weight between 0 and 1 applied to future rewards | How much a chargeback 30 days later counts today |
The agent tries to maximize the return, which is the discounted sum of future rewards: Gt = rt+1 + γ rt+2 + γ2 rt+3 + ... With γ = 0.9, a reward of 10 that arrives three steps from now is worth 10 × 0.92 = 8.1 today. A γ close to 1 makes the agent patient. A γ close to 0 makes it care only about the next reward.
Q-learning is the textbook method for learning action values without a model of how the environment works. After each step, it nudges its estimate toward a target made of the reward just received plus the best value it expects from the next state:
Q(s, a) <- Q(s, a) + alpha * [ r + gamma * max over a' of Q(s', a') - Q(s, a) ]Here α (alpha) is the learning rate, s' is the next state, and a' ranges over the actions available in that state. The bracketed quantity is the temporal-difference error: how much better or worse things went than expected. Worked example: the current estimate for challenging a certain kind of payment is Q = 2.0. The settings are α = 0.5 and γ = 0.9. The customer completes the payment (r = 1), and the best value available from the next state is 4.0.
- Target: 1 + 0.9 × 4.0 = 4.6.
- Error: 4.6 - 2.0 = 2.6. Things went better than expected.
- Update: 2.0 + 0.5 × 2.6 = 3.3. The estimate goes up.
Now change one input: the customer abandons the checkout, and the reward is r = -5. The target becomes -5 + 3.6 = -1.4. The error is -1.4 - 2.0 = -3.4. The update gives 2.0 + 0.5 × (-3.4) = 0.3. One bad outcome removed most of the estimate's value. The learning rate controls how hard each single experience pushes.
An agent that always takes the action with the highest current estimate is greedy, in exactly the sense of the previous section. It also shares greedy's flaw: an action that got lucky early can be locked in for good while better actions are never tried. Epsilon-greedy selection is a simple but effective fix. With a small probability ε (epsilon), such as 0.1, the agent picks an action at random. Otherwise it uses its best current estimate. This tension between exploring to learn and exploiting what is already known is the central problem of RL. Its simplest form is the multi-armed bandit, which has a single state and several actions, such as five thumbnail images or three discount levels. A bandit is a practical alternative to a fixed A/B test (Lesson 10) when you want traffic to move toward the winner while the test is still running.
| Feature | Supervised learning | Unsupervised learning | Reinforcement learning |
|---|---|---|---|
| Feedback | The correct label for each example | None | A reward that grades actions, often after a delay |
| Data | A fixed labeled dataset | A fixed unlabeled dataset | Generated by the agent's own actions |
| Goal | Predict the label | Find structure | Maximize long-run reward |
| Payment example | Classify a payment as fraud or genuine | Segment customers by behavior | Choose to allow, challenge or block |
Miller's book says it covers the strengths and weaknesses of different approaches to RL.[6] The failure modes below are the ones a practitioner meets most often. A misspecified reward is optimized literally: reward clicks and the agent learns clickbait. Learning takes many interactions, so serious projects usually train in a simulator first, which opens a gap between simulated and real behavior. Exploring on live customers has real costs. Judging a new policy from logs collected under an old one (off-policy evaluation) is statistically difficult. Credit assignment, working out which action earned a reward, is hard when the reward arrives weeks later, as chargebacks do. Typical uses are control and robotics, game playing, recommendation and ad selection through bandits, dynamic pricing, inventory and resource allocation, and fine-tuning large language models from human preference ratings (reinforcement learning from human feedback, RLHF).
The core of it: RL fits when decisions come in sequence, outcomes are scored only afterward, and the agent's own actions shape the data it sees. Supervised learning fits when someone can label the right answer for each example in advance.
Anomaly, event and fraud detection: three questions that blur together
These three bullets overlap so much that exam questions are often built on the overlap. Start with what each one asks.
| Feature | Anomaly detection | Event detection | Fraud detection |
|---|---|---|---|
| Core question | Does this differ from normal? | Did the state of the system change, and when? | Is this a deliberate deception for gain? |
| Unit examined | A point, a point in context, or a group | A time window or a stream | A transaction, account, claim or ring |
| Labels | Usually none (unsupervised) | Often none; sometimes labeled past incidents | Some, from chargebacks and investigations, but late and incomplete |
| Typical methods | z-scores, interquartile range (IQR) fences, isolation forest, local outlier factor (LOF), autoencoders | CUSUM, change-point detection, burst detection, forecast residuals | Supervised gradient boosting, anomaly scores, graph features, rules |
| Main pitfall | Unusual is not harmful | Detection delay traded against false alarms | Fraudsters adapt; classes are extremely imbalanced |
Anomaly detection looks for observations that do not fit the expected pattern of normal behavior. It comes in three forms. A point anomaly is unusual on its own: a $9,000 card payment from an account that has never spent more than $200. A contextual anomaly is unusual only in its setting: heavy electricity use is normal on a January evening and strange at 3 a.m. in an empty office. A collective anomaly is a group of observations that are each normal but abnormal together: thirty $1 payments to thirty merchants in five minutes, the signature of a stolen card being tested. Akoglu and colleagues list spotting rare events, such as disease outbreaks or drug side effects in medicine, among its uses.[3] They also point to data cleaning, where anomaly detection removes erroneous values before a model is trained.[3]
| Method | Mechanism | Strength | Weakness |
|---|---|---|---|
| z-score or IQR fence | Flag points where |x - μ| / σ > 3, where μ is the mean and σ the standard deviation, or points above Q3 + 1.5 × IQR, where the interquartile range IQR = Q3 - Q1 | Simple and easy to explain | Works on one variable at a time; the z-score assumes rough normality and is itself pulled by outliers |
| Isolation forest | Random splits isolate anomalies in fewer steps, so a short average path length means a point is anomalous | Scales well and needs no distance measure | Struggles when anomalies cluster together |
| Local outlier factor (LOF) | Compares a point's local density with the density around its neighbors | Finds local anomalies in regions of varying density | Sensitive to the choice of k and to feature scaling |
| Density-based Spatial Clustering Analysis with Noise (DBSCAN) noise points (Lesson 17) | Points not reachable from any dense region are labeled as noise | Clustering and anomaly flags in one pass | The radius and minimum points are hard to set in high dimensions |
| Autoencoder or Principal Component Analysis (PCA) reconstruction | Learn to compress normal data; a high reconstruction error means abnormal | Handles high-dimensional data, images and sequences | Needs mostly clean training data |
| Forecast residuals (Lesson 5) | Compare each value with a time-series forecast | Handles trend and seasonality | Only as good as the forecast |
Fraud detection asks a narrower and more consequential question: is this a deliberate deception for gain? Irofti's survey notes that fraud detection can be framed as an anomaly detection (AD) task, because frauds are rare events that stand out from normal behavior.[1] That framing helps when labels are scarce, and it can catch new schemes that no labeled example has yet shown. In practice, though, the two are not the same, and the difference matters on the exam:
- Many anomalies are innocent. A customer's first trip abroad looks strange and is perfectly legitimate.
- Skilled fraud is designed to look normal. An account takeover that copies the victim's usual merchants and amounts is not an outlier at all. That is why production systems rely on supervised models trained on confirmed cases, plus device, velocity and network features.
- Labels arrive late and incomplete. A chargeback can appear weeks after the payment, and fraud that nobody reports is never labeled.
- The opponent adapts. When a rule starts blocking a pattern, fraudsters change the pattern. This deliberately creates the concept drift described in Lesson 13.
- Costs are lopsided. A missed fraud loses the amount stolen; a false decline loses a sale and sometimes the customer.
- Rings are relational. This is where graph analysis returns: a cluster of new accounts that share devices and pay each other is visible only as structure.
The base rate drives everything. Work through one fictional month: 1,000,000 card payments, of which 0.1 percent, or 1,000, are fraud. Model A catches 90 percent of fraud (recall 0.90) and wrongly flags 1 percent of legitimate payments (false positive rate 0.01). Model B, a better model, keeps the same recall but cuts the false positive rate to 0.1 percent.
| Quantity | Calculation | Model A (1% false positives) | Model B (0.1% false positives) |
|---|---|---|---|
| Fraud caught (true positives) | 1,000 × 0.90 | 900 | 900 |
| Legitimate payments flagged (false positives) | 999,000 × false positive rate | 9,990 | 999 |
| Total alerts | True positives + false positives | 10,890 | 1,899 |
| Precision | True positives / total alerts | 8.3% | 47.4% |
With Model A, about 92 percent of alerts are false alarms, even though its accuracy is about 99 percent. A model that flags nothing at all would score 99.9 percent accuracy and catch no fraud. That is why imbalanced problems are judged with precision, recall and the Matthews correlation coefficient (MCC), a correlation between predicted and actual labels that uses all four cells of the confusion matrix and stays informative when one class is rare. With Model B, precision rises to 47 percent. A false positive rate that looked tiny either way, cut by a factor of ten, changed the investigators' workload from 10,890 alerts to 1,899.
Event detection asks whether the state of a system has changed and when the change began. It works on time series and streams: transactions per minute, error rates, sensor readings, mentions of a word on social media. The change can be a jump in level, a change in variance or a burst of activity. Irofti's survey stresses the need to react to misconduct as fast as possible, and notes for that reason that detecting fraudulent events requires a temporal representation of the data.[1] The line between event detection and anomaly detection is partly a matter of emphasis, but it shows up in the methods. A small shift that persists may produce no single extreme point at all.
The classic tool here is the CUSUM (cumulative sum) chart. It keeps a running total of how far each observation sits above the expected mean μ (mu), minus an allowance k that absorbs ordinary noise, and never lets the total fall below zero. When the total crosses a threshold h, it raises an alarm.
S_0 = 0
S_t = max(0, S_(t-1) + x_t - mu - k)
alarm at the first t where S_t > hWorked example (fictional): declined card payments per minute normally average μ = 100, with a standard deviation of 10. Set k = 5 and h = 20, so each observation adds x - 105 to the sum.
| Minute t | Declines x | x - 105 | Running sum St |
|---|---|---|---|
| 1 | 102 | -3 | 0 |
| 2 | 98 | -7 | 0 |
| 3 | 101 | -4 | 0 |
| 4 | 115 | 10 | 10 |
| 5 | 112 | 7 | 17 |
| 6 | 118 | 13 | 30 (alarm) |
| 7 | 110 | 5 | 35 |
CUSUM raises its alarm at minute 6. Now apply a point-anomaly rule to the same data: flag any minute more than three standard deviations above normal, which means above 130. No minute comes close; the highest is 118. The point rule sees nothing because no single minute is extreme. The cumulative rule sees that the level has moved up by about 15 and stayed there. Raising k or h cuts false alarms but delays detection, and lowering them does the reverse. That trade-off between detection delay and false-alarm rate is the main tuning decision in event detection.
The core of it: anomaly detection asks 'is this unusual?', event detection asks 'did the system change, and when?', and fraud detection asks 'is this deliberate deception?'. Fraud work borrows from both, but it also needs supervised labels, graph features and a hard look at precision under a low base rate.
Signal processing: turning waveforms into features
Imagine a fictional wind turbine gearbox fitted with an accelerometer that reports vibration 25,600 times a second. A failing bearing adds a faint tone at a frequency set by its geometry, buried under the rumble of everything else. You could feed the raw samples straight into a model, but that is wasteful and fragile. Signal processing is the toolkit that turns waveforms like this into a small number of meaningful features. MIT OpenCourseWare's 2011 Digital Signal Processing course (RES.6-008) shows the usual order of ideas: its early lectures cover discrete-time signals and systems,[7] then the discrete-time Fourier transform, the z-transform and the discrete Fourier transform.
Everything starts with sampling. A sensor measures a continuous signal every T seconds, producing a sequence x[n]. The sampling rate is fs = 1/T, measured in hertz (Hz), meaning samples per second. The Nyquist-Shannon sampling theorem says a signal can be captured without loss only if fs is greater than twice the highest frequency present. Half the sampling rate, fs/2, is called the Nyquist frequency. A component above that frequency does not simply vanish. It folds back and shows up as a false lower frequency. This is aliasing.
Worked example: a bearing fault produces a 1,000 Hz tone, and a cheap logger samples at 1,500 Hz. The Nyquist frequency is 750 Hz, so the tone is above it. For a tone between fs/2 and fs, the alias appears at fs - f = 1,500 - 1,000 = 500 Hz. Your spectrum shows a confident peak at 500 Hz that matches no real part of the machine. Now change one input and sample at 2,560 Hz. The Nyquist frequency becomes 1,280 Hz, the tone falls below it, and the peak appears at its true 1,000 Hz. Once aliased samples are stored, no later processing can undo the damage. That is why hardware applies an analog low-pass anti-aliasing filter before the sampler.
The second tool is the Fourier transform. It re-expresses a signal as a sum of sinusoids and reports how much energy sits at each frequency. For N samples, the discrete Fourier transform (DFT) is X[k] = Σn=0..N-1 x[n] e-i2πkn/N. The fast Fourier transform (FFT) computes the same result in about N log N operations instead of N2. Each output bin k corresponds to the frequency k × fs/N, so the frequency resolution is fs/N. With fs = 2,560 Hz and N = 2,560 samples (one second of data), the bins are 1 Hz apart and the bearing tone lands in bin 1,000. Doubling N to two seconds of data halves the bin width to 0.5 Hz.
Two refinements matter in practice. A finite chunk of signal rarely contains a whole number of cycles, so energy spreads into neighboring bins, which is called spectral leakage. Multiplying the chunk by a tapering window, such as a Hann window, before the FFT reduces the spread. Computing FFTs on short overlapping windows gives the short-time Fourier transform (STFT). Its magnitude plotted over time is a spectrogram: an image that a Convolutional Neural Network (CNN) can classify, which is a common way to classify audio.
The third tool is filtering, which keeps some frequencies and suppresses others. A low-pass filter smooths away fast noise. A high-pass filter removes slow drift. A band-pass filter keeps the band around a fault frequency. A notch filter removes a single frequency, such as 50 or 60 Hz mains hum. The simplest low-pass filter is a moving average, y[n] = (x[n] + x[n-1] + ... + x[n-M+1]) / M. Look at the indices: this version uses only current and past samples, so it is causal. A centered moving average also uses future samples. That is fine for a plot, but in a forecasting feature it leaks future information into the training data, which makes validation scores look better than live performance will be.
From the cleaned signal you extract features for a model. Common choices are the root mean square (RMS) amplitude, the peak-to-peak range, kurtosis (which rises with sharp impacts), the energy in chosen frequency bands and the dominant frequency. The same pipeline serves predictive maintenance, speech and audio, electrocardiograms (ECG), radar, wearables, radio and seismic data.
The core of it: sample at more than twice the highest frequency present. Move to the frequency domain with an FFT when the information lies in repeating patterns. Use causal filters whenever the features feed a forecast.
Optimization for edge computing: fitting the model to the device
Edge computing means running computation on or near the device where data is produced, such as a phone, a camera, a card terminal, a car or a sensor gateway, instead of shipping the data to a central data center. Optimization for edge computing is the work of making a model small, fast and economical enough to run there. Five pressures push models toward the edge:
- Latency. A round trip to the cloud adds network delay, and a production line, a car or a payment terminal may not be able to wait.
- Bandwidth. Raw sensor streams are large, while summaries are small.
- Privacy. Camera frames, voice or health signals that never leave the device cannot leak from a central store.
- Connectivity. Ships, mines, farms and moving vehicles lose the network.
- Power and cost. Battery-powered devices have tight energy budgets, and cloud inference is billed per call.
The bandwidth argument is easy to put numbers on. The turbine accelerometer from the previous section takes 25,600 samples a second at 2 bytes each, which is 51,200 bytes a second. Over a day of 86,400 seconds that is 4,423,680,000 bytes, about 4.4 GB per sensor. If the device runs the FFT itself and sends a 20-number feature vector once a second, with each number a 4-byte float, it sends 80 bytes a second, or 6,912,000 bytes (about 6.9 MB) a day. Signal processing on the device cut the traffic by a factor of 640.
| Technique | What it does | Typical gain | Watch out for |
|---|---|---|---|
| Quantization | Stores weights, and often activations, at lower precision, for example 8-bit integers (INT8) instead of 32-bit floating point (FP32) | Weights take a quarter of the memory; integer arithmetic runs faster on hardware that supports it | Accuracy can drop. Post-training quantization is quick; quantization-aware training recovers more accuracy |
| Pruning | Removes weights, neurons or whole channels that contribute little | A smaller model; removing whole channels (structured pruning) speeds up ordinary hardware | Scattered zero weights save time only on hardware and libraries that exploit them; fine-tuning is usually needed afterward |
| Knowledge distillation | Trains a small student model to match a large teacher model's output probabilities | A compact model that keeps much of the teacher's accuracy | The student's size limits what it can learn |
| Compact architectures | Designs built for efficiency, such as depthwise separable convolutions | Fewer operations per prediction from the start | Must be chosen before training |
| Compilation for an edge runtime | Converts the model for the target chip and fuses operations together | Lower latency without changing the weights | Unsupported operations can fail to convert |
| Hardware acceleration | Runs the model on a Graphics Processing Unit (GPU), Tensor Processing Unit (TPU), neural processing unit (NPU) or similar chip | Large speedups per watt | Ties the model to one hardware family |
| Cascades and split inference | A small model on the device handles confident cases and forwards uncertain ones to the cloud | Most traffic stays local | Hard cases still need connectivity |
| Federated learning | Devices train locally and send only model updates, which a server averages | Raw data stays on the device | Updates can still leak information; mixed device types complicate training |
Worked example: a defect-detection model has 25 million parameters. At FP32 each parameter takes 4 bytes, so the weights need 25,000,000 × 4 = 100 MB. Quantized to INT8 at 1 byte each, they need 25 MB, a fourfold cut. If the target camera has 40 MB free for the model, quantization alone solves the memory problem. Now change one input: the camera has only 20 MB free. Quantization alone no longer works. You combine it with pruning or distill the model into a smaller student. Pruning half of the weights would bring the INT8 model to about 12.5 MB. Structured channel pruning removes more than a proportional share: a convolutional layer's parameter count scales with its input channels times its output channels, so halving the channels in every layer cuts each inner layer to roughly a quarter of its size. Either way the job is not finished until you rerun the held-out evaluation on the device itself. Measure accuracy and tail latency, such as the 95th percentile, not just the average, because compression errors and slow outliers often show up only there. Lesson 24 compares deployment environments, and Lesson 23 covers the MLOps (Machine Learning Operations) side: pushing model updates to thousands of devices and monitoring drift when the devices send summaries rather than raw data.
The core of it: edge optimization trades a little accuracy for large gains in latency, bandwidth, privacy and power. Quantize, prune or distill to fit the device, then prove on the device that accuracy and latency still meet the requirement.
Multimodal machine learning: one model, several kinds of data
A modality is a type of data: text, images, video, audio, tabular records, time series or graphs. Google Cloud's documentation describes a multimodal model as a machine learning model that can process information from different modalities, such as images, videos and text.[8] Its example is the Gemini model receiving a photo of a plate of cookies and writing out a recipe.[8] The purpose of multimodal learning is complementary evidence. A fictional insurance claim arrives with a photo of a dented car, an adjuster's free-text note and a table of policy details. Each modality on its own is ambiguous. Together they show whether the damage matches the story.
The main design question is where to combine the modalities, a step called fusion:
| Fusion strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Early fusion | Join raw inputs or simple features from each modality into one vector before modeling | The model can learn fine-grained interactions | Modalities differ in scale and structure; one missing input breaks the vector |
| Intermediate (joint) fusion | Encode each modality with its own network, for example a CNN for images and a transformer for text, then combine the learned embeddings in shared layers or through attention | Learns interactions while respecting each modality's structure | The most complex to train; needs paired data |
| Late fusion | Train a separate model for each modality and combine their predictions, for example by averaging or with a small meta-model | Simple, tolerates a missing modality, reuses existing models | Cannot learn interactions between modalities |
One powerful form of intermediate fusion trains separate encoders so that their outputs land in a shared embedding space. Google's multimodal embeddings documentation states that its image and text embedding vectors sit in the same semantic space and have the same number of dimensions.[9] As a result, the vectors can be used interchangeably, for example to search images by text or video by image.[9] Models of this kind are usually trained contrastively on large sets of paired images and captions: matching pairs are pulled together and mismatched pairs pushed apart. OpenAI's CLIP (Contrastive Language-Image Pre-training), published in 2021, is the best-known example.
Worked example with toy three-dimensional vectors (real embeddings have hundreds of dimensions). The text query hail damage on a roof embeds to q = (0.6, 0.8, 0.0). Three claim photos embed to p1 = (0.8, 0.6, 0.0), p2 = (0.0, 0.6, 0.8) and p3 = (0.0, 0.0, 1.0). All four vectors have length 1, so cosine similarity is simply the dot product. q·p1 = 0.48 + 0.48 = 0.96, q·p2 = 0.48 and q·p3 = 0. The search returns photo 1 first. None of the photos needed a caption, because text and images already share a coordinate system.
Multimodal systems fail in their own ways:
- Missing modalities. A model trained on photo plus text may break when a claim arrives without a photo. Late fusion, or training with modalities randomly dropped, makes it more robust.
- Misalignment. Audio must line up with the right video frames, and each caption with the right image. A one-second offset or a mismatched pair teaches the model nonsense.
- Modality imbalance. The model may lean on the easiest modality, often text, and learn to ignore the image. Check performance with each modality removed.
- Leakage through one modality. An adjuster's note that says 'confirmed fraud' carries the label straight into the inputs.
- Compute and collection cost. Each extra encoder adds compute, latency and data-collection burden, which collides directly with edge constraints.
The core of it: multimodal learning combines different data types so each can cover the others' blind spots. Choose early, intermediate or late fusion according to how much interaction you need and how often a modality will be missing. Use a shared embedding space when the task is cross-modal search.
Exam cues: telling the neighbors apart
Exam questions describe a scenario and expect you to name the application. The words in the question stem are the best guide. The last column lists the answer people most often confuse it with.
| Stem mentions | Points to | Do not confuse with |
|---|---|---|
| Connections, shared devices, network, influencers, brokers, shortest route between entities | Graph analysis | Clustering of independent rows (Lesson 17) |
| Good enough, exact solver times out, rule of thumb, NP-hard | Heuristics | Exact optimization (Lesson 25) |
| Locally best choice at each step, never revisits, builds a solution piece by piece | Greedy algorithm | Heuristics in general; greedy is one kind |
| Agent, reward, policy, trial and error, explore versus exploit, bandit | Reinforcement learning | Supervised learning with labels |
| Deviates from normal, outlier, no labels, rare pattern | Anomaly detection | Fraud detection, which implies intent |
| When did it change, spike, burst, sustained shift, stream | Event detection | A point anomaly in a single record |
| Chargebacks, account takeover, money laundering, rings, deception | Fraud detection | Anomaly detection in general |
| On-device, latency, bandwidth, low power, no connectivity, quantize | Optimization for edge computing | Cloud deployment (Lesson 24) |
| Sensor, waveform, frequency, sampling rate, FFT, noise filter | Signal processing | Time-series forecasting (Lesson 5) |
| Text and images together, cross-modal search, fusion, audio plus video | Multimodal machine learning | An ensemble of models on one data type |
Common misconceptions
- 'Greedy means wrong.' Greedy is provably optimal for matroid-structured problems such as minimum spanning trees, and for Huffman coding and Dijkstra's shortest paths with non-negative weights. It fails on other problems, such as the 0/1 knapsack and coin systems like {1, 3, 4}. What decides it is the structure of the problem, not the method.
- 'Every anomaly is fraud, and every fraud is an anomaly.' A first trip abroad is unusual and legitimate. A skilled account takeover copies normal behavior. That is why fraud systems add supervised models and graph features to anomaly scores.
- 'A fraud model with 99 percent accuracy is a good fraud model.' At a 0.1 percent fraud rate, flagging nothing scores 99.9 percent accuracy. Judge fraud models by precision, recall and cost at the real base rate.
- 'Event detection is just anomaly detection on a time series.' Event detection looks for a lasting change in state and when it began. CUSUM catches a sustained shift that no single point reveals.
- 'Reinforcement learning is supervised learning with a reward column.' A reward grades an action instead of naming the right one. It often arrives late, and the agent's own choices determine what data it sees, so exploration is essential.
- 'Sampling faster than the frequency you care about is enough.' The sampling rate must be more than twice the highest frequency present. Below that, tones alias to false frequencies, and no later processing can repair them.
Putting it together
- Graph analysis models entities as nodes and relationships as edges. Betweenness centrality finds brokers that degree centrality misses.
- A heuristic gives up the guarantee of an optimal answer in exchange for speed. A greedy algorithm, one of the most common heuristics, takes the locally best feasible choice at each step and never revisits it.
- Greedy is exact for matroid-structured problems such as minimum spanning trees (Kruskal's algorithm), and for Huffman coding. It can fail on the 0/1 knapsack problem: with 10 hours and cases of 6, 5 and 5 hours, greedy recovered $30,000 where $40,000 was possible.
- Reinforcement learning learns a policy from rewards through interaction. Q-learning moves Q(s, a) toward r + γ max Q(s', a') by a step of size α, and epsilon-greedy selection balances exploration and exploitation.
- Anomaly detection asks whether something differs from normal (point, contextual or collective anomalies). Event detection asks whether and when the system's state changed. Fraud detection asks whether there was deliberate deception, and faces late labels and fraudsters who adapt.
- Low base rates destroy precision: with 0.1 percent fraud, 90 percent recall and a 1 percent false positive rate, only about 8 percent of alerts are fraud.
- Sample at more than twice the highest frequency present. Otherwise tones alias: a 1,000 Hz tone sampled at 1,500 Hz appears at 500 Hz. FFT bins are spaced fs/N apart.
- Edge optimization uses quantization (FP32 to INT8 cuts weight storage fourfold), pruning and distillation, then rechecks accuracy and latency on the device.
- Multimodal learning combines data types through early, intermediate or late fusion. A shared embedding space makes cross-modal search, such as finding images from text, possible.
Sources
- Irofti et al. (2019). Quick survey of graph-based fraud detection methods. arXiv. arxiv.org
- CompTIA. (2023). CompTIA DataX DY0-001 certification exam: Exam objectives (Document version 8.0). lecbyo.files.cmp.optimizely.com
- Akoglu, Tong, Koutra. (2014). Graph-based anomaly detection and description: a survey. arXiv. arxiv.org
- University of Adelaide (Optimisation and Operations Research). (n.d.). Lecture 15: The Greedy Heuristic. matthewroughan.netlify.app
- University of Illinois. (2009). Greedy Algorithms (CS 473 notes). courses.engr.illinois.edu
- Tim Miller. (n.d.). Mastering Reinforcement Learning. University of Queensland. uq.pressbooks.pub
- MIT OpenCourseWare. (2011). Digital Signal Processing (RES.6-008) Study Materials. ocw.mit.edu
- Google Cloud. (n.d.). Multimodal AI. cloud.google.com
- Google Cloud. (n.d.). Get multimodal embeddings. docs.cloud.google.com
- Key terms
- Betweenness centrality
- A graph measure that counts how many shortest paths between other pairs of nodes pass through a given node. High values mark brokers and bottlenecks, even when the node has few edges.
- Heuristic
- A rule of thumb for solving a problem, especially an optimization problem, that tends to find good answers quickly but does not guarantee the best one.
- Greedy algorithm
- A method that builds a solution step by step, always taking the feasible choice that looks best right now and never undoing it. It is exact for matroid-structured problems such as minimum spanning trees, but not in general.
- Reinforcement learning
- Machine learning in which an agent learns a policy for choosing actions by interacting with an environment and receiving numerical rewards, aiming to maximize cumulative discounted reward.
- Epsilon-greedy
- An action-selection rule that picks a random action with a small probability epsilon and otherwise picks the action with the highest estimated value, balancing exploration against exploitation.
- CUSUM
- Cumulative sum chart: a change-detection method that adds up small deviations above a target mean, minus an allowance for noise, and raises an alarm when the running sum crosses a threshold.
- Aliasing
- Distortion in which a signal component above half the sampling rate appears at a false lower frequency in the sampled data. It is prevented by sampling fast enough and filtering before sampling.
- Quantization
- Storing and computing a model's weights, and often its activations, at lower numeric precision, such as 8-bit integers instead of 32-bit floats, to reduce memory use and speed up inference.
- Multimodal machine learning
- Machine learning that processes two or more types of data about the same subject, such as text, images, audio and tables, within one model.
- Shared embedding space
- A vector space into which items of different modalities, such as images and text, are mapped so that related items lie close together, making cross-modal search possible.