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
- Suppose you must summarize all the outages by one number \(c\), and you're charged for how far each outage is from it.
- 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.
- 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.
- 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?
- The mean
- The median
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\))?
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?
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?
- Elevators: their whole box sits to the right
- Escalators
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?
- Underfitting
- A more accurate estimate
- Overfitting: it memorizes these exact points instead of the shape behind them
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?
- The biggest values are smaller than a bell curve would give
- The biggest values are far bigger than a bell curve would allow: a long right tail
- The data is normal
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})\)?
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?
- Yes, plain hours are the right scale for estimates
- Yes: the dots line up perfectly
- No: a handful of outages that lasted days, whose estimates came close, sit so far out that they decide the whole number
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
- Same numbers, different data. Anscombe's quartet is four small datasets with the same means, standard deviations and correlation (0.82) to two decimals: one is a noisy line, one a clean curve, one a perfect line with one outlier, one a vertical stack with a single far point. Summary numbers are a compression, and compression throws things away. Plot first.
- Groups that flip the trend. A hospital can have better survival than another in every severity group and worse survival overall, simply because it takes most of the severe cases. Mixing groups of different sizes can reverse a relationship (Simpson's paradox). Here, elevator and escalator outages behave differently, so a summary over both can describe neither.
- Averages of rates. The average of each station's "share of outages fixed in 2 hours" isn't the share of all outages fixed in 2 hours: a station with 1 outage counts as much as one with 30. Decide which question you're asking before averaging.
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)?
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
- Mean vs median: on skewed data the median is the typical value; the mean is what totals need. Medians and quantiles shrug off outliers; means and standard deviations don't.
- Standard deviation is the typical distance from the mean; a z-score measures in those units, and standardizing features is how you scale them for training.
- Box plots show quartiles and outliers; histograms and KDEs show shape, with a bin width or bandwidth that can over- or underfit.
- Right-skewed data (durations, prices) often becomes well-behaved after a log. A QQ plot checks normality.
- Joint tables give marginals (sum a row) and conditionals (divide by a row).
- Correlation is covariance rescaled to [−1, 1]; a few extreme points can decide it, and it's blind to curves. Look at the scatter plot.
- The multivariate normal is described by means and a covariance matrix; its ellipses lead to PCA.
All lessons: AI from scratch.
Last updated