Sub topic 8
Term frequency
This chapter covers how to turn a raw word count into a term frequency (TF) weight. You should already know how a document-term matrix is built with CountVectorizer, and you should be comfortable with NumPy arrays and natural logarithms.
What term frequency measures
Term frequency measures how much a term t contributes to a document d. The simplest definition is the raw count:
tf(t, d) = count of t in d
Every cell of the document-term matrix from the previous chapter already holds this value. The question is whether the raw count is the best number to feed a model. Two problems suggest it is not:
- Document length. A 2,000-word article contains "cat" more often than a 20-word note, even if both are about cats equally.
- Diminishing returns. A document that uses a word 20 times is probably not 20 times more about that topic than one that uses it once.
Term frequency variants address these problems by rescaling the counts.
Common variants
| Variant | Formula | scikit-learn setting |
|---|---|---|
| Raw count | `count(t, d)` | default |
| Relative frequency | `count(t, d) / total terms in d` | `norm="l1"` with `use_idf=False` |
| Binary | `1` if `count > 0`, else `0` | `binary=True` |
| Log scaling | `1 + ln(count)` if `count > 0`, else `0` | `sublinear_tf=True` |
Relative frequency divides by the document length, which removes the length effect directly. Binary keeps only presence or absence. Log scaling shrinks large counts: a count of 1 stays 1, a count of 2 becomes about 1.69, and a count of 10 becomes about 3.30.
Computing the variants by hand
The code below builds the count matrix for the three-sentence corpus and derives the other variants with NumPy.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
counts = vec.fit_transform(docs).toarray()
print(vec.get_feature_names_out())
raw = counts
relative = counts / counts.sum(axis=1, keepdims=True)
binary = (counts > 0).astype(int)
log_tf = np.zeros(counts.shape)
mask = counts > 0
log_tf[mask] = 1 + np.log(counts[mask])
print("raw ", raw[0])
print("relative", relative[0].round(2))
print("binary ", binary[0])
print("log ", log_tf[0].round(2))The vocabulary is alphabetical: cat, chased, dog, log, mat, on, sat, the. For the first document the four rows are:
- raw:
[1 0 0 0 1 1 1 2] - relative:
[0.17 0 0 0 0.17 0.17 0.17 0.33], since the document has 6 tokens - binary:
[1 0 0 0 1 1 1 1] - log:
[1 0 0 0 1 1 1 1.69]
Notice that "the" has the largest weight in every variant except binary. Term frequency alone rewards common words. The next chapter on IDF corrects that. TF is only half of the TF-IDF weight.
Reproducing the variants in scikit-learn
TfidfVectorizer can output pure term frequency if you disable IDF and normalization. This is useful for checking your understanding against the library.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
counts = CountVectorizer().fit_transform(docs).toarray()
log_tf = np.zeros(counts.shape)
mask = counts > 0
log_tf[mask] = 1 + np.log(counts[mask])
sk_log = TfidfVectorizer(
use_idf=False, norm=None, sublinear_tf=True
).fit_transform(docs).toarray()
sk_rel = TfidfVectorizer(
use_idf=False, norm="l1"
).fit_transform(docs).toarray()
print(np.allclose(sk_log, log_tf))
print(np.allclose(sk_rel, counts / counts.sum(axis=1, keepdims=True)))Both checks print True. Two details matter here:
use_idf=False, norm=Nonegives plain counts. Addingsublinear_tf=Trueapplies1 + ln(count)to the nonzero entries.norm="l1"makes each row sum to 1, which is exactly relative frequency.
How length affects each variant
Suppose a document is pasted twice into itself. Every count doubles, but the document is not about anything new. Each variant reacts differently:
- Raw counts double, so the vector gets longer. Distances between it and other documents change.
- Relative frequencies stay identical.
- Binary values stay identical.
- Log values grow by a constant
ln(2)on each nonzero entry, which is a small shift rather than a doubling.
Cosine similarity, covered in a later chapter, ignores vector length. For raw counts, repeating a whole document leaves its cosine similarity to other documents unchanged. This is one reason raw counts with L2 normalization work acceptably in practice. Length effects remain when documents differ in content as well as size, and that is where relative or log scaling helps.
Choosing a variant
Use these rules as a starting point, then check them on a validation set:
- Default to raw counts or
sublinear_tf=Truefor classification. Log scaling reduces the influence of a spammy word repeated many times. It often helps on documents of very different lengths. - Use
binary=Truefor short texts. In tweets or titles, most words appear once, so counts add little. Binary features also suit Naive Bayes variants that model presence. - Use relative frequency when you compare distributions of words. Examples are topic profiles or comparing a corpus's word usage across authors.
- Do not tune on the test set. The choice of TF variant is a hyperparameter like any other.
Common mistakes
- Applying
np.logto a zero count.ln(0)is negative infinity. Always mask zeros first, as the code above does. scikit-learn applies the transform only to stored nonzero entries, so it avoids the problem. - Using
1 + ln(count)on relative frequencies. The log formula assumes counts of at least 1. A relative frequency of 0.05 would give a negative weight. - Forgetting that
TfidfVectorizernormalizes by default. With defaults,norm="l2"rescales every row, so the output is not the raw TF you may expect. - Assuming a higher TF always means a better feature. Stop words have the highest TF in most documents. Use IDF, stop-word removal, or
max_dfto handle them.
Exercise
A document has 100 tokens, and the word "free" appears 8 times. Compute the raw count, the relative frequency, and the log-scaled TF (use the natural logarithm). If the document is then doubled in length by repeating it once, what happens to each of the three values?
Show answer
Raw count = 8. Relative frequency = 8 / 100 = 0.08. Log-scaled TF = 1 + ln(8) = 1 + 2.079 = about 3.08. After repeating the document, "free" appears 16 times in 200 tokens. The raw count doubles to 16. The relative frequency stays 0.08. The log TF becomes 1 + ln(16) = about 3.77, an increase of ln(2), or about 0.69.
Exercise
Write the TfidfVectorizer arguments that produce binary term presence with no IDF weighting and no row normalization.
Show answer
TfidfVectorizer(binary=True, useidf=False, norm=None). Setting binary=True makes every nonzero count 1, useidf=False skips the IDF multiplication, and norm=None leaves the rows unscaled. This gives the same matrix as CountVectorizer(binary=True).