MLDay 1 of 50Foundations
When to Use Machine Learning (and When Not To)
You write a spam filter that blocks any text containing "free" or "prize".
You write a spam filter that blocks any text containing "free" or "prize". It works for a week. Then spammers start writing "fr3e" and "pr1ze", and you're back to writing rules. Machine learning trades that chore for a different one: labelling examples.
The idea
A normal program follows rules a person wrote. Machine learning (ML) turns this around. You give the computer examples with the right answers, and it finds the rules itself.
A few words that every later day uses:
- Training data: the examples the computer learns from, such as 5,000 old text messages.
- Label: the right answer attached to an example, such as "spam" or "not spam".
- Feature: a fact about an example that the computer can measure, such as how often the word "claim" appears.
- Model: the rule the computer learns. It turns an example's features into a prediction, its guess at the label.
- Training: the computer's search for a model that predicts the training labels well.
ML is worth it when two things are true. First, the rules are hard to write or keep changing. Second, you have labelled examples, or can collect them. Spam passes both tests. When a spam trick appears, users click "report spam". That labels new examples, and the model retrains on them.
When not to use ML:
- A simple, fixed rule exists. Sales tax is a percentage of the price. A password needs 12 characters. Write the rule.
- There are no labelled examples, and no way to get them. Training data is the raw material.
- Every answer must be exactly right, or traceable to a rule. A model learns patterns, not laws, so even a good one is wrong some of the time.
Three kinds of learning:
| Kind | What the training data has | Example |
|---|---|---|
| Supervised | examples with labels | spam or not; tomorrow's bike rentals |
| Unsupervised | examples, no labels | group shoppers with similar habits |
| Reinforcement | no examples; actions and the rewards they earn | learn a game by playing it and scoring points |
This course spends most of its days on supervised learning, the kind the spam filter uses.
A tiny example
Four labelled messages are the training data:
| Message | Label |
|---|---|
| claim your free prize | spam |
| free cash, claim now | spam |
| are you free tonight | not spam |
| call me tonight | not spam |
The rule "spam if it contains free" gets three of the four right. It flags "are you free tonight" by mistake.
Now let the data set the rule. Give each word a score: the times it appears in spam minus the times it appears in non-spam.
| Word | claim | your | free | prize | cash | now | are | you | tonight | call | me |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Score | +2 | +1 | +1 | +1 | +1 | +1 | −1 | −1 | −2 | −1 | −1 |
To judge a message, add up its word scores; above 0 means spam. A word the model never saw scores 0.
- "claim your fr3e pr1ze" scores 2 + 1 + 0 + 0 = +3, so it's spam. The keyword rule misses it.
- "free tonight? call me" scores 1 − 2 − 1 − 1 = −3, so it's not spam. The keyword rule flags it.
Nobody typed "claim" as a keyword; the scores came from the labels. Real filters weigh words more carefully, but the idea is the same.
Try it
Keyword rules vs. a filter that learns
Switch keywords on to write rules: a message containing any of them is called spam. Then let a filter learn from the labelled examples instead, and see what happens when spammers change their wording.
| Message | Really | Rules say |
|---|---|---|
| Win a free prize, claim now | spam | ok ✗ |
| Free cash waiting for you, call now | spam | ok ✗ |
| You won a cash prize, reply YES | spam | ok ✗ |
| Urgent: your prize expires tonight, claim now | spam | ok ✗ |
| Are you free for lunch today? | ok | ok |
| Running late, see you at six | ok | ok |
| We won the match! Drinks later? | ok | ok |
| Call me when you get home | ok | ok |
Rules: caught 0 of 4 spam · missed 4 · false alarms 0
Switch on keywords until the rules catch all four spam messages. free and won also flag the lunch invite and the match result, so choose with care. Press Learn from examples: the learned filter gets all eight right. Now press Spammers adapt. None of the three new spam messages contains a keyword, so the rules miss them all. The learned filter still catches two, from words like claim, now and waiting. Press Learn again to add the four new messages, and it catches all three.
In code
The same contest, on 22 made-up messages. The rule filter checks four keywords. The learned filter uses
scikit-learn, Python's standard ML library: CountVectorizer turns each message into word counts (the
features), and MultinomialNB learns from them how spammy each word is.
Day 21 explains
how.
# script_id: day_001_when_to_use_ml/filters
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
def rule_filter(text): # hand-written: spam if any keyword appears
words = set(re.findall(r"\w+", text.lower()))
return int(bool(words & {"free", "win", "prize", "cash"}))
def learn_filter(examples): # learned: finds its own rules in labelled examples
texts, labels = zip(*examples)
vec = CountVectorizer().fit(texts) # features: how often each word appears
model = MultinomialNB().fit(vec.transform(texts), labels) # training
return lambda text: int(model.predict(vec.transform([text]))[0])
def score(name, filt, examples):
right = sum(filt(text) == label for text, label in examples)
print(f"{name:<38} {right}/{len(examples)} right")
The data: twelve old messages, four that users flagged after spammers changed tactics, and six fresh messages that neither filter has seen. Each label is 1 for spam and 0 for not spam.
# script_id: day_001_when_to_use_ml/filters
old = [("Win a free prize, claim now", 1), ("Free cash waiting for you, call now", 1),
("You won a cash prize, reply YES", 1), ("Claim your free gift card today", 1),
("Urgent: your prize expires tonight, claim now", 1), ("Win big: text WIN to 80080", 1),
("Are you free for lunch today?", 0), ("Running late, see you at six", 0),
("Can you send me the notes tonight?", 0), ("We won the match! Drinks later?", 0),
("Call me when you get home", 0), ("Thanks for the gift, mum loved it", 0)]
flagged = [("Ur fr3e pr1ze is waiting, txt now", 1), ("Gr8 d3al: fr3e c4sh for u", 1),
("Txt W1N for ur pr1ze", 1), ("Lunch was fr3e, lol", 0)]
fresh = [("Fr3e entry: txt W1N to 80080", 1), ("Ur c4sh pr1ze is ready", 1),
("Gr8 news, ur fr3e d3al is here", 1), ("Are you free tonight?", 0),
("See you at lunch, call me", 0), ("Got the notes, thanks", 0)]
score("rules, old messages", rule_filter, old)
score("rules, fresh messages", rule_filter, fresh)
score("learned from old, fresh messages", learn_filter(old), fresh)
score("relearned with flagged, fresh messages", learn_filter(old + flagged), fresh)
rules, old messages 11/12 right
rules, fresh messages 2/6 right
learned from old, fresh messages 4/6 right
relearned with flagged, fresh messages 6/6 right
The rules miss all three new spam messages and flag "Are you free tonight?". The filter learned from old messages still catches one new spam, from words like "to" and "80080". After four flagged examples it learns "fr3e", "pr1ze" and "ur", and gets all six right. Nobody rewrote any code; four labels did the work.
Quick check
Quick check
1. Which task is the best fit for machine learning?
2. Spammers switch from "prize" to "pr1ze". What does a learned filter need to catch up?
3. In the spam filter, which is the label?
Next
Day 2: Set Up Python, NumPy, pandas and matplotlib installs the tools that every later day uses.