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

      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.

      Chaand Sheikh

      ·27 November 2026Text and NLP

      What you will learn

      • Explain term frequency (TF) and inverse document frequency (IDF)
      • Compute one review's TF-IDF by hand and match scikit-learn
      • Read the idf_ values and the row-length scaling of TfidfVectorizer
      • Compare the top words by counts and by TF-IDF on real reviews

      Before you start

      • Bag of Words with CountVectorizer
      • Basic pandas

      Imagine a pile of restaurant reviews on your desk:

      • Review 0: The food was great
      • Review 1: The food was cold
      • Review 2: Great food, friendly staff
      • Review 3: The food was mouldy

      Every single review says food. When you read that word, you learn nothing new. But only one review says mouldy. That word is rare, and it tells you a lot. You'd remember that restaurant, and you'd probably never go back.

      A word that is everywhere should whisper, and a rare word should shout. That's the whole idea of TF-IDF.

      Plain counts treat every word the same

      In Bag of Words with CountVectorizer we turned text into word counts. Let's do that for the four reviews:

      import numpy as np
      import pandas as pd
      from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
      
      reviews = ["The food was great", "The food was cold",
                 "Great food, friendly staff",
                 "The food was mouldy"]
      
      cv = CountVectorizer()
      counts = cv.fit_transform(reviews)
      terms = cv.get_feature_names_out()
      pd.DataFrame(counts.toarray(), columns=terms)
         cold  food  friendly  great  mouldy  staff  the  was
      0     0     1         0      1       0      0    1    1
      1     1     1         0      0       0      0    1    1
      2     0     1         1      1       0      1    0    0
      3     0     1         0      0       1      0    1    1

      This count has a name: TF, the term frequency, how often a word appears in this review. Look at the food column: a 1 in every row. And mouldy is also just a 1. The counts can't tell us which word matters.

      IDF: the rarer the word, the bigger the number

      So we need a second number, the IDF, the inverse document frequency. For every word we check how many reviews hold it. scikit-learn uses this formula (the default, smoothed version):

      idf = ln( (1 + n) / (1 + df) ) + 1

      Here n is the number of reviews (4) and df is how many of them contain the word. A TfidfVectorizer counts the words and also learns the idf of each one, in its idf_ attribute:

      tfidf = TfidfVectorizer()
      X = tfidf.fit_transform(reviews)
      terms = tfidf.get_feature_names_out()
      for word, value in zip(terms, tfidf.idf_):
          print(word, f"{value:.3f}")
      cold 1.916
      food 1.000
      friendly 1.916
      great 1.511
      mouldy 1.916
      staff 1.916
      the 1.223
      was 1.223

      food is in all four reviews, so it gets the smallest value, 1.000. the and was are in three reviews and get 1.223. great is in two and gets 1.511. mouldy, cold, friendly and staff are each in just one review, so they get the biggest value, 1.916.

      idf of each word in the four restaurant reviews word (reviews that contain it) food (4)1.000 the (3)1.223 was (3)1.223 great (2)1.511 mouldy (1)1.916 cold, friendly, staff (1)1.916
      The idf values printed by the notebook. The fewer reviews a word appears in, the longer its bar. food is everywhere and gets the minimum, 1.000.

      Review 3 by hand: TF x IDF, then scale

      Let's see what happens inside for review 3, "The food was mouldy". Each of its four words appears once, so the TF is 1 for all of them. First, multiply TF by IDF. Then measure the length of the row: the square root of the sum of squares.

      raw = counts[3].toarray()[0] * tfidf.idf_
      for word, value in zip(terms, raw):
          if value > 0:
              print(word, f"{value:.3f}")
      print("length", f"{np.linalg.norm(raw):.2f}")
      food 1.000
      mouldy 1.916
      the 1.223
      was 1.223
      length 2.77

      The length is 2.77. Last, divide every value by it, so the whole row ends up with length 1:

      TF x IDF, then divide by the row length wordTFTF x IDF÷ 2.77 foodthewasmouldy 1111 1.0001.2231.2231.916 0.360.440.440.69 row length = √(1.000² + 1.223² + 1.223² + 1.916²) = 2.77
      Review 3, "The food was mouldy". Every word has the same count of 1, but after TF x IDF and scaling, mouldy gets 0.69 and food only 0.36.

      TfidfVectorizer does it all in one go

      The X we got from fit_transform already holds these scaled values for every review:

      pd.DataFrame(X.toarray(), columns=terms).round(2)
         cold  food  friendly  great  mouldy  staff   the   was
      0  0.00  0.40      0.00   0.60    0.00   0.00  0.49  0.49
      1  0.69  0.36      0.00   0.00    0.00   0.00  0.44  0.44
      2  0.00  0.31      0.59   0.46    0.00   0.59  0.00  0.00
      3  0.00  0.36      0.00   0.00    0.69   0.00  0.44  0.44

      Row 3 matches our hand calculation: mouldy 0.69, food 0.36. In row 1 the rare word cold wins with 0.69. And every row has length 1, so long and short reviews can be compared fairly.

      The same idea on 2,000 movie reviews

      Now the real data. We glue the sentences back into reviews and fit a CountVectorizer and a TfidfVectorizer, both with English stop words:

      sents = pd.read_csv("movie_review.csv")
      grouped = sents.groupby(["cv_tag", "tag"])["text"]
      movies = grouped.apply(" ".join).reset_index()
      cv = CountVectorizer(stop_words="english")
      tv = TfidfVectorizer(stop_words="english")
      C = cv.fit_transform(movies["text"])
      T = tv.fit_transform(movies["text"])
      print(C.shape, T.shape)
      (2000, 39354) (2000, 39354)

      Same vocabulary, same shape: 2,000 rows and 39,354 columns. Only the numbers inside differ. Let's compare the top five words of review 0 under each:

      def top5(s):
          s = s.sort_values(ascending=False)
          return list(s.index[:5])
      
      words = cv.get_feature_names_out()
      counts0 = pd.Series(C[0].toarray()[0], index=words)
      weights0 = pd.Series(T[0].toarray()[0], index=words)
      print("counts:", *top5(counts0))
      print("tf-idf:", *top5(weights0))
      counts: 10 film movie make pretty
      tf-idf: 10 teen sagemiller memento strangeness

      film and movie fill every movie review, so they tell us very little about this one. teen, sagemiller, memento and strangeness tell us what this review is really about. Common words fade, and rare words speak. That's why TF-IDF is a strong, fast first try for search, spam filters and review classifiers.

      Here the vectorizers are fitted on all 2,000 reviews only to look at the words. The idf values are learned from the data, so when you train a model, fit the vectorizer on the training reviews only. A Pipeline does that for you, as shown in Build a Text Classifier with TF-IDF and a Pipeline.

      Common mistakes

      • Expecting a different vocabulary. TF-IDF changes the numbers, not the columns. With the same settings, CountVectorizer and TfidfVectorizer give the same shape.
      • Forgetting the row scaling. TF x IDF alone gives 1.916 for mouldy; the table shows 0.69 because each row is divided by its length.
      • Fitting on the test text. idf counts how many documents hold each word, so test reviews would leak into it. Fit on train, transform the test.

      Recap

      PieceMeaningReview 3 example
      TFHow often the word appears in this review1 for every word
      IDFHow rare the word is across all the reviewsfood 1.000, mouldy 1.916
      TF x IDFMultiply the twomouldy 1.916
      ScaleDivide the row by its length so it has length 11.916 / 2.77 = 0.69
      TfidfVectorizerAll of the above in one linerow 3: mouldy 0.69, food 0.36

      Try it yourself

      Add a fifth review, "The food was mouldy and cold", to reviews and fit the TfidfVectorizer again. Which word gets the biggest TF-IDF in it? The notebook and the dataset are in the community, free to join.

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

      Join free on Skool →
      ← Previous
      Bag of Words with CountVectorizer: Turn Text into Word Counts
      Next →
      Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
      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
      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.

      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
      • Plain counts treat every word the same
      • IDF: the rarer the word, the bigger the number
      • Review 3 by hand: TF x IDF, then scale
      • TfidfVectorizer does it all in one go
      • The same idea on 2,000 movie reviews
      • 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.