Concepts / Pipelines in scikit-learn for Text Models

Pipelines in scikit-learn for Text Models

tf-idf rescales word counts so that words distinguishing documents count for more, and the source reports that this improved model performance over plain word counts.

  • Programming

Why a Text Classifier Needs Numbers

Imagine you are building a classifier that reads movie reviews and decides whether each one is positive or negative. A model cannot work directly with sentences, so the first job is turning each review into numbers. A simple way to do this is to count how many times each word appears in each review. Those counts become the model's input features.

Counting is a reasonable starting point, but it treats every word as equally informative. Common words that show up in almost every review add as much weight as a word that appears in only a few reviews and therefore says something specific about them. This article follows one review through the process, explains how tf-idf rescales the raw counts, and shows how to check whether that rescaling is actually helping.

Following One Review Through the Pipeline

Follow one review through the process. It starts as a string of text. The vectorizer breaks the text into words and assigns each word a numeric value for that review. Those values are the features the classifier sees. In the setup described by the source, the vectorizer is one step inside a pipeline, so the same transformation happens automatically whenever new text goes through the pipeline.

Raw review texta string of wordsTfidfVectorizersplits text and weightswordstf-idf featuresnumeric value per wordModel steplearns from the featuresCross-validationscorecompared across experimentsentersproducesfeedsevaluated as
Which step produces the features, and which step's fitted object do you pull out to inspect the learned words and weights?

The diagram shows the chain as a sequence. Raw review text enters the vectorizer, the vectorizer produces tf-idf features, the model step learns from those features, and the resulting cross-validation score is what you compare across experiments. The vectorizer is the only step that turns text into numbers, which is why it is the object you will later pull out for inspection.

What tf-idf Is Trying to Find

The practical effect of tf-idf is that words spread across nearly every document carry less weight, while words concentrated in a smaller set of documents carry more. A reviewer's distinctive vocabulary is more likely to earn a high score than filler that appears in every review. This is the sense in which tf-idf rescales the raw counts: the same word can count for different amounts depending on how it is distributed across the collection.

filmcount 4filmlower weightdullcount 1dullhigher weight
The same review produces different weights for a filler word and a distinctive word once tf-idf rescales the counts.
Worked example

Why a word in every review loses weight

Three short reviews are in the collection. The word film appears in all three. The word dull appears in only one. Which word should tf-idf treat as more useful for telling reviews apart?

  1. 1
    Count the documents

    film is in 3 of 3 reviews, so it is spread across the whole collection.

  2. 2
    Count the rare word

    dull is in only 1 of 3 reviews, so it is concentrated in a smaller set of documents.

  3. 3
    Apply the rescaling idea

    The frequent-everywhere word is down-weighted relative to its raw count, and the concentrated word keeps more of its weight.

  4. 4
    Read the result

    dull is the better candidate for distinguishing this review from the others, even though film may appear more often inside a single review.

Result

tf-idf favors words that are distributed unevenly across documents. Here dull distinguishes reviews, while film mostly describes the whole collection.

Key point

Plain counts ask how often a word appears. tf-idf asks how often a word appears and whether it is spread across many documents or concentrated in a few.

Reading the Cross-Validation Score

The source reports that the switch from plain word counts to tf-idf gives a noticeable improvement in model performance. The evidence is the cross-validation score, which goes up when tf-idf replaces the raw counts. A cross-validation score is a metric used to evaluate model performance. The source reports a best cross-validation score of 0.89 for the tf-idf version of the classifier, and a higher score in this comparison is what signals the improvement over word counts.

Read the number as a summary of how well the model did on held-out portions of the data, not as a verdict on whether the features are meaningful. Two runs can produce different scores for reasons that have nothing to do with the words themselves. A score is therefore most useful when you compare setups that differ in one deliberate way, such as counts versus tf-idf.

Why tf-idf Never Sees the Labels

After the score improves, the natural next step is to inspect which words tf-idf ranks as most important. The source gives a caution here: tf-idf is a purely unsupervised technique. It never looks at the labels when it computes its weights. The labels are only used later, when the classifier is trained and evaluated.

Document textthe only input to tf-idftf-idf weightsdistinguish documentsClassifier traininguses labels laterClass labelspositive or negativecomputesfeedssupervises
tf-idf computes weights from document text alone, so its top words describe the collection's distinguishing vocabulary, not the class labels.

What do you think happens?

When tf-idf computes its word weights, does it use the positive and negative labels?

  • Yes, it uses the labels to pick words that predict each class

  • No, it uses only the document text

Reveal answer
Answer:

No, it uses only the document text.

tf-idf is purely unsupervised. Its highest-weighted words describe what distinguishes documents, which may or may not match the words that predict each class.

Retrieving the TfidfVectorizer from the Pipeline

To inspect the tf-idf words, you need the vectorizer itself, not the whole pipeline. The source's first step for this inspection is to extract the TfidfVectorizer from the pipeline. Once you have that object, you can look at the features it produced and see which words received the highest weights.

  1. 1
    Fit the pipeline so the vectorizer has learned its vocabulary and weights from the training text.
  2. 2
    Locate the TfidfVectorizer step inside the fitted pipeline. This is the object that turns text into tf-idf features.
  3. 3
    Extract that vectorizer as its own object, separate from the classifier step.
  4. 4
    Inspect the features it produced and find the words that received the highest weights.

Mistakes When Reading Pipeline Results

  • Common mistake

    Treating the cross-validation score as proof that the top words are meaningful

    Why it fails

    The score summarizes held-out performance. It does not explain which words drove the result or whether they are meaningful.

    Do this instead

    Use the score to compare setups that differ in one deliberate way, then inspect the words separately.

  • Common mistake

    Assuming tf-idf's top words are the words that predict each class

    Why it fails

    tf-idf never looks at the labels, so its highest weights reflect how words are distributed across documents.

    Do this instead

    Treat tf-idf's top words and the classifier's predictive words as two different things, and check them separately.

  • Common mistake

    Trying to inspect the vocabulary from the whole pipeline object

    Why it fails

    The learned vocabulary and weights live in the vectorizer step, not in the pipeline as a whole.

    Do this instead

    Extract the TfidfVectorizer from the fitted pipeline first, then look at its features.

Practice: Predict the Top Words

MEDIUM

A collection contains many movie reviews. The word movie appears in almost every review, and the word cinematography appears only in reviews praising the visuals. Before you inspect anything, predict which of these two words tf-idf is more likely to rank highly, and explain why the classifier's most predictive words might still differ from tf-idf's top words.

Hints
  • Think about whether a word is spread across nearly every document or concentrated in a few.
  • Remember that tf-idf never looks at the positive or negative labels when computing weights.

Key Takeaways

  • tf-idf rescales word counts so that words concentrated in fewer documents count for more, and words spread across nearly every document count for less.
  • The source reports that tf-idf improved the cross-validation score over plain word counts, with a best value of 0.89 for the tf-idf version.
  • A cross-validation score summarizes performance on held-out data. It is most useful when comparing setups that differ in one deliberate way, and it is not proof that the features are meaningful.
  • tf-idf is purely unsupervised, so its most important words describe distinguishing documents and may not match the class labels.
  • To inspect tf-idf's results, extract the TfidfVectorizer from the fitted pipeline and look at the features and weights it produced.

Related concepts

More concepts starting with P