Natural Language Processing · Intermediate level

Intermediate level · Module 2: Feature Extraction and TF-IDF · Lesson 1 of 3

N-grams and Vocabulary Control

Learners add word pairs (bigrams) to capture short phrases such as 'not paid' and control vocabulary size with min_df, max_df and max_features.

In this lesson you will

  • Create n-gram features
  • Control vocabulary size and noise

Key concepts

unigram and bigramngram_rangemin_dfmax_dfmax_features

The lesson

Single words lose phrases. Bigrams (pairs of adjacent words) keep some order: 'not paid', 'exam timetable', 'school fees'. CountVectorizer(ngram_range=(1, 2)) creates both single words and pairs.

N-grams make the vocabulary grow quickly. min_df=2 drops terms that appear in fewer than two documents (often typos); max_df=0.9 drops terms in more than 90% of documents (too common to help); max_features keeps only the most frequent terms.

Check the vocabulary after each change: print its size and a sample of terms. A vocabulary full of typos and numbers is a sign that preprocessing needs work.

Step by step

  1. Fit CountVectorizer with unigrams, then with unigrams and bigrams, and compare vocabulary sizes.
  2. Apply min_df=2 and max_df=0.9 and compare again.
  3. Print 30 random bigrams and judge their usefulness.
  4. Record the settings you choose for the project.

Practice activity

Compare four vectoriser settings on the project corpus and choose one with justification.

Expected result: A table of vocabulary sizes and a justified choice of settings.

Check your understanding

  1. Why add bigrams?

    Show answer

    To keep short phrases such as 'not paid' that single words lose.

  2. What does min_df=2 remove?

    Show answer

    Terms that appear in fewer than two documents.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.