liveBook · Manning

Term frequency-inverse document frequency

As explained in Data Without Labels

Term frequency-inverse document frequency (TF-IDF) assigns a term a weight based on its frequency in a document and its inverse frequency across a document collection.

TF-IDF represents documents by weighting terms according to both their local frequency and their rarity across the document collection. It emphasizes words that distinguish documents rather than words that merely occur often. In a medical corpus, “diabetes” may identify relevant documents more effectively than the common word “disease.” section 7.10

Term frequency (TF) counts a term within a document, while inverse document frequency (IDF) uses the logarithm of the ratio between the total document count and the number of documents containing that term. TF-IDF is their product, combining document-specific frequency with collection-wide rarity. section 7.10

Sports-document calculation

For a 100-word sports document containing “ground” five times and “backhand” twice, the term frequencies are 0.05 and 0.02. Because “ground” is common in sports while “backhand” is rarer, inverse document frequency can give the latter greater relative importance. section 7.10

A practical workflow uses scikit-learn's TfidfVectorizer to convert text into a matrix, optionally removing English stop words. The resulting vectors can feed K-means clustering, whose centroids and prominent terms help separate football and travel documents. section 7.16

tfidf_vectorizer = TfidfVectorizer(stop_words='english')
X = tfidf_vectorizer.fit_transform(text)

Inspect the Python statement that fits a TF-IDF vectorizer to text and produces the document-term matrix. section 7.16

How Data Without Labels covers it

How deep it goes
Explains TF and IDF definitions, gives a worked calculation, and demonstrates Python vectorization before clustering.
Examples
Uses medical terms, sports vocabulary, and a football-versus-travel Python clustering dataset.
What it assumes
Assumes documents, terms, and document counts, while defining term frequency and inverse document frequency explicitly.
What you can do after
Apply it via scikit-learn's TfidfVectorizer and use the resulting vectors in K-means text clustering.
How it connects
Contrasts with bag-of-words and feeds text clustering, while belonging to broader tokenization and text-representation workflows.

Also explained in

Compare how 10 books explain term frequency-inverse document frequency →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Without Labels. The section links point to the parts of the book it draws on.