15/10/2026
➡️ ML code from scratch part 16: THIS algorithm protects your inbox Our inbox is simulated. A small program of ours wrote 400 emails, half of them spam, including the tricky ones: shop newsletters you signed up for, and spam that pretends to be a colleague. No real emails were used.
How it works: First it collects every word that appears in any email. That gives 172 different words, and each one gets its own column. Every email becomes a row of numbers: how often each word shows up in it. It learns from the first 300 emails, where we know the answer. It counts how often every word appears in spam and how often in normal mail, plus one, so no word ever counts as zero. From those counts every word gets a spam score.
"click" and "now" never show up in normal mail here, so after the plus one they come out 52.6 and 57.3 times more likely in spam. "thanks" and "lunch" point the other way. "free" barely counts (1.3), because friends write things like "are you free for lunch". To judge an email, it adds up the scores of its words. Above zero means spam. This method is called naive Bayes, naive because it looks at every word on its own.
The real test: 100 new emails, written with sentences it has never seen. It sorts 83 of them right. It catches all 33 obvious spam emails and keeps all 39 personal ones.
The tricky ones go wrong: only 7 of 21 disguised spam emails are caught, and 3 of 7 shop newsletters get flagged. We ran it 20 times with newly written emails, and it always landed between 78 and 95%.
Our own email "you won a free trip claim it now" scores +7.54, straight to spam. The most suspicious word of all is "now". Every number in the video comes from the real run of the program shown.