Sub topic 8
Term Frequency: Measuring How Often a Term Appears
Assume you know basic Python, NumPy vectors, and how a classifier uses fit and predict. You should also be comfortable with logarithms, although this chapter does not need one.
Term frequency (TF) measures how often a term appears in one document. A term is usually a token such as a word or an n-gram. TF describes the document itself. It does not yet compare how common the term is across the whole collection. That later comparison uses inverse document frequency.
Raw term frequency
The simplest TF value is the raw count:
\mathrm{TF}(t,d) = \text{number of times term }t\text{ occurs in document }dConsider this document:
cats chase cats and dogsThe term cats occurs twice. Its raw TF is 2. The terms chase, and, and dogs each have a raw TF of 1. A term that does not occur has a TF of 0.
| Term | Raw count | Total tokens | Relative TF |
|---|---|---|---|
| cats | 2 | 5 | 0.40 |
| chase | 1 | 5 | 0.20 |
| dogs | 1 | 5 | 0.20 |
| birds | 0 | 5 | 0.00 |
Relative TF adjusts for document length:
\mathrm{TF}_{\mathrm{relative}}(t,d)
=
\frac{\text{count}(t,d)}{\text{number of tokens in }d}Here, cats has relative TF \(2/5 = 0.40\). This adjustment matters when one document is much longer than another. A raw count of 2 means something different in a five-token document than in a 1,000-token document.
Common TF choices
A vectorizer can represent term frequency in several ways:
- Raw count: use the number of occurrences.
- Binary presence: use 1 if the term occurs and 0 otherwise.
- Relative frequency: divide each count by the document's token count.
- Sublinear TF: replace a positive count \(c\) with \(1+\log(c)\). This reduces the effect of repeated terms.
Sublinear TF is useful when repeating a word 20 times should not make it 20 times as important as a word used once. In scikit-learn, sublinear_tf=True selects this transformation.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"cats chase cats and dogs",
"dogs sleep",
]
vectorizer = TfidfVectorizer(
use_idf=False,
norm=None,
sublinear_tf=True,
)
matrix = vectorizer.fit_transform(docs)
print(vectorizer.get_feature_names_out())
print(matrix.toarray().round(3))With use_idf=False, the vectorizer applies TF without inverse document frequency. With norm=None, it does not perform a later row normalization, so the printed values show the selected TF transformation directly.
Exercise
In the document "red blue red green red", what are the raw TF and relative TF of "red"?
Show answer
The raw TF is 3. There are 5 tokens, so the relative TF is 3/5 = 0.6.