Concepts / Word Counts as Features for Text Classification

Word Counts as Features for Text Classification

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 Model Needs Numbers, Not Sentences

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 to turn 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 those reviews. This article asks two questions: what happens when the counts are rescaled with tf-idf before the model sees them, and how you can check whether that rescaling is actually helping.

What do you think happens?

In a set of movie reviews, which should count for more in a positive-or-negative classifier: a word that appears in every review, or a word that appears in only one review?

  • The word that appears in every review

  • The word that appears in only one review

Reveal answer
Answer:

The word that appears in only one review

Words spread across nearly every document say little that distinguishes one review from another, so tf-idf gives them less weight. A word concentrated in a smaller set of documents carries more distinguishing weight.

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 the source describes, the vectorizer is one step inside a pipeline, so the same transformation happens automatically whenever new text goes through the pipeline.

review textraw sentencesTfidfVectorizersplits text into wordstf-idf featuresnumeric value per wordclassifierlearns from featuresclass labelspositive or negativecross-validationscoreresult to compareentersproducesinput toused in trainingevaluated to give
Which step receives the raw review text, which step produces the features, and where the class labels enter the process.

Notice where the labels enter. The text goes into the vectorizer first, and the labels only reach the process at the classifier. The vectorizer produces its features without them. Keep this ordering in mind, because it becomes important when you try to interpret which words tf-idf ranks highly.

What Plain Counts Miss

Plain word counts are easy to compute and easy to explain, but they give every word the same kind of influence. A word that appears in almost every review contributes its count just as strongly as a word that appears only in a handful of reviews. Yet the second kind of word is the one that helps separate one review from another. Filler that shows up everywhere adds noise rather than distinction.

raw count per wordhow often it appearsrescaled count perwordadjusted by spreadevery word weightedalikecommon filler includedspread-out wordsdown-weighted
How the same review is represented under plain counts and under tf-idf, and what changes about how each word is treated.

The source reports that switching from plain word counts to tf-idf gives a noticeable improvement in model performance, and that the evidence is a cross-validation score that goes up when tf-idf replaces the raw counts. The rest of this article looks at what that improvement does and does not tell you.

Tracing Word Weights Across Reviews

The core idea of tf-idf is that the weight of a word depends on two things at once: how often it appears in a particular document, and how widely it is spread across the whole collection. The source describes the effect in practical terms: words spread across nearly every document carry less weight, while words concentrated in a smaller set of documents carry more. The same word can therefore count for different amounts depending on how it is distributed.

theappears in every reviewtheweight reducedboringappears in one reviewboringweight kept hightf-idf scalingtf-idf scaling
What happens to a word's weight when it appears in nearly every review versus only one, and why the two cases end up different.
Worked example

Comparing two words across three reviews

Suppose a tiny collection has three movie reviews. The word 'the' appears in all three. The word 'boring' appears in only one. Decide which word tf-idf should treat as more distinctive, using only the spread of each word across the reviews.

  1. 1
    Check how widely each word is spread

    'the' appears in every review, so it is spread across the whole collection. 'boring' appears in only one review, so it is concentrated in a small set of documents.

  2. 2
    Apply the rule from the source

    Words spread across nearly every document carry less weight. Words concentrated in fewer documents carry more.

  3. 3
    Compare the resulting weights

    'the' is down-weighted even though it may occur several times in a review, while 'boring' keeps a high weight in the one review where it appears.

  4. 4
    Interpret the outcome

    For a positive-or-negative classifier, 'boring' is the more distinctive feature here. This is an illustration of the weighting logic, not a measured result from the source.

Result

tf-idf gives 'boring' more weight than 'the' because 'boring' is concentrated in fewer reviews, while 'the' is spread across all of them.

Reading the Document-Term Matrix

When the vectorizer processes a collection of reviews, the result is a matrix of features. Each row corresponds to one document, and each column corresponds to one vocabulary word. A cell records the value for that word in that document. Because each word has a fixed column position, you can always trace a feature back to the word it represents.

greatcolumn 0boringcolumn 1thecolumn 2
Each vocabulary word occupies one column of the feature matrix. The column position links the feature back to the word the vectorizer learned.

This mapping matters when you inspect results. Once you know which column is which word, a high value in a column tells you which vocabulary word that document relied on. The vectorizer holds the vocabulary that defines these positions, which is one reason you need the vectorizer object itself and not just the matrix it produced.

Why tf-idf Is Unsupervised

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

This is why inspection is worth doing carefully. If you look at the top tf-idf words and see distinctive vocabulary, that tells you something about how the collection is spread out. Whether those words line up with the classes is a separate question, and the vectorizer never answered it because it never saw the labels.

Reading a Cross-Validation Score

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. The score summarizes how well the model did on held-out portions of the data.

Cross-validation works by splitting the data into folds, scoring the model on each held-out fold, and then summarizing those per-fold results. The result is a single number that reflects performance across the folds rather than on one lucky or unlucky split.

Finding the Vectorizer Inside a 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 fitted pipeline. The vectorizer is one step among the pipeline's steps, alongside the classifier step, so you reach it by navigating from the pipeline object to the step that holds it.

fitted pipelinewhole trained objectTfidfVectorizer stepproduces tf-idf featuresword weightsready to inspectclassifier steplearns from featurescontainscontainsextract and inspect
The fitted pipeline contains a vectorizer step and a classifier step. Extracting the vectorizer gives access to the tf-idf words it found important.

Once you have the vectorizer object, you can look at the features it produced and see which words received the highest weights. Keep the two roles separate in your head: the vectorizer is the piece that learned weights from text, and the classifier is the piece that used those weights together with the labels.

Mistakes With Counts, Scores, and Labels

  • Common mistake

    Assuming a high tf-idf word is a label-predicting word

    What it looks like

    Seeing the top tf-idf word and concluding it signals a positive review.

    Why it fails

    tf-idf is purely unsupervised and never looks at the labels, so its most important words mean distinguishing documents and not necessarily the classes.

    Do this instead

    Check the words' relationship to the labels separately, using the classifier's results rather than the weights alone.

  • Common mistake

    Treating a cross-validation score as proof that the features are meaningful

    What it looks like

    Reporting a score of 0.89 as evidence that the model understands sentiment.

    Why it fails

    A score summarizes performance on held-out portions of the data. Different scores can arise from factors unrelated to the words.

    Do this instead

    Describe the score as performance evidence and compare setups that differ in one deliberate way.

  • Common mistake

    Inspecting the whole pipeline when you need the vectorizer

    Why it fails

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

    Do this instead

    Extract the TfidfVectorizer from the fitted pipeline before looking at the features it produced.

  • Common mistake

    Assuming a word that appears often is always important, regardless of how many documents it appears in

  • Common mistake

    Comparing two runs that differ in many ways at once, so you cannot tell what caused a score change

Practice Tracing Word Weights

MEDIUM

A classifier reads movie reviews. The word 'film' appears in nearly every review, while the word 'masterpiece' appears only in the reviews that are strongly positive. Using the rule that words spread across nearly every document carry less weight, predict which word tf-idf will weight more heavily, and explain why it may not be the same as the word that best matches the labels.

Hints
  • Ask how spread out each word is across the whole collection.
  • Remember that tf-idf never sees the labels when it computes weights.

Key Takeaways

  • Plain word counts give every word the same kind of influence, while tf-idf rescales counts so that words concentrated in fewer documents carry more weight than words spread across nearly every document.
  • The source reports that tf-idf improved model performance over plain counts, as shown by a higher cross-validation score, which is evidence of performance rather than proof of meaning.
  • tf-idf is purely unsupervised: it is fit on the text alone, so its most important words describe distinctiveness across documents and may not match the class labels.
  • To inspect tf-idf results, extract the TfidfVectorizer from the fitted pipeline and examine the features it produced, using the column-to-word mapping of the document-term matrix.

Related concepts

More concepts starting with W