…
…
AI Fundamentals · Lesson 3 / 31 · Rules or learning
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Elena gives you six questions from last week, each with the correct unit written next to it: aid or residence. "Build a router that separates the two," she says, "but try both ways first: write a rule, and also teach a program from these examples." The rule-based router will run for a week, and on Friday the list of questions it got stuck on will land on your desk.
At the end of this lesson you will have a router with three exits: Aid, Residence, and Hand off to Elena. The report card below shows the goal of the lesson. The first column has six questions from the Friday list. The second column shows what the rule said after a week of trials. The third column shows what the learning router we will build by the end of the lesson should do. The last column shows the correct unit.
| Question | What the rule said | Learning router (goal) | Correct unit |
|---|---|---|---|
| When does the scholarship application close? | Aid | Aid | Aid |
| Has my scholarhsip payment arrived? | Hand off to Elena | Aid | Aid |
| When does my student loan arrive? | Hand off to Elena | Aid | Aid |
| I have no scholarship question, I want to change my dorm room | Aid | Residence | Residence |
| Which classroom is my Statistics exam in? | Residence | Hand off to Elena | Courses |
| Can you take my dorm fee out of my scholarship? | Aid | Hand off to Elena | Either one |
Two things stand out in the table. The rule does not recognize some questions at all, and it confidently sends others to the wrong unit. In the goal column, "Hand off to Elena" appears twice, and that is not a failure. In this lesson we will see step by step how to fill in every row of this table.
In this lesson you will:
There are two basic ways to make a computer do a job. In the first, you make the decision and write it into the program: a rule. A rule is a line of the form "if this, do that." Its strength is clarity: everyone can read what it does, it gives the same result every time, and you can explain in one sentence why it decided that way. Its weakness comes from the same place: a rule only knows the situations its author thought of.
Looking at Elena's six questions, the first idea is this: "If the question contains *scholarship*, send it to the aid unit; if not, send it to residence." The code below applies this rule to six questions and counts how many it separates correctly. You do not need to write the code; read the lines and look at the result.
Example 1 (case): Counting how well the rule works
questions = [
("when does the scholarship application close", "Aid"),
("has the scholarship payment arrived", "Aid"),
("my grant payment is late this month", "Aid"),
("i want to change my dorm room", "Residence"),
("my room window is broken", "Residence"),
("what are the dorm meal times", "Residence"),
]
correct = 0
for question, unit in questions:
guess = "Aid" if "scholarship" in question else "Residence"
if guess == unit:
correct += 1
print(correct, "/", len(questions))Output5 / 6Five out of six is not bad. The one it missed is "my grant payment is late this month": it is an aid question, but the word *scholarship* does not appear in it. To improve the rule, you might think of changing the word it looks for. You can try exactly that below: choose the word the rule searches for and see how many questions it separates correctly.
Change the word the rule searches for: how many of the six questions does it separate correctly?
Pick a value; predict the output first, then look.
1questions = [2 ("when does the scholarship application close", "Aid"),3 ("has the scholarship payment arrived", "Aid"),4 ("my grant payment is late this month", "Aid"),5 ("i want to change my dorm room", "Residence"),6 ("my room window is broken", "Residence"),7 ("what are the dorm meal times", "Residence"),8]9keyword = "scholarship"10correct = 011for question, unit in questions:12 guess = "Aid" if keyword in question else "Residence"13 if guess == unit:14 correct += 115print(correct, "/", len(questions))
5 / 6
Faded lines didn't run with this value. A single word never catches everything. "payment" also gives 5/6, but this time it misses a different question. When you choose "dorm" the rule flips: it takes dorm questions for aid questions. Writing a rule means guessing which word will work.
During a week of trials, a second line was added to the rule: "if the question contains *room*, send it to the residence unit." If neither word appears, the question goes to Elena. The rule lowercases the question and searches for letters. The Friday list contains questions the rule got stuck on. "Has my scholarhsip payment arrived?" went to Elena: because of the typo, the letters of *scholarship* do not appear side by side. "When does my student loan arrive?" also went to Elena: it asks the same thing but does not contain the word the rule looks for. "I have no scholarship question, I want to change my dorm room" went to the aid unit, which is the wrong place.
That last question teaches the most. A student who says "I have no scholarship question" is sent to the aid unit, because the rule finds the word. The lesson: finding a word is not understanding a sentence. The rule asks "are the letters of *scholarship* here?" It does not ask "is the student asking about a scholarship?", and it cannot.
The failures on the Friday list are not random; they fall into a few types. *Typo*: a student writes "scholarhsip" in a hurry, a person fixes it at a glance, but a rule cannot. *Synonym*: "student loan" and "monthly support" go to the same unit but do not contain the word the rule searches for. *Negation and context*: the word appears, but the sentence says the opposite. *A question that fits two units*: the question really concerns both units. *Over-catching*: searching for letters sometimes catches too much. *Scholarships* and *scholarship's* are caught by luck, but a rule that searches for the letters *room* also takes *classroom* for a dorm word.
Match each question on the Friday list with its failure type.
For each row, pick its match from the list, then check.
The first fix that comes to mind is adding a new rule for each failure: a rule for "scholarhsip," a rule for "student loan," an exception for "I have no scholarship question." The problem is that as rules multiply, they start to collide. When a question fits two rules at once, the order in which the rules were written decides which one wins, not the meaning. This is exactly why the rule-based expert systems of the 1980s reached thousands of rules and became hard to maintain. In the small example below, the rules are in a dictionary; the program asks the question to each rule in order and picks the unit of the first rule that matches.
Example 2 (case): When rules collide, the first one written wins
rules = {"scholarship": "Aid", "room": "Residence", "password": "IT"}
question = "Can you take my dorm room fee out of my scholarship?"
unit = "Hand off to Elena"
for word in rules:
if word in question.lower():
unit = rules[word]
break
print(unit)OutputAidThe question contains both *scholarship* and *room*. The program looked at the "scholarship" rule first and found the word, so the question went to the aid unit. If you changed the order of the rules, it would go to the dorm instead, but neither would be a decision made by understanding the question. Now step into Elena's place: the Friday list is in front of you, and the decision is yours.
The Friday list has 14 questions the rule got stuck on: typos, synonyms, questions that fit two units. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
Now let's move to the second way. This time we do not tell the program any words. The program draws the decision from examples whose outcome is known: learning from examples. The examples the program learns from are called training data; here the training data is Elena's six labeled questions.
The method is surprisingly simple. The program takes every word of the six questions one by one and writes into a table how many times it appears in each unit's questions: "the word *payment* appears twice in aid questions and never in dorm questions." When a new question arrives, it looks up each of its words in the table, adds up the counts for each unit, and suggests the unit with the higher score. This count table is our first small model. On the rule path you wrote the decision; here the decision came from the examples. The program even found on its own that the word *payment* points to aid, which nobody told it.
The code below builds the table from six examples and scores two new questions. The second question was chosen on purpose: none of its words appear in the examples.
Example 3 (case): Counting words from examples
examples = [
("when does the scholarship application close", "Aid"),
("has the scholarship payment arrived", "Aid"),
("my grant payment is late this month", "Aid"),
("i want to change my dorm room", "Residence"),
("my room window is broken", "Residence"),
("what are the dorm meal times", "Residence"),
]
counts = {}
for question, unit in examples:
for word in question.split():
counts.setdefault(word, {"Aid": 0, "Residence": 0})
counts[word][unit] += 1
for new in ["payment still not here", "library opening hours please"]:
score = {"Aid": 0, "Residence": 0}
for word in new.split():
if word in counts:
for unit in score:
score[unit] += counts[word][unit]
print(new, "->", score)Outputpayment still not here -> {'Aid': 2, 'Residence': 0}
library opening hours please -> {'Aid': 0, 'Residence': 0}For the first question, the model bases its decision on two clues and picks aid. For the second question, it gives zero to both units. This zero does not mean "equally sure about both units"; it means "I have no clue." Any decision made here would be chance. So a model that learns is not always better than a rule: it only knows what its examples tell it. Also, because the program compares letter by letter, it counts *payment* and *payments* as two different words; we will see ways to improve this in the data unit.
Put the steps of the router that learns from examples in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now try the model yourself. The same code is ready in the cell below. Change only the sentence on the new = "..." line and press Run. Find three sentences in turn: first one the model knows well, then one that gives the two units equal scores, and last one that gives both units zero. Write the words in lowercase without punctuation; the table was built that way.
Try it now· not graded; doesn't affect progress
The question "rule or learning?" does not belong only to Elena's desk. Think of the spam filter in your inbox. The first rule that comes to mind is this: "If the message contains *free*, move it to the spam folder." This rule meets two messages: one is a real notice from a store where you shop, and the other is a fake message promising a prize.
What does the rule "if the message contains 'free', it is spam" do with these two messages? (1) "Free shipping is now on your account" (a real message) (2) "Fr3e gift, you won, click now" (spam)
Example 4 (outside the case): A filter with a rule
messages = [
"Free shipping is now on your account",
"Fr3e gift, you won, click now",
]
for message in messages:
if "free" in message.lower():
print(message, "-> spam")
else:
print(message, "-> inbox")OutputFree shipping is now on your account -> spam
Fr3e gift, you won, click now -> inboxA filter that learns counts from the messages that users marked as "spam": which words, which sender patterns, which kinds of links are common in spam messages. Nobody tells it the word "Fr3e"; it learns it on its own because it appears often in marked messages. As senders try new tricks, new marks arrive and the filter is updated with them. A rule has to be rewritten by someone sitting down to do it.
A method that learns is better than a rule at synonyms and common typos; if the archive has hundreds of examples asking about a "student loan," it learns on its own that the phrase goes to aid. But in one type of failure it struggles too: questions that fit two units. The question "Can you take my dorm fee out of my scholarship?" has no single right answer. In Elena's archive, some of these questions went to aid and some went to residence. We cannot expect a program to be perfect on a question that even people disagree about.
This is easy to see in a tiny model with two examples. The model learns from one aid question and one dorm question, and the new question carries a word from each unit.
Example 5 (case): Equal scores
examples = [
("scholarship payment late", "Aid"),
("dorm fee how much", "Residence"),
]
counts = {}
for question, unit in examples:
for word in question.split():
counts.setdefault(word, {"Aid": 0, "Residence": 0})
counts[word][unit] += 1
new = "what is the dorm payment procedure"
score = {"Aid": 0, "Residence": 0}
for word in new.split():
if word in counts:
for unit in score:
score[unit] += counts[word][unit]
print(score)Output{'Aid': 1, 'Residence': 1}An equal score tells you the model cannot decide. Real systems often turn scores into shares: each unit's score is divided by the total score, and the two shares add up to 1. A model trained on a larger archive might give a question that fits two units, for example, Aid 0.51 and Residence 0.49. What do these numbers tell you?
The learning model gave "Can you take my dorm fee out of my scholarship?" Aid 0.51 and Residence 0.49. What is the best behavior?
This is where the router's third exit comes from. The rule: if the difference between the two units' scores is smaller than a set value, the question is not sent automatically but handed to Elena. A person chooses this value; it is the same idea as the threshold you saw in lesson 1. If the difference threshold is large, Elena gets too many questions; if it is small, questions you are unsure about go to the wrong unit.
We have seen both ways; now it is time to choose. The table below summarizes the decision.
| Situation | Suitable path | Example |
|---|---|---|
| The situation is clear and there are few cases, the reason for each decision must always be explainable, and there are no examples | Rule | Sending every question that asks for a "password reset link" to the IT unit |
| People say the same thing in a hundred different ways, and there are many examples with known outcomes | Learning from examples | Sending scholarship questions to the aid unit, however they are written |
| A real system | Both + handing off to a person | A few rules for exact cases, a learning model for the rest, and Elena for questions it is unsure about |
A rule is good when the situation is clear and there are few cases, when the reason for the decision must always be explainable, or when you have no examples. Learning from examples comes out ahead when the cases are very varied and you have many examples with known outcomes. The cost of the two paths is paid in different places. On the rule path the cost is human time: someone has to think through the cases, write the rules, and update them at every exception. On the learning path the cost is labeled data: every example needs its correct answer written next to it. Elena is lucky: for years the desk has been routing every question to a unit, so the labels already exist. We will see in the data unit in detail how labeled data is collected and how much work it takes.
What do we expect to happen if we give the learning router 6,000 labeled questions instead of six?
Think about the two traps of this lesson together. The first is trying to cover every failure with a new rule: rules multiply, collide, and old correct answers break. The second is always assuming the learning model is better: on a question with no examples, the model decides by chance, and for clear and few cases an explicit rule is more reliable. A good design sits between the two and knows how to say "I don't know" where it is not sure.
Four questions come with score shares. If the difference is smaller than 0.30, the question goes to Elena; otherwise it goes to the unit with the higher score.
scores = [
("Has my scholarship payment arrived?", 0.90, 0.10),
("Can you take my dorm fee out of my scholarship?", 0.51, 0.49),
("My room heater is not working", 0.20, 0.80),
("Does a scholarship count toward dorm payments?", 0.56, 0.44),
]
diff_threshold = 0.30
for question, aid, residence in scores:
diff = round(abs(aid - residence), 2)
if diff < diff_threshold:
decision = "Hand off to Elena"
elif aid > residence:
decision = "Aid"
else:
decision = "Residence"
print(question, "->", decision)OutputHas my scholarship payment arrived? -> Aid
Can you take my dorm fee out of my scholarship? -> Hand off to Elena
My room heater is not working -> Residence
Does a scholarship count toward dorm payments? -> Hand off to ElenaIn real systems, the rule runs first for exact cases; the remaining questions go to the model. Here a question containing "password" goes straight to the IT unit, and the others are decided by the score from the count table.
counts = {
"scholarship": {"Aid": 2, "Residence": 0},
"room": {: 0, : 3},
: {: 2, : 0},
}
question [, , ]:
question:
(question, )
score = {: 0, : 0}
word question.split():
word counts:
unit score:
score[unit] += counts[word][unit]
(question, , score)Two mistakes often come together. The first is trying to cover every failure with a new rule: a rule for "scholarhsip," a rule for "student loan," an exception for "I have no scholarship question," and soon the rules collide and old correct answers break. The second is always assuming the learning model is better: on a question that never appears in the examples, the model gives {'Aid': 0, 'Residence': 0} and the decision is left to chance. The right way: a rule for exact and few cases, learning for varied wording, and Hand off to Elena when the scores are close or zero. This exit is not a failure; it is a decision that has been made.
Next lesson: A chat assistant has been set up on Elena's desk; let's look at its first answers together.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Outputi forgot my password -> IT (rule)
room change -> {'Aid': 0, 'Residence': 3}
scholarship payment -> {'Aid': 4, 'Residence': 0}