Beginner level · Module 5: Introduction to Text Classification · Lesson 2 of 3
Training a First Text Classifier
Learners combine CountVectorizer and Multinomial Naive Bayes in a scikit-learn pipeline, train it on labelled enquiries and classify new messages.
In this lesson you will
- Train a text classification pipeline
- Classify new messages and read predicted probabilities
Key concepts
PipelineMultinomialNBtrain_test_splitpredictpredict_proba
The lesson
A scikit-learn pipeline chains steps: make_pipeline(CountVectorizer(), MultinomialNB()). Calling fit(texts, labels) learns the vocabulary and the model together; predict(new_texts) applies both.
Multinomial Naive Bayes learns how often each word appears in each category and combines this evidence to choose the most likely category. It trains in seconds and works well with small datasets, which makes it ideal for a first classifier.
Split the data before training with train_test_split(..., test_size=0.25, stratify=labels, random_state=42), so that the model is tested on messages it has never seen. predict_proba shows how confident the model is, which helps decide when a person should check.
Step by step
- Split the cleaned project data into training and test sets.
- Build and fit the pipeline on the training set.
- Predict the categories of five new messages and print the probabilities.
- Mark which predictions are uncertain (highest probability below 0.6).
Routing institutional enquiries with Multinomial Naive Bayes
A bag-of-words Naive Bayes pipeline trained on eight synthetic messages routes new messages and shows its probabilities.
from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.pipeline import make_pipeline # Synthetic training messages (two per category)train_texts = [ "My salary has not been paid for two months", "The teacher was rude and nobody answered my call", "What time does the registration office open", "Which documents are needed to apply for the course", "Please send me a copy of my transcript", "I need a new student ID card please", "Congratulations you won a free phone click this link", "Win cash now send your PIN to claim the prize",]train_labels = ["complaint", "complaint", "enquiry", "enquiry", "request", "request", "spam", "spam"] model = make_pipeline(CountVectorizer(), MultinomialNB()) # alpha=1.0 (add-one smoothing)model.fit(train_texts, train_labels) new_messages = ["When does the registration office open", "Please send my ID card", "You won a prize, click the link"]for msg, probs in zip(new_messages, model.predict_proba(new_messages)): best = model.classes_[probs.argmax()] scores = " ".join(f"{c}={p:.2f}" for c, p in zip(model.classes_, probs)) print(f"{msg!r} -> {best} ({scores})")
Output
'When does the registration office open' -> enquiry (complaint=0.03 enquiry=0.91 request=0.02 spam=0.03)
'Please send my ID card' -> request (complaint=0.04 enquiry=0.02 request=0.92 spam=0.03)
'You won a prize, click the link' -> spam (complaint=0.03 enquiry=0.05 request=0.02 spam=0.90)How it works
CountVectorizer lowercases the text and keeps tokens of two or more characters, building a 56-word vocabulary from the training messages. 'When' is not in that vocabulary, so it is simply ignored. MultinomialNB starts from equal priors (two messages per category) and multiplies smoothed word likelihoods: 'registration', 'office', 'open' and 'does' only appeared in enquiries, so the first message scores 0.91 for enquiry. 'send', 'id', 'card' and 'please' point to request (0.92), and 'won', 'prize', 'click' and 'link' to spam (0.90). Naive Bayes probabilities are usually over-confident, and with only eight training messages this is a demonstration: a real router needs hundreds of labelled messages per category, a test set and a confusion matrix, as in the evaluation example.
Key concepts
make_pipelineCountVectorizer vocabularyadd-one smoothingpredict_probaout-of-vocabulary words are ignored
Practice activity
Train the level project's first classifier and classify ten new synthetic messages.
Expected result: A trained pipeline with predictions and probabilities for new messages, and uncertain cases flagged.
Check your understanding
-
Why split data before training?
Show answer
To test the model on messages it has never seen.
-
What can predict_proba be used for?
Show answer
To find uncertain predictions that a person should check.
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.