0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Fraud or festival gift? The hook
Here's a Brightcart customer's order history. Forty-two dollars, thirty-eight, fifty-five, about forty-seven on average, for months. And then: four hundred and twenty dollars. It might be a loyal customer buying festival gifts. Or it might be a stolen card. And it's one order among thousands every minute. There are no labels here telling us which orders are fraud, so this is unsupervised again. The machine has to learn what "normal" looks like, and flag what doesn't fit. Today we'll build anomaly detectors from simple statistics all the way to a clever forest of random trees.
And we'll see how one big outlier can hide others. Season One, Module Five, stop four: anomaly detection.
1:01What counts as an anomaly?
Anomalies come in a few forms. A point anomaly is a single value far from the rest, like our four-hundred-and-twenty-dollar order. A contextual anomaly is normal in one setting but strange in another: an ordinary order, placed at three in the morning by someone who always orders at lunchtime. And a collective anomaly is a pattern, like twenty small orders in two minutes, where no single order is strange on its own. The same ideas catch card fraud, failing machines, server problems and typos in data. And the strategy is always the same: build a picture of what normal looks like, then flag whatever is unlikely under that picture.
1:47The z-score, and the masking problem
The simplest detector is the z-score from episode four: how many standard deviations a value is from the mean. Values more than three standard deviations away are rare in normal data, so they're a common warning sign. Let's compute it for this account, using all fourteen orders. The mean is about seventy-four dollars, and the standard deviation about ninety-six. The four-hundred-and-twenty-dollar order has a z-score of three point six. Flagged, but only just. Now a new order arrives: ninety dollars, twice this customer's normal spend.
Its z-score is zero point one seven. It looks completely ordinary. Here's what's happening. The giant order dragged the mean upwards and blew up the standard deviation. Take it out and recompute: the mean drops to forty-seven, and the standard deviation shrinks to just over six. Now the ninety-dollar order has a z-score of six point eight, and the four-hundred-and-twenty-dollar order, fifty-nine. This is called masking. The anomaly corrupts the very statistics we use to detect anomalies, hiding itself, and hiding others too.
3:04Robust statistics: median, MAD and IQR
The fix is to use statistics that outliers can't push around. The median, the middle value, is forty-seven dollars fifty. Make the big order ten times bigger and the median doesn't move at all. For spread, we use the median absolute deviation, or MAD: the median distance of each order from the median. Here it's five fifty. From these we build a robust version of the z-score. The four-hundred-and-twenty-dollar order scores about forty-six, the ninety-dollar order about five, and an ordinary sixty-dollar order about one and a half.
Both suspicious orders are caught, and the normal one isn't. Another classic tool is the box plot. The middle half of the orders lie between forty-two fifty and fifty-two fifty. A common rule flags anything more than one and a half times that range beyond the box, here anything above sixty-seven fifty. Again, both the ninety and the four-twenty stand out.
4:11Distance and density: k-NN and LOF
Real anomalies usually involve several features at once. A customer might spend a normal amount and visit a normal number of times, but never that combination. So we bring back distance. One approach: score each point by how far it is from its k-th nearest neighbour. Normal customers have neighbours close by. Outliers sit alone, so their score is large. But clusters can have different densities. A point slightly outside a very tight group can be suspicious even if it's not far away in absolute terms. The Local Outlier Factor handles this by comparing each point's local density with the density around its neighbours.
A score near one means "as dense as my neighbourhood", and well above one means "much sparser than my neighbours". On Brightcart's customers, the two odd customers score two point two and three point one, while no normal customer goes above one point one three.
5:14Isolation Forest
Now one of the cleverest ideas in anomaly detection, the Isolation Forest. Instead of describing what's normal, it measures how easy each point is to isolate. Take the fourteen orders on a line and cut it at a random point. Then cut each piece again, at random, and keep going until every order sits alone. The four-hundred-and-twenty-dollar order is so far from the others that a single random cut often isolates it. A typical order, in the crowded middle, needs many cuts before it's on its own. So anomalies have short paths in these random trees.
Build a couple of hundred trees, average each point's path length, and turn it into a score where roughly a half is typical and close to one is anomalous. The four-twenty scores zero point eight four, the highest of the fourteen. A typical order scores around zero point four two. Isolation Forests need no distance calculations, scale to huge datasets, and handle many features, which is why they're a popular first choice in practice.
6:26Reconstruction error: a preview
There's another family of methods we'll meet properly later. Train a model to compress normal data and rebuild it, like the PCA reconstruction from two episodes ago. It gets good at rebuilding normal examples, and bad at rebuilding unusual ones, so the reconstruction error itself becomes the anomaly score. Neural versions, called autoencoders, are coming in Season Three.
6:54Fraud in practice: base rates and drift
In real fraud systems, these pieces fit together. Anomaly detectors flag unusual orders. Sana's team reviews the most suspicious ones. Every confirmed case becomes a label, and those labels train a supervised classifier, like the boosted trees from episode fifteen, which then works alongside the anomaly scores. Two lessons from earlier episodes matter enormously here. Fraud is rare, so accuracy is meaningless: a model that never flags anything can be ninety-nine point nine percent accurate. And since a team can only review so many orders a day, the most useful measure is often precision at k: of the top fifty orders we flag today, how many were really fraud?
And fraud is a moving target. Criminals adapt, so yesterday's patterns fade. Detectors must be monitored and retrained regularly. Notice too that "normal" differs from customer to customer. Forty-five dollars is normal for this account; for a restaurant ordering supplies, four hundred might be routine. Good systems compare each customer with their own history.
8:04Try it yourself: a $75 order
A seventy-five-dollar order arrives on the same account. Is it suspicious? Check it against the box-plot fence and the robust z-score. Pause and decide. The box-plot fence was sixty-seven fifty, so seventy-five is above it: flagged. The robust z-score is zero point six seven four five, times seventy-five minus forty-seven fifty, divided by five fifty: zero point six seven four five times five, about three point three seven, just under the common threshold of three point five: not flagged. Two reasonable rules, two different answers for a borderline case.
That's the lesson: thresholds are choices, not facts. Choose them based on how many alerts your team can review, and what a missed case costs.
8:59Context matters
An amount alone rarely tells the whole story. Seventy-five dollars is unusual for an account whose orders are usually around forty-seven dollars, and completely routine for a café that orders supplies every week. So good systems compare each customer with their own history. Time and context matter too. An ordinary forty-five-dollar order at three in the morning, from an account that always orders at lunchtime, to a brand-new delivery address, might be more suspicious than a large order at the usual time. Adding features like the hour, the device, address changes and how many orders arrived in the last hour lets multivariate detectors, like the Isolation Forest, catch combinations that no single feature would reveal.
9:49Anomalies with PCA reconstruction error
Here's a detector built from the tool in our PCA episode. Our six customers lie almost exactly along the engagement line, so rebuilding them from just the first principal component works beautifully, with a tiny average error. Now take a strange new customer who visits constantly but spends almost nothing. They sit far from the line, so the reconstruction is poor, and that large error flags them as unusual. Neural autoencoders, in Season Three, use exactly the same logic with curved, learned structure.
10:25Choosing thresholds by capacity
In practice, thresholds are often set by capacity. If Sana's team can review fifty orders a day, rank every order by its anomaly score and send the top fifty. Then track precision at fifty: of the fifty reviewed, how many were real problems? That one number tells you whether the detector is earning its keep. And as patterns shift, so does the score distribution, so check and adjust the threshold regularly.
10:56Evaluating a detector with few labels
Evaluating anomaly detectors is hard, because labels are rare and often arrive late: a stolen-card chargeback might come weeks after the order. Teams combine several approaches: expert review of a sample of flagged and unflagged orders; deliberately inserting artificial anomalies to check they're caught, remembering that real fraudsters won't behave like your test cases; and backtesting on past months once their labels have arrived. The key measures are precision among the top flagged cases, the share of known fraud caught, and how quickly it's caught.
11:35The human in the loop
Finally, anomaly detection works best as a partnership with people. Sana's team sees each flagged order with the reasons it was flagged and similar past cases, and records a decision: genuine, fraud, data error, or needs more information. Every decision becomes a label that improves the system. And the customer experience matters: hold a suspicious order and verify politely, rather than cancelling it, and release it quickly when it turns out to be genuine, like a festival gift.
12:10Myth vs Fact
Myth: anomalies are mistakes or fraud, so just delete them. Fact: an anomaly is simply unusual. It might be a data-entry error, it might be fraud, or it might be a genuine, important event, like a festival rush or the first sign of a new kind of customer. Investigate before you delete.
12:32Recap
Let's recap. Anomaly detection builds a picture of normal and flags what doesn't fit. Simple z-scores can be fooled by masking, so robust statistics like the median, the MAD and box-plot fences are safer. Distance methods and the Local Outlier Factor handle many features and varying densities. The Isolation Forest isolates anomalies with just a few random cuts. And in practice, fraud is rare and always changing, so we measure precision at k and retrain often. One sentence to remember: outliers are easy to isolate, and hard to average.
13:10Next: reinforcement learning
Mission complete. The four-hundred-and-twenty-dollar order is flagged by every method we ran on the order amounts and goes to Sana's team for review, not automatic cancellation. And robust statistics caught a new ninety-dollar order that the simple z-score would have missed. That completes Module Five, unsupervised learning: clustering, dimensionality reduction, association rules and anomaly detection. One more way of learning remains in this season, and it's completely different. No labels, no fixed dataset, just an agent acting in a world and learning from rewards.
Our delivery robot needs to find the fastest route by trial and error. Reinforcement learning, next. See you on the map.