…
…
Turn 40 fictional messages from a club's contact box into word counts, build a count table from the training messages and score new ones; change the threshold and count false alarms and misses, compare with the nearest neighbor, and build a two-threshold filter that leaves unsure messages to a human.
The contact box of the campus robotics club gets dozens of messages every day. Some are club business: a meeting time, a workshop sign-up, a project presentation. Others are unwanted: "Congratulations, you won a prize, click now!" Lena, the club member who checks the box, is tired of sorting them out. She asks you to build a simple spam filter with what you learned in lessons 6 and 7.
Lena gave you 40 messages she labeled by hand (messages.csv, fictional sample data). The first 24 messages are the train group the filter will learn from; the last 16 are the test group the filter will predict without ever seeing them. The filter will not read the text; it will only count the words in a dictionary. At the end of the project your filter will print this summary:
OutputSPAM FILTER: test result
spam folder | spam: 4 | normal: 0
inbox | spam: 0 | normal: 6
to Lena | spam: 4 | normal: 2
False alarm: 0
Miss: 0Along the way you will meet two errors by name. A false alarm puts a club message in the spam folder; a miss leaves a spam message in the inbox. A threshold reduces one while it increases the other; the way to bring both to zero is to leave the unsure message to Lena.
| Step | What you will do |
|---|---|
| 1 | Read the messages and count them by group and label |
| 2–3 | Clean the text and turn it into a vector with the dictionary |
| 4–5 | Build a count table from the training messages and score new messages |
| 6–7 | Decide with a threshold, count false alarms and misses, run a threshold experiment |
| 8 | Try the same messages with the nearest neighbor and compare the two methods |
| 9 | Build the two-threshold filter that leaves unsure messages to Lena |
Lessons used: rule or example, and comparing a score with a threshold (3); turning text into numbers: cleaning, dictionary, counting by looking at the start of a word, the count table (6); nearest neighbor, distance and "the model always answers" (7); choosing a setting with an experiment table (8).
How to work: The nine cells share one session: the clean you write in step 2, the vector in step 3 and the diff in step 5 are used in later cells. The lines that read the file and print the results are ready; the comments tell you what to do, and you write the code where it says ___. Run the cell, compare your output with "Show expected output", then press Check. Do not type the results by hand; the checks also try your functions with other messages and other thresholds. The messages, the club and the people are fictional; messages in a real contact box may contain personal information and must not be shared without permission.
What you'll do
Required topics
messages.csvDownload file
Reading file…
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
Lena has 40 messages picked from the club's contact box: messages.csv. Each row holds three pieces of information: group, label and text. Lena set the labels by hand: an unwanted message is spam, a message about club business is normal.
The group column matters. The first 24 messages are in the train group: the filter will learn its words from them. The last 16 messages are in the test group: the filter will predict them without ever seeing them, and we will compare its predictions with Lena's labels. It is like Elena setting aside 12 questions in lesson 8.
The lines that read the file are ready; each message goes into the messages list as a tuple in the form (group, label, text). Your job is to count how many messages there are for each (group, label) pair. That shows whether spam and normal messages are balanced in both groups. The counting method is the same as the vote count in lesson 8: counts[key] = counts.get(key, 0) + 1.
This step's code cell is for members.Sign up free
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
The filter cannot read; first we have to turn every message into a word list by the same rule. The three steps from lesson 6 apply here too: clean, split, count. In this step you will write the clean(text) function, which does the first two.
Spam messages are often written in capital letters: "CONGRATULATIONS", "URGENT". That is why lowercasing matters here. Without lower(), "URGENT" would never match the dictionary word "urgent", and the filter would miss the most obvious spam. Lowercase first, then remove the punctuation marks (. , ! ? :) and split on spaces.
The function must return the word list; printing is not the function's job, it belongs to the print lines below.
This step's code cell is for members.Sign up free
Lena picked a ten-word dictionary for the filter. The first seven are words she often sees in spam messages (prize, win, free, click, discount, urgent, password); the last three are common in club messages (meeting, workshop, project). As you saw in lesson 6, a good dictionary word is one that separates the two classes.
vector(words) must count, for every dictionary word, how many words in the list start with that word, and return the counts in dictionary order. Looking at the start of a word roughly ignores endings: "winner", "wins" and "winning" all fall into the win column, and "clicking" falls into click. Irregular forms slip through: "won" does not start with win. The vector length is always the dictionary length, which is 10.
The message in the last line contains no dictionary word. The zero vector you will see in the output means the filter knows nothing about that message; we will use this in the last step.
This step's code cell is for members.Sign up free
Now it is time to teach the filter. As we did with the cafeteria filter in lesson 6, we will count how many times each dictionary word appears in spam messages and in normal messages among the 24 messages of the training group. This table will be all the filter knows; it will know nothing else.
The table dictionary is ready: {"spam": 0, "normal": 0} for every dictionary word. The loop walks through all messages; you will count only in the train group. If you count the test messages, the filter would have seen the exam questions in advance, and the results we measure in later steps would come out better than they really are.
After cleaning a message, for each of its words, add one to table[k][label] for every dictionary word k that the word starts with. Look at the output: which words appear in only one class?
This step's code cell is for members.Sign up free
The table is ready; now we can score a new message. The rule is the same as the filter in lesson 6: for every word of the message, add the table's spam count to the spam score and the normal count to the normal score, for every dictionary word that the word starts with. At the end the function returns the spam score minus the normal score difference.
If the difference is large and positive, the message looks like spam messages; if negative, like club messages. If it is zero, there is no lean either way: either there are no dictionary words, or the two sides canceled each other out.
In the output you will see the difference, Lena's label and the text of the 16 test messages. Read the lines one by one and mark the odd ones: is there a normal message with a high score? Is there a spam with a score of zero? Also look at the message "No free pizza, bring your own food to the workshop.": the negation problem you saw in lesson 6 shows up here too.
This step's code cell is for members.Sign up free
A score alone is not a decision; you need a threshold. The rule is: if the difference is greater than or equal to the threshold, the message goes to the spam folder; otherwise it stays in the inbox. In lesson 3, when we talked about learning from examples versus rules, we also compared a score with a limit.
The filter can be wrong in two different ways, and the two do not cost the same:
In this step you will classify the test messages with threshold = 1 and keep three numbers: correct, false alarms, misses. The total is ready. Can you find which message is the false alarm and which is the miss from the output of the previous step?
This step's code cell is for members.Sign up free
The threshold is a knob you turn; we will run the same experiment for the threshold that we ran for k and scale in lesson 8. Try the threshold from 0 to 7, one by one, and write the false alarm and miss counts for each threshold into the table.
The loop variable is named threshold; the classify you wrote in the previous step uses this name, so it works with the new threshold on every turn. Your job is to walk through the test messages on every turn and compute the two error counts (fa and mi).
When you read the table, look for this: as the threshold grows, the filter becomes more careful and asks for more evidence before calling something spam. False alarms go down, misses go up. Is there a threshold that brings both errors to zero? If not, you have to decide which one is more expensive. For a club, losing an important message in the spam folder is usually more expensive than deleting a spam by hand.
This step's code cell is for members.Sign up free
Besides scoring, let's also try the method from lesson 7: nearest neighbor. This time there is no table; the vector and label of every training message are stored (the train list is ready). You compare the vector of a new message with every training vector; the distance is the sum of the absolute values of the differences between numbers in the same position. The label of the message with the smallest distance is the prediction.
Write the neighbor_guess(v) function: it should return (label, distance). As in lesson 7, remember the smallest distance and update only when you find a smaller one (<); that way, on a tie, the example that comes first in the list is chosen.
Look at two things in the output. The first is the messages with empty vectors: the model still names a label, because a smallest distance always exists. "The model always answers" was the most important warning of lesson 7. A distance of 0 should not fool you either: there is a message in training with no dictionary word at all (the robot arm motor), and the distance between two empty vectors is 0. This does not show that the two messages are alike; it shows that nothing is known about either of them. The second is the two numbers at the bottom: is the neighbor method better or worse than scoring? How solid is it to trust a single neighbor in a small archive of 24 messages?
This step's code cell is for members.Sign up free
The experiment table showed the limit of a single threshold: the threshold that brings false alarms to zero (6) misses four spam messages; the thresholds that reduce misses send one club message to the spam folder. In lessons 3 and 7 we saw the way out: leave the unsure message to a human.
The filter will now make three decisions:
1. If the vector is empty: "to Lena". The filter saw no word it knows in the message; even if the score comes out 0, that is not information, it is ignorance.
2. If the difference is high_threshold or above: "spam folder". We chose 6 because, according to the table, there is no false alarm at this threshold.
3. If the difference is low_threshold or below: "inbox". Every message in between: "to Lena".
Write the decide(text) function in this order. The ready code below counts the test messages by their decisions and prints a summary. Look at the result: see the trade-off between the number of errors and the number of messages Lena will look at by hand. The filter does not finish the job completely, but it puts only the undecided messages in front of Lena.
Remember: these numbers come from a small test group of 16 messages. As new kinds of spam appear in the club's real box, the dictionary and thresholds need to be tried again.
This step's code cell is for members.Sign up free