Week 02 · Bag of words and TF–IDF
Build a baseline and inspect the terms that drive its predictions.
← Week 1 · Subject contents · Week 3 →
Build a baseline and inspect the terms that drive its predictions.
Work through the problem
A bag of words maps each document to token counts. TF–IDF downweights terms that occur in many documents. In the vectorizer below the smoothed inverse document frequency is 1+log((1+n)/(1+df)). In four documents, a term appearing once has weight about 1.916; a term appearing in all four has weight 1.
A linear classifier scores w·x+b. Inspect the coefficient direction for a term, but remember its actual contribution also depends on the token’s TF–IDF value in the input. This baseline ignores word order, so “cache misses” and “misses cache” have the same representation.
Run the Python lab
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
docs = ["cache key hit","cache expired key","queue job retry","queue retry worker"]
v = TfidfVectorizer()
X = v.fit_transform(docs)
model = LogisticRegression(solver="liblinear").fit(X,[0,0,1,1])
for term, weight in sorted(zip(v.get_feature_names_out(),model.coef_[0]),key=lambda pair:pair[1]):
print(term,round(weight,3))
test = model.predict(v.transform(["cache key","worker retry"])).tolist()
print("Predictions:",test)
assert test==[0,1]
Output from the lab
cache -0.382
key -0.382
expired -0.242
hit -0.242
job 0.242
worker 0.242
queue 0.382
retry 0.382
Predictions: [0, 1]
Practice
- How would you retain the phrase “cache key” as a separate feature?
Check your reasoning
- Include bigrams with ngram_range=(1,2), then validate whether they improve held-out results.
← Week 1 · Subject contents · Week 3 →
Further reading · Jurafsky and Martin · Speech and Language Processing