Working with Text
Reviews, support tickets, emails, tweets: a lot of valuable data is text. Models need numbers, so text must be turned into a numeric table first. The classic, surprisingly strong approach is the bag of words: ignore word order and count which words appear in each document.
CountVectorizer: bag of words
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the battery lasts all day",
"battery died after one day",
"great screen and great battery",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
print("vocabulary:", list(vec.get_feature_names_out()))
print(X.toarray())
print("type:", type(X).__name__, " shape:", X.shape)vocabulary: ['after', 'all', 'and', 'battery', 'day', 'died', 'great', 'lasts', 'one', 'screen', 'the']
[[0 1 0 1 1 0 0 1 0 0 1]
[1 0 0 1 1 1 0 0 1 0 0]
[0 0 1 1 0 0 2 0 0 1 0]]
type: csr_matrix shape: (3, 11)
Each column is one word from the vocabulary learned during fit, each row one document, each cell a count ("great" appears twice in the third review). The result is a sparse matrix: real vocabularies have tens of thousands of words, and most cells are zero, so only non-zero values are stored.
Useful options
| Option | Effect |
|---|---|
lowercase=True (default) |
"Battery" and "battery" are the same word |
stop_words="english" |
drop very common words: "the", "and", "a" … |
ngram_range=(1, 2) |
also count pairs of words ("not good") |
min_df=2 |
ignore words in fewer than 2 documents |
max_features=1000 |
keep only the 1 000 most frequent words |
binary=True |
1/0 for presence instead of counts |
from sklearn.feature_extraction.text import CountVectorizer
docs = ["The food was not good", "The food was good", "Not bad at all"]
vec = CountVectorizer(stop_words="english", ngram_range=(1, 2))
vec.fit(docs)
print(list(vec.get_feature_names_out()))['bad', 'food', 'food good', 'good']
Careful: the English stop-word list includes "not", which can flip the meaning of a review! For sentiment tasks it's often better to keep stop words and use bigrams.
TF-IDF: weighting informative words
Raw counts favour words that are frequent everywhere. TF-IDF (term frequency × inverse document frequency) lowers the weight of words that appear in many documents and raises rare, distinctive ones:
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the battery lasts all day",
"battery died after one day",
"great screen and great battery",
]
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
words = vec.get_feature_names_out()
for i, doc in enumerate(docs):
row = X[i].toarray().ravel()
top = row.argsort()[::-1][:3]
print(f"{doc!r:34} top words: {[(words[j], round(float(row[j]), 2)) for j in top]}")
print("idf of 'battery':", round(float(vec.idf_[vec.vocabulary_['battery']]), 3),
" idf of 'screen':", round(float(vec.idf_[vec.vocabulary_['screen']]), 3))'the battery lasts all day' top words: [('the', 0.5), ('lasts', 0.5), ('all', 0.5)]
'battery died after one day' top words: [('one', 0.5), ('died', 0.5), ('after', 0.5)]
'great screen and great battery' top words: [('great', 0.79), ('screen', 0.4), ('and', 0.4)]
idf of 'battery': 1.0 idf of 'screen': 1.693
"battery" appears in every review, so its IDF is the minimum and it never makes the top of a document's list. Each row is also normalised to length 1, so long and short documents are comparable.
A sentiment classifier
Let's train a tiny review classifier: TF-IDF features into logistic regression, wrapped in a pipeline so the raw strings go straight in.
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
reviews = [
"loved it, works perfectly", "excellent quality and fast delivery", "really happy with this purchase",
"great value, would buy again", "works great, very happy", "perfect fit and excellent finish",
"broke after two days", "terrible quality, very disappointed", "did not work at all",
"waste of money, broke quickly", "very poor and slow delivery", "disappointed, would not buy again",
]
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0] # 1 = positive
model = make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression(C=10))
model.fit(reviews, labels)
tests = ["excellent, works perfectly", "poor quality, broke", "would buy again, happy", "not happy at all"]
for text, p in zip(tests, model.predict_proba(tests)[:, 1]):
print(f"{text!r:30} P(positive) = {p:.2f}")'excellent, works perfectly' P(positive) = 0.83
'poor quality, broke' P(positive) = 0.27
'would buy again, happy' P(positive) = 0.67
'not happy at all' P(positive) = 0.32
With 12 training sentences this is a toy, but the same pipeline trained on thousands of reviews is a genuinely strong baseline.
Which words matter?
For a linear model, every word gets a coefficient. The largest positive and negative ones show what the model learned:
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
reviews = [
"loved it, works perfectly", "excellent quality and fast delivery", "really happy with this purchase",
"great value, would buy again", "works great, very happy", "perfect fit and excellent finish",
"broke after two days", "terrible quality, very disappointed", "did not work at all",
"waste of money, broke quickly", "very poor and slow delivery", "disappointed, would not buy again",
]
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
model = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10)).fit(reviews, labels)
words = model[0].get_feature_names_out()
coefs = model[-1].coef_[0]
order = coefs.argsort()
print("most negative:", [str(words[i]) for i in order[:5]])
print("most positive:", [str(words[i]) for i in order[-5:][::-1]])most negative: ['disappointed', 'not', 'broke', 'slow', 'poor']
most positive: ['great', 'excellent', 'works', 'happy', 'value']
Note: Bag-of-words ignores word order and meaning ("not good" vs "good" needs bigrams; "awful" and "terrible" are unrelated columns). Modern NLP uses embeddings from neural language models, which place similar words and sentences close together. They are beyond this course, but the pipeline idea is the same: text → numeric vectors → classifier.
Go further: TF-IDF Weighting rebuilds
TfidfVectorizerfrom scratch and explains its knobs: sublinear tf, smoothing and idf.
Test yourself
What does CountVectorizer produce for a list of documents?
- A list of sentences
- A sparse matrix of word counts, one row per document
- One number per word
- Word embeddings
What does the IDF part of TF-IDF do?
- Counts words per document
- Lowers the weight of words that appear in many documents
- Removes punctuation
- Translates words
Why can stop_words='english' hurt a sentiment classifier?
- It is very slow
- It removes negations such as 'not'
- It adds extra words
- It only works with TF-IDF