Concepts / CountVectorizer and Tokenization

CountVectorizer and Tokenization

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…

Why Filter Features at All

A CountVectorizer turns every token it finds into a feature. A token is a unit of text the vectorizer has split out of a document, such as a word. On a realistic text collection this produces a very large number of features. Many of them are noise: numbers, misspellings, and rare words that show up only once. The min_df setting lets you decide how rare a token may be before it is allowed to become a feature.

Work through the rest of this article in the same order you would work in front of a notebook: form a prediction first, run the code, and then work out why the result came out the way it did. The prediction step matters because the parameter is easy to misread if you only read its description.

What do you think happens?

Consider three documents: "cat sat", "cat ran", and "dog ran". If you set min_df=2, which tokens do you expect to remain in the vocabulary?

  • All four tokens: cat, dog, ran, sat

  • Only cat and ran

  • Only cat

  • No tokens at all

Reveal answer
Answer:

Only cat and ran

The token cat appears in two documents and the token ran appears in two documents, so both meet the threshold of two documents. The token dog and the token sat each appear in only one document, so they are dropped. The sections below explain why the threshold is measured this way and confirm the result with code.

Documents Versus Occurrences

Definition

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 count how many times a token is used overall. It counts how many separate documents contain the token at least once. A token repeated many times inside one document still has a document count of one. This is the core of the parameter: it asks how widely a word is spread across the collection, not how heavily it is used.

The reason for this design is that a heavily repeated word inside a single review is only weak evidence of a general pattern. A model that learns from that review would have only that one document to learn from. A word that shows up across many separate documents has a better chance of being a dependable signal.

SituationTotal occurrencesDocument countPasses min_df=2?
data appears 6 times in one document and nowhere else61No
word appears once in each of 2 documents22Yes

Total occurrences can favor the first case, but min_df only looks at document count.

Tracing the Three-Document Corpus

Follow one small corpus through the whole process. The corpus has three documents: "cat sat", "cat ran", and "dog ran". Before any filtering happens, the vectorizer lowercases the text, splits each document into tokens, and counts the tokens inside each document. Only after that does min_df decide which tokens survive as columns.

Raw textcat satLowercasetext made lowercaseSplit into tokenscat, satCount per documentone count per tokenApply min_dfdocument count checkFeature columnssurvivors only
The steps a single document passes through, from raw text to surviving feature columns, with min_df applied after per-document counting.

Before running anything, predict the vocabulary at min_df=1. Ask yourself whether any token could be dropped when the threshold is a single document. The answer is no: every token in this corpus appears in at least one document, so all four tokens cat, dog, ran, and sat should remain. Now run the code to check.

python
Output (expected)
{'cat': 0, 'dog': 1, 'ran': 2, 'sat': 3}
[[1 0 0 1]
 [1 0 1 0]
 [0 1 1 0]]
Notes on the code
  • min_df=1 means a token must appear in at least one document, so nothing is dropped.
  • vocabulary_ maps each surviving token to its column index.
  • Each row of the matrix is one document; each column is one surviving feature.
Worked example

Reading one row of the count matrix

Using the min_df=1 output, explain what the first row [1 0 0 1] means.

  1. 1
    Identify the row

    The first row belongs to the first document, "cat sat".

  2. 2
    Match columns to tokens

    Column 0 is cat, column 1 is dog, column 2 is ran, and column 3 is sat.

  3. 3
    Read the counts

    Column 0 holds 1 and column 3 holds 1, so cat and sat each appear once in this document. The zeros mean dog and ran do not appear in it.

Result

The first row records that the first document contains cat and sat, once each, and contains neither dog nor ran.

Watching the Vocabulary Shrink

Now raise the threshold to min_df=2. Each token's document count is the number of rows in which it appears. The token cat appears in the first and second documents, so its document count is two. The token ran appears in the second and third documents, so its document count is also two. The token dog appears only in the third document, and the token sat appears only in the first, so each has a document count of one and is dropped.

catcolumn 0dogcolumn 1rancolumn 2satcolumn 3
Every token gets a column index at min_df=1, because all four tokens appear in at least one document.
python
Output (expected)
{'cat': 0, 'ran': 1}
[[1 0]
 [1 1]
 [0 1]]
Notes on the code
  • The vocabulary has two entries instead of four, so the feature count dropped by two.
  • The indices were reassigned: ran moved from column 2 to column 1.
  • The matrix has three rows, one per document, and now two columns.
catcatdogranransatkeptkept
The tokens dog and sat are removed from the vocabulary, and the surviving tokens cat and ran remain as the new columns.

Compare the two matrices. Removing dog and sat deleted two columns, so the matrix shape changed from three rows by four columns to three rows by two columns. The number of rows stayed the same, because min_df never removes documents. It only removes features. Within the surviving columns, the counts are unchanged.

Why Single-Document Tokens Rarely Help

The model learns only from training documents. A token that appears in a single training document gives the model very little to generalize from. If the same token is absent from the test set, the model has no way to use it when it is evaluated. The source notes that a token appearing in only one document is unlikely to appear in the test set, so it is not helpful at evaluation time.

Dropping such tokens reduces the feature count without giving up much a model could use. This is what min_df does about them: it removes tokens whose document count falls below the threshold, so the matrix keeps only features that spread across more of the collection.

In one benchmark run, 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 surviving tokens also changed in kind, not only in number. There were clearly fewer numbers in the list, and some obscure words and misspellings had disappeared. Those are the kinds of features that often appear in only one or two documents.

Mistakes With min_df

  • Common mistake

    Thinking min_df counts how often a word is used

    What it looks like

    A word that appears six times in one document is assumed to pass min_df=2.

    Why it fails

    min_df counts the number of documents containing the token, and six occurrences inside one document still give a document count of one.

    Do this instead

    Count the documents that contain the token, then compare that number to the threshold.

  • Common mistake

    Expecting the same column index for a token after filtering

    What it looks like

    The token ran sits at column 2 when min_df=1 but column 1 when min_df=2.

    Why it fails

    Column indices are assigned to the features that survive the filter, so removing columns shifts the indices of later columns.

    Do this instead

    Read the indices from vocabulary_ after each fit instead of reusing numbers from an earlier run.

  • Common mistake

    Expecting min_df to remove documents

    What it looks like

    A row for a document with only dropped tokens is assumed to disappear from the matrix.

    Why it fails

    min_df only filters features. The number of rows in the matrix stays equal to the number of documents.

    Do this instead

    Check the row count separately if you need to know whether any document has no surviving features.

  • Common mistake

    Assuming a higher min_df is always better without comparing the feature counts before and after

Filtering Is Not an Accuracy Upgrade

It is tempting to assume that removing noisy features will improve a model. The source is direct about this. In its benchmark, the best cross-validation accuracy stayed at 89 percent, the same as before the filter. The model was not improved by min_df. The benefit lies somewhere else.

The benefits the source identifies are faster processing, because there are fewer features to handle, and a model that may be easier to interpret, because useless features have been discarded. Filtering is therefore a decision about cost and clarity, and you should check accuracy yourself rather than assume it changed.

Some applications, such as spam detection, may benefit from knowing how many out-of-vocabulary words a document contains. The source suggests adding a feature that counts them. 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.

Practice Your Prediction

MEDIUM

Corpus: "data data data data data data" (one document), "model trains" (second document), "data drives model" (third document). Before running any code, predict whether data passes min_df=2, and predict which tokens remain at min_df=2. Then run the code and compare.

Hints
  • Count the documents containing data, not its occurrences.
  • The token data appears in the first document and also in the third document.
  • Check the document count of model separately, since it appears in two documents.

Key Takeaways

  • The min_df parameter of CountVectorizer sets the minimum number of documents a token must appear in to become a feature.
  • min_df counts documents rather than occurrences, so a token repeated many times within one document still has a document count of one.
  • Tokens found in only one document are unlikely to help a model generalize, so min_df can remove them and reduce the feature count.
  • Filtering does not guarantee better accuracy. Its benefits are faster processing and possibly easier interpretation, and it should be checked against accuracy on your own data.

Related concepts

More concepts starting with C