Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Machine Learning
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. Text and NLP

      Bag of Words with CountVectorizer: Turn Text into Word Counts

      A model only does maths, so text has to become numbers first. Clean a review, count its words with CountVectorizer, read the document-term matrix, see why it is sparse, and add word pairs with n-grams. Shown on 2,000 movie reviews.

      Chaand Sheikh

      ·27 November 2026Text and NLP

      What you will learn

      • Explain why a model cannot fit on raw text
      • Clean text with lower-casing, tokenising and stop words using CountVectorizer
      • Build and read a document-term matrix and its sparse form
      • Keep a little word order with n-grams using ngram_range

      Before you start

      • Basic Python
      • Reading a CSV with pandas

      Imagine a postbox full of letters. Letter one says "great movie, great cast". Letter two says "boring movie". Letter three says "great story".

      Open letter one and count each word: great two times, movie once, cast once. Letter two has boring once and movie once. Letter three has great once and story once. Notice something? The order of the words is forgotten, as if we shook them in a bag. Every letter becomes a row of word counts, and that's a bag of words.

      That's exactly how we'll turn movie reviews into numbers a model can learn from.

      The data: 2,000 movie reviews

      The file movie_review.csv has one sentence per row. We glue the sentences back together, review by review:

      import pandas as pd
      from sklearn.feature_extraction.text import CountVectorizer
      from sklearn.linear_model import LogisticRegression
      
      sents = pd.read_csv("movie_review.csv")
      grouped = sents.groupby(["cv_tag", "tag"])["text"]
      reviews = grouped.apply(" ".join).reset_index()
      print(reviews.shape)
      print(reviews["tag"].value_counts().to_dict())
      print(reviews["text"][0][:44])
      (2000, 3)
      {'neg': 1000, 'pos': 1000}
      plot : two teen couples go to a church party

      2,000 reviews, 1,000 positive and 1,000 negative. The first one starts "plot : two teen couples".

      A model cannot read text

      What happens if we hand the text column straight to a logistic regression and call fit?

      try:
          model = LogisticRegression()
          model.fit(reviews[["text"]], reviews["tag"])
      except ValueError as err:
          print("ValueError:", str(err).split(":")[0])
      ValueError: could not convert string to float

      Boom. A model only does maths on numbers, so it can't use a sentence. We need a step that turns each review into a row of numbers first.

      Clean the text: lower-case, tokens, stop words

      Before we count, we clean. Three things happen:

      1. Lower-case everything, so "GREAT" and "great" are the same word.
      2. Tokenise: split the text into words. Each word is a token.
      3. Drop the stop words. Words like "the" and "was" are everywhere, so they tell us very little. They're the small talk of a sentence.

      CountVectorizer does all three for us. stop_words="english" asks it to drop the filler words, and build_analyzer() hands us its cleaning function so we can try it on one sentence:

      vec = CountVectorizer(stop_words="english")
      analyze = vec.build_analyzer()
      print(analyze("The movie was GREAT, really great!"))
      ['movie', 'great', 'really', 'great']

      Lower-case, split, and "the" and "was" are gone. The punctuation is gone too. What's left are the words that matter.

      The document-term matrix

      Now four tiny reviews:

      corpus = [
          "The movie was great and the acting was great",
          "The movie was boring",
          "Great story, boring ending",
          "I loved the movie",
      ]
      
      X = vec.fit_transform(corpus)
      terms = vec.get_feature_names_out()
      pd.DataFrame(X.toarray(), columns=terms)
         acting  boring  ending  great  loved  movie  story
      0       1       0       0      2      0      1      0
      1       0       1       0      0      0      1      0
      2       0       1       1      1      0      0      1
      3       0       0       0      0      1      1      0

      fit_transform does two jobs:

      • fit learns the words. Seven are left after cleaning: acting, boring, ending, great, loved, movie, story.
      • transform counts them, review by review.

      So there's one row per review, which we call a document, and one column per word, which we call a term. That's the document-term matrix. Look at row 0: great is 2, because the review says "great" twice.

      Document-term matrix of the four tiny reviews document actingboringendinggreatlovedmoviestory review 0review 1review 2review 3 1002010 0100010 0111001 0000110 term = one column per word
      One row per review (document), one column per word (term). Review 0, "The movie was great and the acting was great", gets a 2 under great. The word order is gone: only the counts are left.

      All 2,000 reviews: almost all zeros

      Now the same on every review. This time we keep every word (no stop-word list), just to see how big the matrix gets:

      texts = reviews["text"]
      X_all = CountVectorizer().fit_transform(texts)
      print(X_all.shape)
      print("stored numbers:", X_all.nnz)
      total = 2000 * X_all.shape[1]
      share = 100 * X_all.nnz / total
      print("filled:", round(share, 2), "%")
      (2000, 39659)
      stored numbers: 666842
      filled: 0.84 %

      2,000 rows and 39,659 columns, one for every different word. That's about 79 million cells, but only 666,842 of them are not zero. Fewer than one cell in a hundred holds a count, because each review uses only a tiny slice of all the words.

      So scikit-learn returns a sparse matrix. It stores just the non-zero numbers and where they sit, not the millions of zeros. Your laptop will thank you. (.toarray() turns it back into a full table, which is fine for four tiny reviews and a bad idea for 2,000.)

      This cell fits on all 2,000 reviews only to measure the matrix. When you train a model, split first and fit the vectorizer on the training reviews only, as in Train-Test Split and Data Leakage. The text classifier article does exactly that.

      N-grams: pairs of words keep a little order

      Forgetting the order has a cost. A bag of words can't tell "good" from "not good". Take two reviews:

      • "the movie was good"
      • "the movie was not good"

      Counted as single words, they look almost the same. So we also count pairs of neighbouring words: "the movie", "movie was", and so on. A run of n neighbouring words is called an n-gram, and ngram_range=(1, 2) asks for single words and pairs. Here we keep every word, so "not" stays in:

      a, b = "the movie was good", "the movie was not good"
      bi = CountVectorizer(ngram_range=(1, 2))
      counts = bi.fit_transform([a, b]).toarray()
      names = bi.get_feature_names_out()
      pd.DataFrame(counts, columns=names).T
                 0  1
      good       1  1
      movie      1  1
      movie was  1  1
      not        0  1
      not good   0  1
      the        1  1
      the movie  1  1
      was        1  1
      was good   1  0
      was not    0  1

      Ten columns, shown flipped with .T so each row is one word or pair. Look at not good: 0 for review 0 and 1 for review 1. Now the two reviews look different.

      Single words versus word pairs review 0: "the movie was good" review 1: "the movie was not good" single words goodmoviethewas goodmoviethewasnot pairs that differ was goodnot goodwas not
      Single words barely separate the two reviews. With ngram_range=(1, 2), "not good" becomes a column of its own, and only review 1 fills it.

      Pairs bring back a little of the order. The price is more columns: 10 here instead of 5 single words.

      Common mistakes

      • Passing raw text to a model. You get could not convert string to float. Vectorize first.
      • Calling .toarray() on a big matrix. 2,000 x 39,659 is fine sparse and wasteful dense. Keep it sparse; the text models in the text classifier article (MultinomialNB and LinearSVC) take the vectorizer's output directly.
      • Dropping stop words when you need n-grams like "not good". Check what your stop-word list removes before you rely on negation pairs.
      • Fitting the vectorizer before the split. The vocabulary is learned from the data, so fit it on the training text only.

      Recap

      StepWhat it doesIn code
      TokeniseLower-case and split the text into wordsbuild_analyzer()
      Stop wordsDrop the filler wordsstop_words="english"
      Bag of wordsCount each word; every review becomes a rowCountVectorizer().fit_transform()
      Sparse matrixStore only the non-zero countsX_all.nnz
      N-gramsCount word pairs to keep a little orderngram_range=(1, 2)

      Plain counts treat every word the same, though, and words like "film" fill every movie review. The next step, TF-IDF, lets the rare words count for more.

      Try it yourself

      Add a fifth review, "Boring, boring, boring", to corpus and run fit_transform again. Which column changes, and to what number? The notebook and the dataset for this lesson are in the community, free to join.

      Built this? Share your solution in the StudyEasy AI Community.

      Join free on Skool →
      ← Previous
      Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
      Next →
      TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool
      Go deeper with a course

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

      Related articles
      TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak

      Plain word counts treat every word the same. TF-IDF multiplies each count by how rare the word is, then scales each row to length 1. Worked by hand on four restaurant reviews, then on 2,000 movie reviews.

      Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC

      Train a movie-review sentiment classifier: split first, put TF-IDF and the model in one Pipeline, compare MultinomialNB (F1 0.801) with LinearSVC (F1 0.857), read the confusion matrix and predict new reviews from raw text.

      On this page
      • The data: 2,000 movie reviews
      • A model cannot read text
      • Clean the text: lower-case, tokens, stop words
      • The document-term matrix
      • All 2,000 reviews: almost all zeros
      • N-grams: pairs of words keep a little order
      • Common mistakes
      • Recap
      • Try it yourself
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool
      Go deeper with a course

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.