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
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      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
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      • 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

      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.

      Chaand Sheikh

      ·27 November 2026Text and NLP

      What you will learn

      • Split raw text before any vectorizer learns from it
      • Put TfidfVectorizer and a model in one Pipeline
      • Compare MultinomialNB and LinearSVC with the F1 score and a confusion matrix
      • Predict the sentiment of brand-new raw reviews

      Before you start

      • TF-IDF with TfidfVectorizer
      • Train-Test Split and Data Leakage
      • Precision, Recall and F1 Score

      Think of an email spam filter. You've already marked three emails: "Win a free prize" is spam, "Lunch tomorrow" goes to the inbox, "Free winner, click here" is spam. From these the filter learns which words point where: free and win point to spam, lunch points to the inbox.

      Now a brand-new email arrives: "Claim your free gift". The filter never saw this exact email, but it knows the words, so it says spam. Labelled text in, a word-based rule out.

      Our movie reviews work the same way, with positive or negative instead of spam or inbox. We already know how to turn words into numbers with bag of words and TF-IDF. Now we train a model on them and check it on reviews it has never seen.

      Glue the reviews, then split first

      import pandas as pd
      import matplotlib.pyplot as plt
      from sklearn.model_selection import train_test_split
      from sklearn.pipeline import Pipeline
      from sklearn.feature_extraction.text import TfidfVectorizer
      from sklearn.naive_bayes import MultinomialNB
      from sklearn.svm import LinearSVC
      from sklearn.metrics import f1_score, ConfusionMatrixDisplay
      
      sents = pd.read_csv("movie_review.csv")
      reviews = (sents.groupby(["cv_tag", "tag"])["text"]
                 .apply(" ".join).reset_index())
      X = reviews["text"]
      y = (reviews["tag"] == "pos").astype(int)  # 1 = pos
      print(len(X), "reviews,", y.sum(), "positive")
      2000 reviews, 1000 positive

      The file has one sentence per row, so we glue the sentences back into 2,000 full reviews. X is the text, and y is 1 when the review is positive.

      Then the split, before anything learns from the text. stratify=y keeps half positive and half negative in both parts:

      X_train, X_test, y_train, y_test = train_test_split(
          X, y, test_size=0.2, stratify=y, random_state=42)
      print(X_train.shape, X_test.shape)
      (1600,) (400,)

      1,600 reviews to learn from and 400 to test. Notice that X is still raw text. No vectorizer has seen it yet.

      One fit, then only predict

      The vectorizer learns from text: its vocabulary and how rare each word is. If it ever sees the test reviews during learning, they leak into the model, exactly like a scaler fitted on all rows in Train-Test Split and Data Leakage. A Pipeline fixes this by tying the vectorizer and the model into one object:

      What a text Pipeline does in fit and in predict pipe.fit(X_train, y_train) X_train1,600 reviews TfidfVectorizerlearns 36,352 words modellearns its weights pipe.predict(X_test) X_test400 reviews only transformssame 36,352 columns only predicts1 = pos, 0 = neg the words and the weights come from the train reviews only
      During fit, the vectorizer and then the model learn from X_train. During predict, the test reviews ride the same road, but nothing learns from them.

      Two contestants, one shape

      models = {
          "MultinomialNB": Pipeline([
              ("tfidf", TfidfVectorizer()),
              ("clf", MultinomialNB())]),
          "LinearSVC": Pipeline([
              ("tfidf", TfidfVectorizer()),
              ("clf", LinearSVC(random_state=42))]),
      }

      Both pipelines start with a TfidfVectorizer that turns the words into weighted numbers. They differ only in the last step:

      • MultinomialNB is naive Bayes on word weights. Fast, simple, and a classic for text.
      • LinearSVC is a linear support vector machine. It looks for the widest gap between the positive and the negative reviews.

      Fit and score each pipeline

      for name, pipe in models.items():
          pipe.fit(X_train, y_train)
          pred = pipe.predict(X_test)
          print(name, "F1:", round(f1_score(y_test, pred), 3))
      MultinomialNB F1: 0.801
      LinearSVC F1: 0.857

      pipe.fit on X_train: the vectorizer learns the words and the model learns its weights. pipe.predict on X_test: the vectorizer only transforms and the model only predicts. Then we print the F1 score.

      Both are good, and LinearSVC wins, 0.857 against 0.801. And there's no manual fit_transform anywhere. The pipeline handles the train and the test text the right way.

      Where does LinearSVC go wrong?

      F1 is one number. A confusion matrix shows where the mistakes are:

      best = models["LinearSVC"]
      disp = ConfusionMatrixDisplay.from_estimator(
          best, X_test, y_test,
          display_labels=["neg", "pos"], cmap="Blues")
      print(disp.confusion_matrix)
      plt.show()
      [[160  40]
       [ 20 180]]
      Confusion matrix of the LinearSVC pipeline on 400 test reviews: 160 negative reviews predicted negative, 40 negative predicted positive, 20 positive predicted negative, 180 positive predicted positive.
      The LinearSVC pipeline on the 400 test reviews. Rows are the true label, columns the prediction.

      160 negative reviews were called negative and 180 positive reviews were called positive, so 340 of 400 are right. The most common mistake is the top-right cell: 40 negative reviews called positive. The other way round it's 20. A sarcastic "great, just great" is hard for words alone.

      What did the vectorizer learn?

      Let's look inside the fitted pipeline and check that nothing leaked:

      tfidf = best["tfidf"]
      n_words = len(tfidf.vocabulary_)
      print(n_words, "words learned from X_train")
      print(tfidf.transform(X_test).shape)
      36352 words learned from X_train
      (400, 36352)

      best["tfidf"] is the fitted vectorizer inside the pipeline. It learned 36,352 words from the 1,600 training reviews only. The 400 test reviews get the very same columns. A word that appears only in a test review gets no column; it's simply ignored. So the test reviews taught the vectorizer nothing.

      (In the TF-IDF article the vectorizer saw all 2,000 reviews and English stop words were dropped, which gave 39,354 columns. Here it sees fewer reviews and keeps every word, so the number is different.)

      Raw text in, label out

      And now the fun part, reviews the model has never seen:

      new = ["a wonderful, moving film with a brilliant cast",
             "a dull, boring mess and a waste of time"]
      print(best.predict(new))
      [1 0]

      1 means positive, for wonderful, moving and brilliant. 0 means negative, for dull, boring and waste. We passed raw text: the pipeline cleans, counts, weighs and predicts in one call.

      Common mistakes

      • Vectorizing before the split. Fitting TfidfVectorizer on all 2,000 reviews lets the test text shape the vocabulary and the idf values. Split first, then fit inside a Pipeline.
      • Calling fit_transform on the test text. That builds a new vocabulary with different columns. The test set is only ever transformed.
      • Judging by one number. F1 hides which way the model errs. The confusion matrix showed twice as many negatives called positive as the other way round.

      Recap

      StepCodeResult here
      Split firsttrain_test_split(..., stratify=y)1,600 train, 400 test
      One PipelinePipeline([("tfidf", ...), ("clf", ...)])vectorizer fits on train only
      Compare modelsf1_scoreMultinomialNB 0.801, LinearSVC 0.857
      Find the errorsConfusionMatrixDisplay.from_estimator340 of 400 right, 40 neg called pos
      Use itbest.predict(raw_text)[1 0]

      Try it yourself

      Add ngram_range=(1, 2) to the TfidfVectorizer of both pipelines, so word pairs like "not good" become features too. Does F1 go up or down? 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
      TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
      Next →
      Why Neural Networks: Pixels, One Neuron and Layers
      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.

      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.

      On this page
      • Glue the reviews, then split first
      • One fit, then only predict
      • Two contestants, one shape
      • Fit and score each pipeline
      • Where does LinearSVC go wrong?
      • What did the vectorizer learn?
      • Raw text in, label out
      • 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.