0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Two classifiers, two ideas
Two new problems from Sana's desk. A new customer hasn't ordered in thirty days and has placed four orders recently. Will they leave? One idea is beautifully simple: find the customers most like them, and see what they did. And on the review page, posts like this one keep appearing: "Free gift! Claim your free gift now!" Can a machine learn which words give spam away? Today, two classic classifiers built on two very different ideas. One measures distance. The other uses probability and Bayes' theorem. Both are simple enough to compute by hand, and both are still used today.
Season One, Module Four, stop three: k nearest neighbours and Naive Bayes.
0:58k-NN: you are who your neighbours are
k nearest neighbours, or k-N-N, might be the most intuitive algorithm in machine learning. To classify a new example, find the k most similar examples you've already seen, and let them vote. Here are ten past Brightcart customers: days since their last order across, number of recent orders up. Red ones left, green ones stayed. Our new customer is the white star. Let's use k equals three. We measure the distance to every past customer, the Euclidean distance from episode two, and pick the three closest. The nearest is two point two four away, and they left.
Next, three point one six, and they left too. Third, four point four seven, and they stayed. Two votes to one: we predict this customer will leave. We can even read the vote as a rough probability: two out of three, about sixty-seven percent. With k equals five, two more neighbours join, one who left and one who stayed. Three votes to two, and the prediction is still "leaves".
2:12Why k-NN is a lazy learner
Notice something unusual. k-N-N has no training phase at all. It doesn't fit a line or learn weights. It simply remembers every example. That's why it's called a lazy learner. The price comes at prediction time. To classify one new customer, it must compare them against every stored customer. With millions of customers, that gets slow, so in practice we use clever indexes that find neighbours quickly. Remember that idea: it comes back in Season Five, when AI assistants search millions of documents for the ones nearest to a question.
2:52Choosing k and scaling features
How many neighbours should vote? Watch the map repaint as we change k. With k equals one, the map follows every single customer exactly. Our ten customers happen to split cleanly, but real data has noisy, mislabelled points, and k equals one builds a little island around each of them. That's overfitting. With k equals ten, all customers vote every time, and with five leavers and five stayers, every vote is a tie: it tells us nothing. That's underfitting. The sweet spot is in between, and, as always, we choose it with cross-validation.
For two classes, an odd k avoids tied votes, and a popular refinement lets closer neighbours count more. There's a hidden problem in our plot. Days since the last order range from five to fifty-two, but recent orders only range from one to nine. In raw distances, a difference of a few days swamps a difference of a few orders, so "orders" barely matters. As we learned in episode seven, distance-based models need scaled features, or the feature with the biggest numbers quietly takes over. And k-N-N isn't only for classification.
For regression, predict the average of the neighbours' values instead of taking a vote.
4:17The curse of dimensionality
k-N-N has one more weakness, and it has a dramatic name: the curse of dimensionality. Suppose our data is spread evenly, and we want a neighbourhood that contains ten percent of it. On a line, that's a segment covering a tenth of the length. In two dimensions, a square needs sides about a third of the way across. In ten dimensions, the box must stretch seventy-nine percent of the way along every axis. In a hundred dimensions, ninety-eight percent. In other words, with many features, a "local" neighbourhood isn't local any more.
The nearest neighbours are almost as far away as everyone else, and distance stops being informative. That's why k-N-N works best with a modest number of meaningful features, and why dimensionality reduction, coming in Module Five, can help.
5:12Naive Bayes: the idea
Now for spam. Naive Bayes classifies with Bayes' theorem from episode four. We want the probability that a review is spam given its words. Bayes says that's proportional to two things: how common spam is in general, the prior, and how likely these words are in a spam review. Brightcart has twenty labelled reviews: eight spam and twelve real. So the prior probability of spam is zero point four. Next, we count words. "Free" appears in six of the eight spam reviews, but only one of the twelve real ones. "Gift": five spam, one real.
"Great" and "delivery" lean the other way. They show up much more in genuine reviews. Here's the "naive" part. To get the probability of a whole combination of words, we pretend each word appears independently of the others, once we know the class. That's clearly not true. "Free" and "gift" love to appear together. But this simplification makes the maths easy, and in practice it works surprisingly well.
6:19Naive Bayes by hand: "free gift"
Let's classify the review "free gift" by hand. For the spam side, start with the prior, zero point four. Multiply by the probability of seeing "free" in a spam review, zero point seven, and then "gift" in a spam review, zero point six. That gives zero point one six eight. For the real side: prior zero point six, times the probability of "free" in a real review, about zero point one four, times "gift" in a real review, also about zero point one four. That's only about zero point zero one two. Those two scores aren't probabilities yet, so we divide each by their total.
Spam gets zero point one six eight, divided by zero point one six eight plus zero point zero one two. About ninety-three percent spam. Watch the scale: the prior leaned towards "real", but each word added strong evidence until the balance tipped decisively. You might have noticed something odd about those word probabilities. "Free" appears in six of eight spam reviews, so why zero point seven and not zero point seven five? That's a small correction called smoothing, and it solves a serious problem.
7:38Laplace smoothing and log-probabilities
Imagine a review containing the word "warranty", which has never appeared in a spam review. Without smoothing, its probability given spam would be zero out of eight: zero. And multiplying by zero wipes out the entire spam score, no matter how spammy every other word is. One unseen word would overrule everything. Laplace smoothing fixes this by adding one to every count, and adjusting the total so the probabilities still make sense. Now "warranty" gets a small probability, zero point one, instead of an impossible zero.
That's why "free" became zero point seven. There's a second, practical problem. A long review might mean multiplying hundreds of small probabilities, and the result gets so tiny that a computer rounds it to zero. The fix is to use logarithms: the log of a product is the sum of the logs, so we add log-probabilities instead of multiplying probabilities. Same answer, no vanishing numbers. And for numeric features, like order amounts, Gaussian Naive Bayes swaps word counts for a bell curve per class, the normal distribution from episode four.
8:55k-NN vs Naive Bayes: strengths and weaknesses
Both methods have clear strengths. k-N-N needs no training and can draw very flexible boundaries, but it's slow at prediction time, needs scaled features, and struggles with many dimensions. Naive Bayes is lightning-fast, works with very little data, and handles thousands of word features with ease, which is why it powered many early spam filters and is still a strong baseline for text. Its weakness is the naive assumption itself. Its predictions are often good, but its probabilities tend to be overconfident, because it counts related words as independent evidence.
9:35Try it yourself: k-NN after scaling
Earlier we warned that k-N-N needs scaled features. Let's see it happen. Standardise both features, so one standard deviation of "days" counts the same as one standard deviation of "orders". Will the new customer's nearest neighbours change? Pause and predict.
They do. The two closest are still the customers at twenty-eight days and thirty-three days, both of whom left. But the third neighbour changes, from the customer at twenty-six days with six orders, to the one at twenty-two days with five. In raw units, "orders" barely counted; after scaling, it pulls its weight. Here the vote happens to stay two to one, "leaves", but on a different dataset, scaling could flip the answer completely.
10:29Try it yourself: Naive Bayes on a genuine review
Now a review that sounds genuine: "great delivery". Let's run Naive Bayes. With smoothing, the probability of "great" in a spam review is zero point four, and "delivery" zero point two. In genuine reviews, "great" is a half, and "delivery" about zero point five seven. Spam score: the prior zero point four, times zero point four, times zero point two: zero point zero three two. Genuine score: zero point six, times a half, times zero point five seven: about zero point one seven. Normalise, and the chance of spam is about sixteen percent.
The words that appear more often in genuine reviews tipped the balance the other way. Same method, different evidence, different conclusion.
11:19k-NN beyond classification
Nearest neighbours turn up far beyond classification. "Customers like you also bought" can be as simple as finding a customer's nearest neighbours by what they've purchased, and recommending what those neighbours bought. Missing values can be filled in from the most similar customers. And, as we'll see in episode twenty, the distance to a point's neighbours makes a natural anomaly score. The choice of distance matters: Euclidean distance suits numeric features, while cosine similarity, from episode two, suits word counts and other sparse data.
11:58Naive Bayes for many classes and numbers
Naive Bayes extends easily to more than two classes. To route a support ticket to delivery, refunds or damage, give each class its own prior and its own word probabilities, compute a score for each, and pick the highest. And for numeric features, like order amounts, Gaussian Naive Bayes describes each class with its own bell curve, and uses the height of the curve at a given value as the likelihood. You can even mix word features and numeric features in one model: multiply all the likelihoods together, or, better, add their logarithms.
12:38Common mistakes
Let's collect the common mistakes. With k-N-N: forgetting to scale features; including lots of irrelevant features, which drowns the useful ones in noise; forgetting that predictions get slower as the stored data grows; and using k equals one on noisy data. With Naive Bayes: skipping smoothing, so a single unseen word wipes out a whole class; multiplying many small probabilities without logarithms; treating its probabilities as well calibrated; and building the word counts using test documents, which leaks information.
Avoid those, and both methods make excellent, fast baselines.
13:20Myth vs Fact
Myth: Naive Bayes assumes something false, so its predictions must be bad. Fact: to classify, the model only needs the right class to come out on top, not perfectly accurate probabilities. Even when its probabilities are exaggerated, the ranking is often correct. Just don't treat its probabilities as gospel. Calibrate them if you need real-world odds.
13:46Recap
Let's recap. k nearest neighbours classifies by letting the k most similar examples vote. It needs scaled features, a well-chosen k, and not too many dimensions. Naive Bayes multiplies a prior by the likelihood of each piece of evidence, assuming the pieces are independent within each class. Laplace smoothing prevents zero probabilities, and logarithms prevent vanishing numbers. One sentence to remember: neighbours vote by distance, and Bayes weighs the evidence.
14:20Next: decision trees
Mission complete. The new customer's neighbours say "likely to leave", and the "free gift" review is about ninety-three percent likely to be spam. Next, Meera wants a model she can draw on a whiteboard: a flowchart of simple yes-or-no questions that anyone can follow. That's the decision tree, and we'll grow one, split by split, using the maths of information. See you on the map.