Sub topic 2
Rules written by hand versus patterns learned from data
This chapter assumes you can read basic Python, know what a function and a list are, and have scikit-learn installed. You don't need to know any machine learning yet. Terms such as "feature" and "label" get a precise treatment in the next chapter, so here they appear only in plain-language form.
Two ways to get a program to behave
Every program turns inputs into outputs. What differs is where the logic comes from.
- Rule-based programming: a person studies the problem, works out the logic, and writes it as explicit instructions. The program does exactly what the rules say.
- Learning from data: a person collects examples of inputs paired with the outputs they want. A learning algorithm searches for a function that reproduces those pairs and, ideally, works on inputs it has not seen.
In the first approach the programmer supplies the rules and the data is processed by them. In the second, the programmer supplies the data and the desired answers, and the algorithm produces the rules.
The learned rules are called a model. A model is a function whose behavior was set by data instead of typed in by a person.
A worked example: spam filtering
Take a concrete task: decide whether a short message is spam.
The rule-based version
A first attempt is to list suspicious words and flag any message containing one.
SPAM_WORDS = {"free", "prize", "winner"}
def is_spam_by_rules(message: str) -> bool:
words = set(message.lower().split())
return len(words & SPAM_WORDS) > 0
tests = [
"Claim your free prize today",
"Are you free for lunch tomorrow",
"Claim your cash reward",
]
for text in tests:
print(is_spam_by_rules(text), "|", text)Run this and the first message is flagged, which is correct. The second is flagged too, and that is wrong: a colleague asking about lunch is not spam. The third is not flagged, which is also wrong, because "cash reward" is a typical spam phrase that nobody put on the list.
You could fix both errors by editing the rules. Remove "free", or require "free" together with "prize". Add "cash" and "reward". Each fix is reasonable, but each also creates new exceptions, and spammers change their wording once they learn what gets blocked.
The learned version
Now give a learning algorithm labeled examples and let it work out which words matter. This code uses a bag-of-words representation, which counts how often each word appears in a message, and a Naive Bayes classifier. You don't need to understand Naive Bayes yet. Treat it as a procedure that turns example messages and their answers into a model.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
messages = [
"win a free prize now",
"free money claim your prize",
"urgent claim your free reward",
"cheap loans approved now",
"you won a free gift click now",
"limited offer free entry win cash",
"are we still meeting for lunch",
"please review the report by friday",
"meeting moved to noon tomorrow",
"can you send me the notes",
"thanks for the help with the report",
"lunch tomorrow at noon",
]
labels = ["spam"] * 6 + ["ham"] * 6 # "ham" means not spam
model = make_pipeline(CountVectorizer(), MultinomialNB())
model.fit(messages, labels)
new_messages = [
"Claim your free prize today",
"Are you free for lunch tomorrow",
"Claim your cash reward",
]
for text, prediction in zip(new_messages, model.predict(new_messages)):
print(prediction, "|", text)No one wrote a rule that mentions "cash" or "reward". The model saw those words only in spam examples, so it associates them with spam. In the same way, "lunch" and "tomorrow" appear only in ordinary messages, which pushes the lunch invitation toward "ham". On this data you should see the first and third messages predicted as spam and the second as ham.
The dataset has twelve messages, so the result is sensitive to small changes in the data. Treat the output as an illustration of the mechanism, not as evidence that the model is good. How to measure that properly is the subject of a later chapter on evaluation.
What actually changed
The learned version did not remove the need for human judgment. It moved that judgment.
| Question | Rule-based | Learned from data |
|---|---|---|
| Who writes the decision logic? | A programmer | A learning algorithm |
| What does the programmer supply? | Rules | Examples with correct answers, plus a choice of algorithm |
| How do you fix a mistake? | Edit or add a rule | Add or correct examples and retrain |
| Can you read the logic? | Yes, line by line | Sometimes; often only indirectly |
| What happens when the world changes? | Someone rewrites rules | Retrain on newer data |
| Typical failure | A case nobody anticipated | Data that is biased, too small, or unlike real inputs |
The programmer now decides which examples to collect, how to describe each message numerically, which algorithm to use, and how to judge the result. Those choices carry as much responsibility as writing rules did.
When rules are the better choice
Learning from data is not a replacement for ordinary programming. Rules are usually the better choice in these cases:
- The logic is known and exact. Computing sales tax, validating a date, or sorting a list has a correct specification. A learned approximation can only be worse.
- Errors are unacceptable and must be explainable. A rule engine for legal compliance can be audited. A statistical model gives you a probability of being right.
- You have no data. A learning algorithm cannot learn from examples that don't exist.
- The rules are few and stable. If ten lines of code solve the problem, a training pipeline adds cost with no gain.
Learning from data is the better choice when:
- The logic is hard to state. You can recognize a handwritten "7" instantly but cannot write down the rule your brain uses.
- The rules would be too many or change too quickly. Spam, fraud patterns, and product recommendations shift constantly.
- Examples are plentiful and the right answers are known. Years of labeled emails, transactions, or images make a good training source.
- An approximate answer is acceptable. Many useful systems are right 95% of the time and wrong 5%, and that is fine for the task.
Edge cases and common errors
Data that teaches the wrong lesson
A model learns whatever pattern in the data separates the answers, even if that pattern is irrelevant. Suppose all your spam examples were written in capital letters and all your ordinary messages were not. The model may learn "capital letters means spam" and fail on lowercase spam. Rules fail in obvious ways, because you can read them. A learned shortcut like this is hidden unless you test for it.
Training data that does not match real inputs
If you train on messages from 2015 and deploy in a later year, new wording will appear that the model has never seen. This mismatch between training data and real-world inputs is called distribution shift. Rule-based systems suffer from the same drift, but a model can degrade without any visible error message.
Treating a good fit on examples as success
The twelve-message model above would likely score perfectly on its own training messages. That says almost nothing about new messages. A model can memorize its examples instead of capturing a pattern, which is called overfitting. Later chapters cover it and the held-out test set that detects it.
Assuming that "learned" means "objective"
A model reproduces the patterns in its data, including human biases and labeling mistakes. If past reviewers labeled certain senders as spam unfairly, the model inherits that decision and applies it consistently and at scale.
Using learning where a lookup would do
If the same input must always yield the same exact output, such as a currency code for a country, store a table. Training a model for it adds unpredictability for no benefit.
A working definition
You can now state the idea precisely. A program learns from data if its behavior on a task is shaped by example data, so that its performance on that task improves as it sees more or better examples. This is the practical form of a well-known definition by Tom Mitchell: a program learns from experience E with respect to a task T and performance measure P if its performance at T, measured by P, improves with E.
Map the spam filter onto it:
- Task T: label a message as spam or not spam.
- Experience E: the labeled messages used for training.
- Performance P: the fraction of new messages labeled correctly.
If you can name all three for a problem, you have framed it as machine learning. If you can't name E, you probably have no data to learn from, and rules may be your only option.
Exercise
A team must build a function that converts temperatures from Celsius to Fahrenheit. A second team must flag credit card transactions that look fraudulent, using five years of transactions already marked "fraud" or "legitimate". For each team, decide whether hand-written rules or learning from data fits better, and give one reason. Then, for the fraud task, name the task T, the experience E, and the performance measure P.
Show answer
The first team should write a rule: F = C * 9 / 5 + 32 is an exact, known formula, so a learned approximation could only be less accurate. The second team should learn from data: fraud patterns are numerous, change as criminals adapt, and are hard to write down, and five years of labeled transactions give plenty of examples. For the fraud task, T is labeling a transaction as fraud or legitimate, E is the five years of labeled transactions, and P is the fraction of new transactions labeled correctly, or a measure that reflects how well fraud is caught while avoiding false alarms.
Exercise
In the spam example, the rule-based filter flagged "Are you free for lunch tomorrow" as spam. Describe one change to the rules that fixes this case, and one new problem that the change could introduce.
Show answer
One fix is to flag a message only if it contains "free" together with another suspicious word such as "prize", or to remove "free" from the list. Either change would let spam that relies on "free" alone, such as "Free entry, reply now", pass through. This shows why hand-edited rules tend to trade one error for another.