AI from scratch · Probability 2 · Stage 1: the math of learning

Describing data

Before any model, an ML engineer looks at the data: what's typical, how spread out it is, what shape it has, what goes with what. This lesson does that on real data from this site: every NYC subway elevator and escalator outage our archive saw finish between 9 and 12 October 2026, 340 of them. It's messy, lopsided real-world data, which is the point: half the summaries people reach for first give the wrong picture of it.

1. What's typical: mean, median, mode

Each dot is one outage, placed by how many hours it lasted (shaken up and down a little so they don't hide each other). The yellow line is the mean, the plain average. The blue line is the median, the middle value: half the outages were shorter, half longer.

On the plain scale almost everything is squashed against the left edge by a few outages that lasted weeks. The mean, 8.2 hours, sits where hardly any outage is. The median, 1.6 hours, is what a rider actually meets. Press Add one: a single extreme value drags the mean up by hours while the median barely moves. The median is robust: outliers can't push it around.

\[ \bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i \qquad \text{median} = \text{the middle value after sorting} \]

The mode is the most common value. It's most useful for categories: here the most common reason is "Under Investigation".

The median is what a typical case looks like; the mean is what totals need. On lopsided data they disagree, and each answers a different question.

Why the mean and the median? Each is the best single guess for a different penalty
  1. Suppose you must summarize all the outages by one number \(c\), and you're charged for how far each outage is from it.
  2. Charged the squared distance, \(\sum_i (x_i - c)^2\): its slope in \(c\) is \(-2\sum_i (x_i - c)\) (calculus 1), zero when \(\sum_i x_i = n\,c\). The best \(c\) is the mean.
  3. Charged the plain distance, \(\sum_i |x_i - c|\): nudge \(c\) right by a little and every point on its left gets that much further, every point on its right that much closer. It stops paying to move when as many points are on each side: the best \(c\) is the median.
  4. So squaring is why the mean chases outliers: a point 1,000 hours away costs a million, and the mean moves a long way to cut that. The plain distance charges it only 1,000.

This is the same choice a model makes. Trained with squared error, a model predicts the average outcome for each input; trained with absolute error, the median. Same data, different answers, and neither is wrong.

A dashboard should show "how long an outage typically lasts". Which number?

With lopsided data like waiting times, prices or incomes, the median describes the typical case. The mean still matters when totals matter: total hours of lost access is \(n \times\) mean, so a planner budgeting repair crews wants the mean.

2. How spread out: variance and standard deviation

Two datasets can share a mean and still look nothing alike. The variance is the average squared distance from the mean, and the standard deviation \(\sigma\) is its square root, which brings it back to the data's units:

\[ \sigma^2 = \frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2, \qquad \sigma = \sqrt{\sigma^2} \]

(When you estimate the spread of a whole population from a sample, you divide by \(n - 1\) instead; Probability 3 explains why. With hundreds of points the difference is tiny.) Squaring makes big deviations count a lot, so like the mean, the standard deviation is easily blown up by outliers: for our outages it's 56 hours, wider than nearly every outage.

The numbers 2, 4, 4, 4, 5, 5, 7, 9 have mean 5. What's their standard deviation (dividing by \(n\))?

Distances from 5: −3, −1, −1, −1, 0, 0, 2, 4. Squared: 9, 1, 1, 1, 0, 0, 4, 16, which add up to 32. Divided by 8: variance 4. Square root: \(\sigma = 2\).

Standardizing turns any value into "how many standard deviations from the mean": the z-score \(z = (x - \bar{x}) / \sigma\). After it, every feature has mean 0 and spread 1. That's exactly the feature scaling models need: Calculus 3 will show gradient descent zigzagging in a stretched valley, and putting all features on the same scale is what un-stretches it.

The standard deviation is the typical distance from the mean, and a z-score measures any value in those units, which puts every feature on one scale.

Test scores have mean 70 and standard deviation 10. What's the z-score of a score of 85?

\((85 - 70)/10 = 1.5\): one and a half standard deviations above average.

3. Quantiles and box plots

The median splits the data in half. Quantiles split it anywhere: the 25th percentile (first quartile, Q1) has a quarter of the data below it, the 75th (Q3) three quarters. The interquartile range IQR = Q3 − Q1 is the spread of the middle half, and like the median, outliers can't touch it.

A box plot draws exactly that: the box runs from Q1 to Q3 with a line at the median, the whiskers reach the furthest points within 1.5 IQR of the box, and anything beyond is drawn on its own as a possible outlier. The faint shape behind each box is a violin: the same data's density (section 4), mirrored. Here are elevators and escalators side by side, on a log scale:

Which kind of outage typically lasts longer?

Elevator outages have a median of about 2.5 hours against about 1.2 for escalators, and their middle half reaches further too. That matters more than it sounds: an elevator outage is the one that cuts off a wheelchair user, so the MTA reports them separately.

4. The shape: histograms and density estimates

A histogram cuts the range into bins and counts the points in each. Its look depends a lot on the bin width you pick. A kernel density estimate (KDE) instead puts a small bell curve on every point and adds them up, giving a smooth estimate of the density (Calculus 4). Its knob is the bandwidth, the width of each little bell. The x-axis here is \(\log_{10}\) of hours: 0 is 1 hour, 1 is 10 hours, 2 is 100.

Slide the bandwidth all the way down. The curve turns into a comb of spikes, one per point. What's that like?

Too small a bandwidth (or too many bins) copies the noise; too big hides real bumps. Picking it is the same trade-off as model complexity in chapter 11. Rules of thumb exist (Silverman's: about \(1.06\,\sigma\,n^{-1/5}\), here about 0.16), and so does cross-validation.

On the log scale the shape is a single hump, leaning a little right. On the plain scale it's wildly skewed: a big pile near zero and a long tail to the right. Skewness measures that lopsidedness (0 for symmetric, positive for a long right tail), and kurtosis measures how heavy the tails are compared with a bell curve. Durations, prices, incomes and file sizes are all right-skewed, and taking logs is the standard fix: models (and averages) behave much better on \(\log x\) than on \(x\).

5. Is it a bell curve? The QQ plot

Many methods assume data is roughly normal (a bell curve). To check, sort the data, standardize it, and plot each point against where it would be if the data were perfectly normal: the matching quantile of the bell curve. Normal data falls on the diagonal; skew bends it away.

Untick "take logs first". The points curve sharply up at the right end. What does that mean?

On the plain scale the longest outages are 10+ standard deviations out, where a bell curve has essentially nothing. With logs, skewness drops from about 12 to 1.3 and the middle of the data sits right on the line: the durations are roughly log-normal, meaning their logs are close to normal. The top end still bends up, though: the longest outages (planned work lasting days or weeks) are a different kind of event from everyday breakdowns, and real data often mixes groups like that.

6. Two variables: joint, marginal, conditional

With two variables at once, count every combination. This is the joint table of kind × "fixed within 2 hours?". The totals in the margins are the marginal counts: each variable on its own, ignoring the other.

A conditional distribution picks one row and divides by its total: "of the elevator outages, what share ran over 2 hours?". That's Probability 1's \(P(A \mid B)\), counted from real data.

From the table: what is \(P(\text{over 2 h} \mid \text{elevator})\)?

92 of the 158 elevator outages ran over 2 hours: \(92/158 \approx 0.582\). For escalators it's \(50/182 \approx 0.275\). Very different, so kind and duration are not independent: knowing the kind changes the odds.

7. Covariance and correlation

For each outage the MTA posts an estimated return time. Does the estimate predict how long it actually takes? Each dot is one outage: across is the estimate, up is the truth.

Covariance measures whether two variables move together: the average of (x's distance from its mean) times (y's distance from its mean). When both are above or both below their means, the product is positive. Correlation \(r\) divides by both standard deviations, which pins it between −1 (a perfect falling line) and +1 (a perfect rising line), with 0 meaning no straight-line relation:

\[ \operatorname{cov}(x, y) = \frac{1}{n} \sum_i (x_i - \bar{x})(y_i - \bar{y}), \qquad r = \frac{\operatorname{cov}(x, y)}{\sigma_x \sigma_y} \]

A correlation is also just the mean product of z-scores: standardize both, multiply pairwise, average.

Untick "log scale". The correlation jumps from about 0.65 to 0.99. Did the estimates get better?

Covariance multiplies distances from the mean, so the 10 outages that lasted over a day (3% of the data, mostly planned repairs with decent estimates) dominate everything. Among the 326 outages under 12 hours, the plain-scale \(r\) is only 0.2. Always look at the scatter plot before trusting a correlation. The log scale's 0.65 is the honest answer: the estimate helps, but often misses by a factor of several.

Correlation is the average product of z-scores: how consistently two things sit on the same side of their means, along a straight line.

Two more warnings. Correlation only sees straight-line relations: points on a perfect circle have \(r = 0\). And correlation isn't causation: elevator outages correlate with longer estimates and longer durations, but the estimate doesn't cause the repair to take longer; the kind of breakdown drives both.

Where it breaks: summaries that hide the story

8. The two-dimensional bell curve

The bell curve has a version for several variables at once, the multivariate normal. In 2D it's a hill whose contour lines are ellipses. It's described by the two means and a covariance matrix: each variable's variance on the diagonal, their covariance off it, written with the correlation \(\rho\) (rho, the \(r\) of section 7) as \(\rho\,\sigma_x\sigma_y\). The matrix is traditionally called \(\Sigma\): the same capital sigma as the sum sign, used here as a name, not as "add these up". Which one is meant is always clear from what sits around it.

\[ \Sigma = \begin{pmatrix} \sigma_x^2 & \rho\,\sigma_x \sigma_y \\ \rho\,\sigma_x \sigma_y & \sigma_y^2 \end{pmatrix} \]

Shape it: the dots are 600 samples, the rings are 1 and 2 standard deviations.

With \(\sigma_x = 2\), \(\sigma_y = 3\) and \(\rho = 0.5\), what's the covariance (the off-diagonal number)?

\(\rho\,\sigma_x\sigma_y = 0.5 \times 2 \times 3 = 3\).

The ellipse's long axis is the direction the data varies most, and finding those axes is exactly what PCA does, using the covariance matrix's eigenvectors (Linear algebra 2). The same shape shows up as the Gaussian anomaly detector in stage 3: points outside the outer ring are rare.

9. All of it in code

10. What to carry forward

All lessons: AI from scratch.

Last updated