Lesson 4 of 12
Step 3: Split Data and Train
With features ready, we split the data into training and testing sets, then train the classifier.
Why Split the Data?
We never test a model on the same data it was trained on. The test set must be completely unseen during training. This is the only honest way to know how well the model will work on new, real-world emails.
We use an 80/20 split:
- 80% training: the model learns from these
- 20% testing: we evaluate the trained model on these
Diagram
Loading diagram…
Educational visual guide for step 3 split data and train.
Train the Classifier
Train the Classifier
# Complete training pipeline
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report
# Full dataset
emails = [
("Hi Alex, the meeting is rescheduled to Thursday at 3pm. Please confirm.", 0),
("WIN A FREE iPhone NOW! Click here to claim your prize immediately!", 1),
("Your monthly bank statement is ready. Log in to view it.", 0),
("CONGRATULATIONS! You have been selected for a $1000 gift card. Act fast!", 1),
("Can you send me the project report by end of day? Thanks, Sarah.", 0),
("Urgent! Your account will be suspended. Verify your information now.", 1),
("Reminder: Your dentist appointment is tomorrow at 10am.", 0),
("Make $5000 a week from home! No experience needed. Limited spots!", 1),
("The quarterly financial results are attached for your review.", 0),
("FREE pills! Lose 20 pounds in 10 days guaranteed! Order now!", 1),
("Team lunch is scheduled for Friday. Please RSVP by Wednesday.", 0),
("You won a lottery! Claim your prize of $500,000. Reply with your details.", 1),
("Please review the updated terms of service and provide feedback.", 0),
("Hot singles in your area! Click here to meet them tonight!", 1),
("The server maintenance will occur this Sunday from 2am to 4am.", 0),
("Buy cheap medications online! No prescription needed!", 1),
("Your package has been shipped. Track it at the link below.", 0),
("FINAL NOTICE: Pay now or face legal consequences. Click here.", 1),
("Let us catch up this week. Are you free for coffee on Tuesday?", 0),
("Earn unlimited income working from home. Sign up free today!", 1),
]
df = pd.DataFrame(emails, columns=["email", "label"])
# Step 1: Convert text to features
vectorizer = CountVectorizer(lowercase=True, stop_words="english")
X = vectorizer.fit_transform(df["email"])
y = df["label"]
# Step 2: Split into train and test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"Training examples: {X_train.shape[0]}")
print(f"Testing examples: {X_test.shape[0]}")
print(f"Features (vocabulary size): {X_train.shape[1]}")
print()
# Step 3: Train the model
model = MultinomialNB()
model.fit(X_train, y_train)
print("Model trained successfully!")
print(f"Model type: {type(model).__name__}")Why Naive Bayes?
- Naive Bayes is fast: trains in milliseconds even on large text datasets
- It works well for text classification tasks like spam detection
- It handles high-dimensional features (large vocabularies) naturally
- Despite its simplicity, it often performs comparably to more complex models for text
- Easy to interpret: you can see which words it associated with spam vs not spam
- It is a great first algorithm to try for any text classification problem
Key Takeaways
- With features ready, we split the data into training and testing sets, then train the classifier.
- Naive Bayes is fast: trains in milliseconds even on large text datasets
- It works well for text classification tasks like spam detection
- It handles high-dimensional features (large vocabularies) naturally
Finished this lesson?
0 of 12 in Module 11