…
…
AI Fundamentals · Lesson 6 / 31 · Data, features, labels
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.
A computer cannot read the word "scholarship"; it works only with numbers. To give Elena's 600 questions to a model, we first need to turn every question into a list of numbers. In this lesson we will build, ourselves, the source of columns like aid_k and residence_k that you saw in features.csv in the last lesson.
A model can compare two questions only through numbers. You see at a glance that "Did my scholarship payment arrive?" and "When does my scholarship get paid?" are similar; the model compares numbers, not letters. That is why the first step of every AI system that works with text is to turn the text into numbers. By the end of the lesson you will be able to put every question you have into this form:
OutputQuestion: Dorm room's heater won't work, dorm office isn't replying.
Vocabulary: ['scholarship', 'dorm', 'room', 'heater', 'exam']
Vector: [0, 2, 1, 1, 0]The first line is the question the student wrote. The second line is five words we chose in advance. The third line is the only thing the model really sees: five numbers. We will build what each of these numbers means step by step in this lesson.
In this lesson you will:
The job is done in three steps: clean, split, count. Let's look at the first two first. Why do we need to clean? Because for a computer, "Scholarship", "scholarship", and "scholarship?" are three different strings of letters. If the same word is counted separately because it starts with a capital letter or because it has a question mark at the end, two students who ask the same thing look nothing alike to the model.
Cleaning means turning the text into lowercase and dropping the punctuation marks. Splitting into words means cutting the clean text at the spaces to get a list of words. The two-line code below does exactly this; you do not need to write the code, just look at the result.
Example 1 (case): Cleaning and splitting into words
question = "SCHOLARSHIP payment arrived yet?" clean = question.lower().replace("?", "") print(clean.split())
Output['scholarship', 'payment', 'arrived', 'yet']"SCHOLARSHIP" is now "scholarship", and the question mark is gone. The list has four words, in the same order as in the question. At this point we have not counted anything yet; we have only made the text ready to be counted.
Put the steps of turning a question into a vector in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The third step is counting. We keep a list made of words we chose in advance; we call this the vocabulary. For each word in the vocabulary, we look at how many times it appears in the question and write the counts in the vocabulary's order. In the end, every question turns into a list of numbers as long as the vocabulary. This list is called a vector. The method is called a bag of words, because the words of a sentence are counted as if they were thrown into a bag; which came first is forgotten.
Follow the code below step by step. You do not have to try to read the lines; look at the boxes on the right. Does the count box start from zero each time we move to a new vocabulary word? How many times does the vector box grow, and which number does it get in which round?
Run the code line by line: see which line runs next, the variable boxes and the output.
question = "Did my scholarship payments arrive? Scholarship!" clean = question.lower().replace("?", "").replace("!", "") words = clean.split() vocab = ["scholarship", "dorm", "payment"] vector = [] for k in vocab: count = 0 for word in words: if word.startswith(k): count += 1 vector.append(count) print(vector)
The result is [2, 0, 1]. The vector box grew exactly three times, because there are three words in the vocabulary: however many words the question has, the length of the vector is the length of the vocabulary. Notice that in counting we did not look for the word to be exactly equal but at the start of the word (startswith): "payments" was counted because it starts with "payment". Words grow with endings: *scholarship*, *scholarships*, *scholarship's*. Looking at the start of a word is a simple way to roughly ignore these endings. More advanced systems use tools that find the root of a word, but the idea is the same.
You do not need code for this job; it can be done with pen and paper. Write the vocabulary in the header row of a table, clean the question and split it into words, then scan the words for each header and write how many of them start with that word. In the example below the words are already clean; we count how many times each vocabulary word appears.
Example 2 (case): A bag-of-words vector
vocab = ["scholarship", "dorm", "payment", "room", "exam"] words = "scholarship payment delayed scholarship".split() vector = [words.count(k) for k in vocab] print(vector)
Output[2, 0, 1, 0, 0]If you did it by hand, the table would look like this: scholarship 2, dorm 0, payment 1, room 0, exam 0. Because "delayed" is not in the vocabulary, it was not written in any column; it leaves no trace in the vector. Now it is your turn: convert the question below in your head.
The vocabulary is [scholarship, dorm, payment]. We count by looking at the start of a word. Which is the vector of the question "Can you apply my scholarships to the dorm fee?"
This vector should look familiar. In the features.csv table from the last lesson, next to each question there were columns like aid_k, residence_k, and it_k. Those columns are exactly the result of this counting: each vocabulary word (or group of words) becomes a column in the table, each question becomes a row, and the cell holds how many times that word appears in the question. So turning 600 questions into vectors means building a number table of 600 rows. The model never sees the text itself; it sees only this table.
Example 3 (case): The heater question
question = "Dorm room's heater won't work, dorm office isn't replying." vocab = ["scholarship", "dorm", "room", "heater", "exam"] clean = question.lower().replace(",", "").replace(".", "").replace("?", "") words = clean.split() vector = [] for k in vocab: count = 0 for word in words: if word.startswith(k): count += 1 vector.append(count) print("Question:", question) print("Vocabulary:", vocab) print("Vector:", vector)
OutputQuestion: Dorm room's heater won't work, dorm office isn't replying.
Vocabulary: ['scholarship', 'dorm', 'room', 'heater', 'exam']
Vector: [0, 2, 1, 1, 0]This is the target output at the start of the lesson. This is also why a fixed order in the vector matters: the first number is always the "scholarship" count in every question, and the second number is always the "dorm" count. If someone writes the dorm count in the first position for one question, the model takes that question for a scholarship question. If the order gets mixed up, the columns get mixed up and the questions can no longer be compared. It is not enough for the numbers to be right; they also have to stand in the right place.
The same code is ready in the cell below. Without touching the rest of the code, change only the sentence between the quotes on the top question = "..." line and press Run. Try three things in turn: (1) write a scholarship question and make the first number 1. (2) Write a question that makes the vector [0, 0, 0, 0, 0] and ask yourself: what does the model know about this question? (3) Add the word "loan" to the vocabulary line and try the question "When is my student loan paid out?"
Try it now· not graded; doesn't affect progress
The zero vector in the second try says something important: the question is not empty, but the vocabulary does not recognize the words of the question. For the model, this question is no different from a blank sheet of paper. In the third try, adding a single word to the vocabulary made the vector one number longer, and the "loan" question suddenly became visible.
Who chooses the vocabulary? In features.csv we wrote the vocabulary by hand: a few keywords for each unit. In real systems the vocabulary is usually built automatically from all the words in the training data; this gives vectors with thousands of columns, and the model decides which word is important. Our small vocabulary makes things easier to understand, but a word that is not in the vocabulary does not appear in the vector at all, and the model never knows it.
When we turn a sentence into numbers, we leave some information behind on purpose. It is important to know this, because the model sees only what is left in the vector. There are three losses. The first is word order: which of the words thrown into the bag came first is forgotten. The second is negation: if words like "not" or "no" are not in the vocabulary, the vector stays the same even when the sentence says the opposite. The third is words outside the vocabulary: a word that is not in the vocabulary does not appear at all. The result of these three losses is surprising: two sentences with different meanings can fall on the same vector.
What happens if the sentences "Scholarship yes, dorm no" and "Dorm yes, scholarship no" are turned into vectors with the vocabulary [scholarship, dorm, yes, no]?
Let's see the same thing in an example from outside the campus. We turn food comments that arrive in the cafeteria's comment box into numbers with a five-word vocabulary: great, tasty, bad, cold, late. In the block below, change the comment and look at the vector. Which two comments give the same vector? Do they mean the same thing, too?
Change the comment: which two comments give the same vector, and do they mean the same thing?
Pick a value; predict the output first, then look.
1comment = "The food is great, the service is great!"2vocab = ["great", "tasty", "bad", "cold", "late"]3clean = comment.lower().replace(",", "").replace(".", "").replace("!", "")4words = clean.split()5vector = []6for k in vocab:7 count = 08 for word in words:9 if word.startswith(k):10 count += 111 vector.append(count)12print(vector)
[2, 0, 0, 0, 0]
Faded lines didn't run with this value. The last two comments give the same vector: [1, 0, 1, 0, 0]. One says "not great" and the other "not bad"; they say different things, but the same words appear the same number of times. Because "not" is not in the vocabulary, the negation is not visible, and the word order is lost in the bag.
This loss looks big at first glance, but for jobs like the help desk, a bag of words works surprisingly well. Which unit a question goes to is often given away by a few words that do not depend on order: *tuition*, *room*, *password*. Negative sentences and complicated questions are the limit of this method. In Lesson 3 we saw leaving the question to a person when the scores are close or zero; the same way out applies here. If the vector says "I have no clue" or the sentence contains a negation, the decision can be left to Elena.
Here is a mistake people often make: "The model reads the sentence and knows its meaning." It does not. The model looks only at numbers; if the numbers of two sentences are the same, the two sentences are the same in its eyes.
It is not a good idea to put every word into the vocabulary. Words like "is", "the", "for", and "a" appear in almost every question. Because they are found in aid questions and in residence questions alike, they are no use for telling questions apart; they only make the vector longer. These are called stop words, and most systems drop them before counting. A good vocabulary word is one that appears often in the questions of one unit and rarely in the others: "tuition" gives away enrollment questions, "heater" residence questions, "password" IT questions. So "the more words, the better" is not true; what matters is whether the word separates the questions.
Let's go back to the cafeteria. We want to build a filter that separates comments into "happy" and "complaint". We build the count table from Lesson 3 here, too: in the labeled comments we have, we count how many times each vocabulary word appears in each class. "great" and "tasty" appear often in happy comments; "cold", "late", and "bad" in complaints. Then we give a score to a new comment.
Example 4 (outside the case): Cafeteria comment filter
reviews = [
("the food is great", "happy"),
("the soup is very tasty", "happy"),
("the dessert is great and tasty", "happy"),
("the rice is cold and bad", "complaint"),
("the service came late", "complaint"),
]
vocab = ["great", "tasty", "bad", "cold", "late"]
table = {k: {"happy": 0, "complaint": 0} for k in vocab}
for review, label in reviews:
for word in review.split():
for k in vocab:
if word.startswith(k):
table[k][label] += 1
new_review = "not great and cold"
score = {"happy": 0, "complaint": 0}
for word in new_review.split():
for k in vocab:
if word.startswith(k):
for label in score:
score[label] += table[k][label]
print(table["great"], table["cold"])
print(new_review, , score)Output{'happy': 2, 'complaint': 0} {'happy': 0, 'complaint': 1}
not great and cold -> {'happy': 2, 'complaint': 1}The filter counts the comment "not great and cold" as happy: "great" appears in two happy comments, so it brings 2 points, while "not" is not in the vocabulary, so it says nothing. The person who wrote the comment is clearly complaining. This is the price of a bag of words losing negation. Real filters build the vocabulary automatically and use thousands of columns; some also count two words side by side, like "not great", as a single vocabulary item. But the basic idea is the same: the text is first turned into numbers, and the model sees only the numbers.
Match each situation with the information that is lost or distorted in the conversion.
For each row, pick its match from the list, then check.
exam column comes out as 1Another misconception in this lesson is about order: "If the numbers are right, that is enough." It is not; the same numbers written to other columns describe a different question. A vector carries information both through its content and through its order: the content is in the numbers, and the meaning is in which vocabulary word each number belongs to.
Now every question is a list of numbers. In the next lesson we will compare two lists and build our first model: we will find the old questions that look most like a new question and look at their unit.
Plain lowercasing leaves the hyphen in "Wi-Fi" and "E-Mail"; first the hyphen is removed, then the text is lowercased.
raw = "Wi-Fi is down and my E-Mail is too" wrong = raw.lower() right = raw.replace("-", "").lower() print(wrong.split()[0] == "wifi") print(right.split()[0] == "wifi") print("E-Mail".lower(), "E-Mail".replace("-", "").lower())
OutputFalse
True
e-mail emailEvery question converted with the same vocabulary becomes one row of the table; the columns stand in the same order in every row.
questions = [
"Did my scholarship payment arrive?",
"My dorm room's heater is not working.",
"When will my exam results be announced?",
]
vocab = ["scholarship", "dorm", "room", "heater", "exam"]
print("scholarship dorm room heater exam")
for question in questions:
clean = question.lower().replace("?", "").replace(".", )
words = clean.split()
vector = [(1 w words w.startswith(k)) k vocab]
(vector)Lowercasing without unifying the spellings. A plain lower() turns "Wi-Fi" into "wi-fi" and "WIFI" into "wifi"; these two are counted as different words, and "E-Mail" becomes "e-mail", which does not match "email" in the vocabulary. So the same word is counted in two different forms and the vector loses a count. First remove the hyphen with replace("-", ""), then lowercase: "Wi-Fi".replace("-", "").lower() == "wifi" is True.
aid_k and residence_k columns in features.csv are this count, and the model sees only these numbers, not the text.Next lesson: we will compare vectors and build our first model with the nearest neighbor method.
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.
Outputscholarship dorm room heater exam
[1, 0, 0, 0, 0]
[0, 1, 1, 1, 0]
[0, 0, 0, 0, 1]