Concepts / Text Features with CountVectorizer

Text Features with CountVectorizer

Removing stopwords reduced the dataset from 27,271 features to 26,966, so 305 features were removed, which is a small fraction of the total.

  • Programming
Interactive lab

Try it: Text Vectorization: Tokens to Vectors

The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.

How it works

  1. Standardize: lowercase and delete punctuation.
  2. Split on whitespace into tokens.
  3. Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
  4. Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
  5. Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.

Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.

Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.

Educational simulation

Loading the simulation…

Predicting the Feature Count Before Running the Experiment

A common habit in text modeling is to delete words that carry little meaning before a model sees the text. Articles, pronouns, and short connectors such as these appear in almost every document, and they often say little about what a document is actually about. The expectation is that a cleaner set of features will help the model. This article asks a practical question: does that expectation hold up when you measure it on a real model?

What do you think happens?

A text dataset starts with 27,271 features. A stopwords list is removed, and the dataset is left with fewer features. How many features remain?

  • About 27,000 features

  • About 26,966 features

  • About 20,000 features

  • About 5,000 features

Reveal answer
Answer:

26,966 features remain.

Removing the stopwords reduced the dataset from 27,271 features to 26,966, so 305 features were removed. Notice how the count of removed features is small compared with the total.

What a Feature Is in a Text Dataset

A feature, in this setting, is one column of the data the model learns from. In a text dataset, each column usually corresponds to a word or word-like token. The set of columns is the vocabulary the model can see. When you tell the pipeline to remove a stopwords list, it deletes only the columns whose words match that list. Every other column stays exactly as it was.

Think of the feature set as a table with one column per word. A dataset with 27,271 features has 27,271 such columns. Removing stopwords does not shorten the documents or change how often the remaining words occur. It only removes the columns that correspond to words on the list. Columns for words not on the list are untouched.

Tracing the Text Through the Pipeline

Before looking at numbers, trace the path a document takes. Raw documents are split into tokens. Each token is then checked against the filter you chose, either a stopwords list or a frequency rule such as max_df. The tokens that pass the filter become the columns of the document-term matrix, and the model learns from that matrix. Each stage is a checkpoint where the outcome can be compared with your expectation.

Raw documentsTokensStopwords or max_dffilterFeature columnsone column per remainingwordDocument-term matrixModelsplitcheck each tokentokens that passcolumnslearns from
In what order do raw documents become tokens, get filtered by a stopwords list or max_df, and end up as columns in the document-term matrix the model uses?

Measuring the Feature Count After Stopword Removal

27,271 features26,966 features305 features removedstopwords removeddifference
What does the feature set look like before and after the stopwords list is applied, and why is a removal of 305 features from 27,271 a small fraction?
Worked example

How large is the reduction?

The feature count went from 27,271 to 26,966. How many features were removed, and what fraction of the original set does that represent?

  1. 1
    Find the starting count

    The dataset began with 27,271 features.

  2. 2
    Find the remaining count

    After the stopwords list was removed, 26,966 features remained.

  3. 3
    Compute the difference

    27,271 minus 26,966 gives 305 features removed. The starting count, the remaining count, and the difference play three separate roles, so keep them distinct.

  4. 4
    Express as a fraction

    The removed share is $\frac{305}{27271}$, which is about 0.011, or roughly 1.1 percent of the original features.

Result

305 features were removed, about 1.1 percent of the original 27,271. The source describes this as a small fraction of the total.

The source notes that the stopwords list covered most, but not all, of its words in this dataset. Some words on the list did not occur in the data at all, so they could not remove any features. The 305 removed features are therefore the words from the list that did appear, and the reduction reflects only those.

Feature Count Versus Model Score

The experiment uses a logistic regression model tuned with grid search. Grid search tries a set of candidate parameter values, scores each one with cross-validation, and reports the best score it found. The script reports one number, the best cross-validation score, and that number is only part of the story. You should first check what changed in the data itself, because the score is only meaningful once you know how the feature set moved.

27,271 featuresbeforeBest CV score 0.8826,966 features afterstopwords removedgrid search refit
How do the change in the number of features and the change in the cross-validated score differ as two separate measurements, and which step affects each one?

The feature count is a property of the data. The cross-validated score is a property of the trained model's measured performance. The stopwords step affects the first directly and affects the second only indirectly, through the model that is refit on the smaller feature set. Because they are two different measurements, a small change in one does not automatically explain the other. This is why the three checkpoints must be checked in order.

Reading a Small Drop in the Cross-Validated Score

After the feature set shrank, grid search was run again and reported a best cross-validation score of 0.88. The source describes this as a slight decrease in performance. The source does not report the earlier score as a precise value, so the size of the change is best described qualitatively: the score went down a little, not dramatically.

The source gives two separate reasons the result did not justify keeping the list. First, a drop that small was judged not enough to worry about. Second, removing 305 features from more than 27,000 was unlikely to change either performance or interpretability much. When a change is small in performance and also small in the size of the feature set, the cost of maintaining the list can outweigh the benefit.

When a Fixed Stopwords List Is Worth Using

The source notes that fixed lists are mostly helpful for small datasets. A small dataset may not contain enough information for the model to work out which words are stopwords from the data itself. With a large dataset, the frequency patterns in the data can do much of that work. In this experiment the dataset was large, which is part of why the fixed list added little.

Letting the Data Choose with max_df

Instead of naming the words to remove in advance, you can let the data decide which words are too common. The max_df option of CountVectorizer discards words that appear frequently in the dataset. Because the threshold comes from the data, it does not depend on whether a word happens to be on someone's list.

python
Notes on the code
  • max_df sets the frequency threshold for dropping common words
  • The value 0.5 is only an illustrative setting chosen for this article
Full vocabularyVocabulary aftermax_dfFrequent wordsdroppedapply max_dfremoved by frequency
When max_df is set, which words are dropped, and how does the vocabulary look before and after words that appear in too many documents are removed?

Mistakes When Reading Feature Counts and Scores

  • Common mistake

    Treating the feature count change as the performance change

    What it looks like

    Seeing 305 fewer features and concluding the model must have improved or worsened by a matching amount.

    Why it fails

    The feature count and the cross-validated score are different measurements. The count describes the data; the score describes the trained model's measured performance.

    Do this instead

    Record the feature count, then record the score separately, and judge each against its own expectation.

  • Common mistake

    Blaming the whole pipeline for one change

    Why it fails

    A result can appear to come from everywhere when only one step produced the change.

    Do this instead

    Check the three checkpoints in order: the count before removal, the count after removal, and the score after refit.

  • Common mistake

    Assuming every word on the stopwords list was present

    What it looks like

    Expecting the list to remove as many features as it has entries.

    Why it fails

    The source notes that some words on the list did not occur in this data, so they removed nothing.

    Do this instead

    Compare the removed count with the list's words that actually appear in the data.

  • Common mistake

    Reading a small score drop as proof either way

    Why it fails

    A small drop was judged not enough to worry about, but whether it justifies keeping or dropping a list depends on the feature change and the cost of maintaining the list.

    Do this instead

    Weigh the score change together with the size of the feature reduction and the trade-off.

Practice Tracing a Feature Count

EASY

A text dataset starts with 27,271 features. After a stopwords list is removed, the count is 26,966. Before checking the model score, state how many features were removed, then explain why a best cross-validation score of 0.88 cannot by itself tell you how many features changed.

Hints
  • Subtract the remaining count from the starting count.
  • Think about which of the two measurements the feature count describes and which one the score describes.

Key Takeaways

  • Removing a stopwords list deletes only the feature columns that match the list; here it reduced 27,271 features to 26,966, removing 305.
  • The feature count and the cross-validated score are separate measurements, and each must be checked against its own expectation.
  • A small drop in the best cross-validation score, 0.88 in this experiment, was judged not enough to justify keeping a fixed list when the feature reduction was also small.
  • Fixed stopwords lists are most useful for small datasets, while max_df lets the data decide which frequent words to drop.

Related concepts

More concepts starting with T