🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Turn Text into Numbers

A computer cannot read words, so text must become numbers first. A bag of words turns each document into a row of word counts.

Count the words

CountVectorizer learns four words from two short lines. Each row counts one line.

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
docs = ["I love this film", "I hate this film"]
counts = CountVectorizer()
matrix = counts.fit_transform(docs)
print("Vocabulary:", sorted(counts.vocabulary_))
print(matrix.toarray())

Rare words weigh more

The word love appears in one line only, so its TF-IDF score beats the shared word film.

tfidf = TfidfVectorizer()
scores = tfidf.fit_transform(docs)
names = tfidf.get_feature_names_out()
row = scores.toarray()[0]
for word in ["love", "film"]:
    print(word, round(float(row[list(names).index(word)]), 3))

New text uses the old vocabulary

transform() counts new text with the words the vectorizer already knows. The word great is unknown, so it drops out.

new = counts.transform(["I love this great film"])
print("New shape:", new.shape)
print("New row:", new.toarray()[0])

Example

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer

docs = [
    "I love this film",
    "I hate this film",
    "This film is great",
    "This film is bad",
]
counts = CountVectorizer()
matrix = counts.fit_transform(docs)
print("Vocabulary:", len(counts.vocabulary_))
print("Count type:", type(matrix).__name__)
print("Count shape:", matrix.shape)
print("Dense shape:", matrix.toarray().shape)
print("First row:", matrix.toarray()[0])
tfidf = TfidfVectorizer()
scores = tfidf.fit_transform(docs)
print("TF-IDF shape:", scores.shape)
print("TF-IDF first row:", [round(float(v), 3) for v in scores.toarray()[0]])

Key points

  • Bag of words: a table that counts how often each word appears in each document
  • Vocabulary: the full list of words the table knows
  • Token: one word after splitting the text apart
  • Use CountVectorizer to build the count table from a list of documents
  • Document frequency: the number of documents that hold a word
  • TF-IDF: a score that lifts rare words and lowers common ones
  • Use TfidfVectorizer to build the TF-IDF table in one step

In this example, the docs list holds four short film lines. CountVectorizer learns a vocabulary of 7 words and turns the lines into a count table. The table is a csr_matrix, which is a sparse matrix that stores only the non-zero counts. Its shape is 4 rows by 7 columns, and toarray() shows the same shape in dense form. The first row counts the line I love this film. TfidfVectorizer then builds a second table with the same shape, where the rare words score higher than the shared ones. In short, turning text into numbers means counting words per document, then weighting the rare words up and the common words down.

Note

The tables are sparse, so most cells hold zero. Print the dense form with toarray() to see the numbers.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does CountVectorizer count?