Concepts / Stop Words and Feature Selection in Text

Stop Words and Feature Selection in Text

The min_df parameter of CountVectorizer sets the minimum number of documents a token must appear in to become a feature.

  • 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…

Every Token Becomes a Feature by Default

A CountVectorizer turns every token it finds into a feature. A realistic text collection therefore produces a very large number of features, and many of them are noise: numbers, misspellings, and rare words that only show up once. This article looks at one setting, min_df, which lets you decide how rare a token may be before it is allowed to become a feature. You will make a prediction first, then run the code, then work out the reason behind the result.

What do you think happens?

Consider three documents: 'cat sat', 'cat ran', and 'dog ran'. If min_df is set to 1, how many features does the vectorizer keep?

  • Two: cat and ran

  • Three: cat, dog, and ran

  • Four: cat, dog, ran, and sat

  • Zero, because no word appears in every document

Reveal answer
Answer:

Four: cat, dog, ran, and sat

With min_df=1, a token only needs to appear in at least one document to become a feature. Every word in this tiny corpus appears in at least one document, so nothing is dropped.

Counting Documents Instead of Occurrences

The min_df parameter of CountVectorizer sets the minimum number of documents a token must appear in to become a feature. The key word is documents. min_df does not care how often a word is used overall; it asks how widely that word is spread across the collection. A token repeated many times inside a single document still has a document count of one.

The reason for this design is that a word repeated heavily in one review is a weak sign of a general pattern. The model would only have that single document to learn from. A word that shows up across many separate documents has a better chance of being a dependable signal, and min_df measures exactly that spread.

PropertyOccurrence countDocument count (what min_df uses)
What it countsEvery appearance of the tokenThe number of distinct documents containing the token
Token 'great' repeated 5 times in one review51
Token 'cat' once in each of 2 documents22
Passes min_df=2?Not decided by this measureOnly the second token passes

Occurrences and document counts can disagree sharply. min_df uses the document count.

Worked example

Why a Repeated Word Fails min_df=2

A corpus has two documents. Document 1 is 'great great great great great'. Document 2 is 'the film was fine'. Does 'great' pass min_df=2?

  1. 1
    Count occurrences

    'great' appears five times in total, which looks like a lot.

  2. 2
    Count documents

    All five appearances are in Document 1. Document 2 does not contain 'great', so the document count is one.

  3. 3
    Compare to the threshold

    min_df=2 requires the token to appear in at least two documents. A document count of one is below that threshold.

Result

'great' is removed from the vocabulary, even though it occurs five times. The occurrence total never enters the decision.

Tracing the Vocabulary as min_df Rises

Work through the three-document corpus 'cat sat', 'cat ran', and 'dog ran' and count the documents each token appears in. 'cat' appears in documents 1 and 2, so its document count is two. 'ran' appears in documents 2 and 3, so its count is also two. 'sat' and 'dog' each appear in only one document, so their count is one. Now run the code for two settings of min_df and compare the output with your count.

python
Output (expected)
min_df=1 ['cat' 'dog' 'ran' 'sat'] (3, 4)
min_df=2 ['cat' 'ran'] (3, 2)
Notes on the code
  • min_df=m sets the document-frequency threshold for this vectorizer.
  • get_feature_names_out() lists the tokens that survived the filter.
  • X.shape gives (number of documents, number of surviving features).

The output matches the count. At min_df=1 all four tokens pass, so the matrix has four columns. At min_df=2 only 'cat' and 'ran' pass, and the matrix has two columns. The number of rows stays at three because there are still three documents. Only the columns change.

min_df=1cat, dog, ran, satmin_df=2cat, ranmin_df=3no tokensdrop dog, satdrop cat, ran
Each step up in min_df removes every token whose document count falls below the new threshold. At min_df=3 no token is in three documents, so nothing survives.

Notice the third step. Setting min_df=3 on a three-document corpus asks for a token that appears in all three documents. 'cat' and 'ran' each reach only two, so no token passes. You can derive this result by hand from the document counts alone, without running anything.

Why Single-Document Tokens Rarely Help

A token found in only one document is unlikely to help a model, for two connected reasons. The first is about testing. A token that appears in only one document is unlikely to appear in the test set, so it does nothing to help when the model is evaluated. The second is about learning. The model learns only from the training documents, so a feature that exists in a single training document gives it very little to generalize from.

Put simply, a token in a single document cannot show a pattern. A pattern needs the token to co-occur with other documents, or with a class label, across several examples. With only one example, there is nothing to compare it against. min_df removes these tokens, which cuts back on the feature count without giving up much that a model could use.

token in onedocumentno second exampleno pattern acrossdocumentsmin_df removes itrarely absent fromtest set
A token present in only one training document has no second example to compare against, and it cannot appear in the test set. min_df targets exactly these tokens.

What Filtering Does and Does Not Buy

In the source's dataset, requiring at least five appearances of each token reduced the number of features to 27,271, which the source describes as about a third of the original features. The change was also one of kind: the source notes that there are clearly fewer numbers, and that some obscure words or misspellings have disappeared from the list.

Filtering did not make the model more accurate. The best cross-validation accuracy stayed at 89 percent, the same as before the filter. The source is direct about this: the model was not improved. The benefits it identifies are different. Fewer features can mean faster processing, and discarding useless features might make the model easier to interpret.

raw textdocumentsCountVectorizertokens foundmin_df filterdrops rare tokensmodelfewer columnsaccuracyunchanged in sourcesmaller matrix
min_df acts inside the vectorizer, after tokens are found and before the model sees the matrix. It changes the number of columns the model receives, and it does not change the accuracy the model reaches on this data.

min_df also has a role beyond the feature count. When transform is called on a new document, it may contain words that never appeared in the training data. CountVectorizer ignores these words, since they are not part of its dictionary, and for classification this is usually acceptable because a model cannot learn anything about a word it has never seen. Some applications, such as spam detection, may still benefit from knowing how many such out-of-vocabulary words a document contains. The source suggests adding a feature that counts them, and to make that count available during training, the vectorizer has to be set up with min_df. Without it, this feature would never become active during training.

Mistakes When Reading min_df

  • Common mistake

    Counting occurrences when reading min_df

    What it looks like

    A token repeated five times in one document is assumed to pass min_df=2.

    Why it fails

    min_df counts the documents that contain the token, not how many times it appears. That token has a document count of one.

    Do this instead

    Count how many distinct documents contain the token, then compare that number to min_df.

  • Common mistake

    Expecting the row count to change

    What it looks like

    After raising min_df, the learner expects fewer documents in the matrix.

    Why it fails

    min_df filters columns, which are features. The rows are still the documents.

    Do this instead

    Read the output shape as (documents, surviving features), and expect only the second number to change.

  • Common mistake

    Assuming filtering always improves accuracy

    What it looks like

    The feature count drops by about two-thirds, so the score is expected to rise.

    Why it fails

    In the source, accuracy stayed at 89 percent after the filter. The benefits were speed and interpretability.

    Do this instead

    Compare accuracy with and without the filter, and treat the feature reduction as a separate gain.

  • Common mistake

    Reading the vocabulary indices as stable: after a filter, the surviving tokens are renumbered, so 'ran' moves from column 2 to column 1 in the example.

Predict, Then Check the Vocabulary

MEDIUM

Use the corpus 'cat sat', 'cat ran', and 'dog ran'. Before running anything, predict the vocabulary for min_df=2 and state how many columns the matrix will have. Then run the code with min_df set to 2 and compare. Finally, change one document so that 'dog' appears in two documents, and predict which tokens survive min_df=2 before checking.

Hints
  • Count the documents, not the occurrences, for each token.
  • A token needs to appear in at least as many documents as min_df to survive.
  • After you change one document, recount only the token you modified and the tokens in that document.

Summary of min_df Behavior

  1. 1
    min_df sets the minimum number of documents a token must appear in to become a feature, and it counts documents rather than occurrences.
  2. 2
    Raising min_df removes tokens whose document count falls below the threshold, and the surviving columns are renumbered.
  3. 3
    Tokens found in only one document are unlikely to help, because they rarely appear in the test set and give the model little to generalize from.
  4. 4
    Filtering reduces the feature count, which can speed processing and aid interpretability, but in the source it did not improve accuracy, which stayed at 89 percent.

At a glance

  • min_df sets the minimum number of documents a token must appear in to become a feature, and it counts documents rather than occurrences.
  • Raising min_df removes tokens whose document count falls below the threshold, and the surviving columns are renumbered.
  • Tokens found in only one document are unlikely to help, because they rarely appear in the test set and give the model little to generalize from.
  • Filtering reduces the feature count, which can speed processing and aid interpretability, but in the source it did not improve accuracy, which stayed at 89 percent.

Related concepts

More concepts starting with S