Concepts / Filtering Rare Words with min_df

Filtering Rare Words with min_df

A pre-defined stopwords list, such as scikit-learn's ENGLISH_STOP_WORDS with 318 entries, is a library-supplied collection of common words that text processing usually ignores.

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

Why Common Words Crowd the Features

When a computer turns a document into numbers, every distinct word it sees can become a feature. Words such as 'the', 'and', 'is', and 'of' appear in almost every English document, so they tell a model very little about what any single document is about. They still occupy a column of the feature matrix, though, and they make the representation larger.

This section looks at a practical response to that problem: a pre-defined stopwords list. You will see what such a list contains, how it is passed to CountVectorizer, and what changes in the resulting features. Before reading each explanation, try to trace the program in your head and decide what you expect each stage to produce. Then compare your expectation with what the code actually does.

Tracing a Document Through the Stopword Stage

It helps to see the stopword step as one stage in a sequence rather than as a standalone operation. Text is first split into tokens. The stopword filter then removes the tokens that appear in the list. The remaining tokens form the vocabulary, and the count matrix records how often each vocabulary item appears in each document. This is a simplified conceptual model. It is meant to show where the stopword decision sits, not to describe every internal detail.

Follow the example sentence through the diagram. It starts as one raw string. It becomes four tokens. The stopword filter then decides, token by token, which ones survive. Only the survivors can become vocabulary entries, and only the vocabulary entries get columns in the count matrix. A surprising feature count therefore has to come from one of these four stages, and the stopword filter is the stage where the list you supply makes its decisions.

What a Pre-defined Stopwords List Contains

Definition

A pre-defined stopwords list, such as scikit-learn's ENGLISH_STOP_WORDS with 318 entries, is a library-supplied collection of common words that text processing usually ignores.

The scikit-learn library provides this list in its feature extraction text module under the name ENGLISH_STOP_WORDS. The sampled entries look ordinary. They include pronouns such as 'he' and 'me', determiners such as 'the', and connecting words such as 'although' and 'into'. The sample contains no subject-specific vocabulary. The list is built around words that carry grammatical function rather than meaning about a particular topic, which is why it is a generic starting point for English text.

What do you think happens?

How many entries does scikit-learn's ENGLISH_STOP_WORDS hold?

Reveal answer
Answer:

318

The source reports that this list contains 318 stopwords. Predicting a number first is useful because it tells you whether your mental model of the list matches the library's actual contents.

Inspecting ENGLISH_STOP_WORDS in Code

You can import the list directly and ask how many entries it holds. Because the list is a set-like collection rather than an ordered sequence, convert it to a list before slicing it. The slice below takes every tenth entry, which is a quick way to sample the contents without printing all 318 words.

python
Output (expected)
318
Notes on the code
  • The import brings the built-in list in from the text feature extraction module.
  • len returns the number of entries, which the source reports as 318.
  • list(...) converts the set-like collection so it can be sliced.
  • [::10] keeps every tenth entry as a quick sample.

Passing stop_words to CountVectorizer

CountVectorizer transforms text into a matrix of token counts. It accepts a stop_words parameter. When you set that parameter to the string 'english', the vectorizer uses the built-in list. The setting is supplied when the object is created, and the vocabulary is learned when fit is called on the training text. The transform step that follows fit uses the vocabulary and stopword handling that were set up earlier.

python
Output (expected)
The printed feature names and count matrix depend on the list in your installed version. Predict which words should be missing before you run it.
Notes on the code
  • stop_words='english' is set in the constructor, before any text is seen.
  • fit_transform learns the vocabulary from the training text and returns the count matrix.
  • get_feature_names_out lists the vocabulary words that survived the filter.
Best practice

Set stop_words when you construct the vectorizer, not later. The setting is chosen at construction and used during fitting, so a vectorizer built without it will keep every word unless you build a new one.

Counting Features Before and After Filtering

A small illustration makes the effect concrete. Suppose a document contains the words 'the', 'movie', 'was', and 'fun', and the list contains 'the' and 'was'. The vectorizer would not treat 'the' and 'was' as features, so the document is represented only by the words that remain. The illustration uses invented words to show the principle. The real effect depends on the words in the list you choose.

Worked example

Counting the features that remain

A document contains the words the, movie, was, and fun. The stop list contains the and was. How many features does the document contribute, and which words are they?

  1. 1
    Start with the candidate words

    The document offers four candidate words: the, movie, was, and fun.

  2. 2
    Apply the stopword filter

    The words the and was appear in the list, so the filter drops them before the vocabulary is built.

  3. 3
    Keep the survivors

    movie and fun are not in the list, so they remain as candidates for the vocabulary.

  4. 4
    Count the features

    Two words remain, so this document contributes two features from the original four candidates.

Result

Two features remain: movie and fun. The count fell by two, and the order of the surviving words is unchanged.

Formula, step by step
  1. 1
    n_before is the number of distinct candidate features before the stopword filter is applied.
  2. 2
    n_after is the number of features that remain after the filter.
  3. 3
    Because the filter only removes candidates, n_after can equal n_before but never exceed it.
  4. 4
    The decrease is bounded by the length of the list: n_before minus n_after is at most 318 when the built-in English list is used.

Notice what changes and what does not. The dropped words are the ones that were removed. The remaining words keep their order and become the candidates for the vocabulary. The removal is applied to the words of the text, not to the documents themselves. Each document still exists, just with fewer candidate features.

Why Fewer Features Do Not Guarantee Better Models

The feature count can only shrink or stay the same when stopwords are removed. The source adds a more hopeful claim: although the count can only fall, the performance of a downstream model might improve. Whether it does is an empirical question. The source frames it as something to test by trying the change and measuring the result.

Mistakes That Produce Surprising Feature Counts

  • Common mistake

    Setting stop_words after the vectorizer already exists

    What it looks like

    Creating vec = CountVectorizer() and then expecting the stopword setting to apply to a later fit call with the same object.

    Why it fails

    The stop_words setting is supplied when the object is created and is used during fitting, so the choice belongs to the constructor.

    Do this instead

    Pass stop_words='english' in the CountVectorizer(...) call that creates the object.

  • Common mistake

    Assuming removing stopwords always improves a model

    What it looks like

    Dropping stopwords, seeing a smaller feature count, and concluding the model must be better.

    Why it fails

    Removing stopwords can only decrease the number of features. Any gain in model performance has to be measured rather than assumed.

    Do this instead

    Train the model both ways and compare the downstream results.

  • Common mistake

    Looking for the cause at the wrong stage

    What it looks like

    Rechecking the raw text when the feature count is wrong, even though the vocabulary was built from a list that does not match what you expected.

    Why it fails

    A surprising result first appears at a specific stage: the constructor, fit, transform, or the comparison you are making.

    Do this instead

    Identify the stage where the unexpected value first appears, starting with the constructor setting, then the fitted vocabulary.

  • Common mistake

    Believing the stopword filter removes words from the documents themselves rather than from the candidate tokens

Locating Where a Surprising Result Starts

MEDIUM

You set stop_words='english' when you create a CountVectorizer, but the feature count is the same as before. Using the four-stage pipeline (tokens, stopword filter, vocabulary, count matrix), name the stage where you should look first, and explain why.

Hints
  • Think about when the stop_words setting is supplied compared with when fit is called.
  • If the setting never reached the stopword filter, which stage's output would be unchanged?
  • The source says to begin with the stage that produced the result you are looking at.
EASY

Predict the feature count for the document the movie was fun when the stop list contains the and was, then check your answer against the worked example above. Explain which stage made the decision.

Hints
  • Count the candidate tokens first.
  • Decide which tokens the stopword filter drops.

Reading the Vocabulary Index Shift

Each surviving word in the vocabulary occupies one column of the count matrix. When a stopword is removed, the words after it move to new column positions, so a column number that meant one word before filtering may mean a different word afterward. This is why you should read feature names from the fitted vectorizer rather than assuming a fixed column order.

In the diagram, the two survivors take columns 0 and 1 once the list is applied, even though movie and fun sat in later positions among the original four candidates. The exact indices depend on the vocabulary the fitted vectorizer produces, so verify them with the feature names rather than trusting a hand count.

Key Takeaways

  • A pre-defined stopwords list, such as scikit-learn's ENGLISH_STOP_WORDS with 318 entries, is a library-supplied collection of common words that text processing usually ignores.
  • Passing stop_words='english' to CountVectorizer applies the built-in list during fitting, and the setting is chosen when the vectorizer is constructed.
  • Removing stopwords can only decrease the number of features, by at most the length of the list, but any gain in model performance must be measured.
  • The stopword filter sits between tokenization and vocabulary building, so a surprising feature count should be traced stage by stage, starting with the constructor setting.

Related concepts

More concepts starting with F