Lesson 8 of 12
Step 7: Save and Load the Model
After training, you need to save the model so you can load and use it later without retraining. This is essential for deploying AI in applications.
Save and Load with Joblib
Save and Load with Joblib
# Saving and loading the trained model
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import joblib
emails = [
("Hi Alex, the meeting is rescheduled to Thursday at 3pm.", 0),
("WIN A FREE iPhone NOW! Click here to claim your prize!", 1),
("Your bank statement is ready. Log in to view it.", 0),
("CONGRATULATIONS! You have been selected for a gift card!", 1),
("Can you send me the project report by end of day?", 0),
("Urgent! Your account will be suspended. Verify now.", 1),
("Team lunch is scheduled for Friday. Please RSVP.", 0),
("You won a lottery! Claim your prize of $500,000!", 1),
("The quarterly financial results are attached.", 0),
("Earn unlimited income working from home!", 1),
]
df = pd.DataFrame(emails, columns=["email", "label"])
vectorizer = TfidfVectorizer(stop_words="english")
X = vectorizer.fit_transform(df["email"])
model = MultinomialNB()
model.fit(X, df["label"])
# Save the model and vectorizer
joblib.dump(model, "spam_classifier.pkl")
joblib.dump(vectorizer, "spam_vectorizer.pkl")
print("Model saved to: spam_classifier.pkl")
print("Vectorizer saved to: spam_vectorizer.pkl")
print()
# Load the model (simulating a fresh start)
loaded_model = joblib.load("spam_classifier.pkl")
loaded_vectorizer = joblib.load("spam_vectorizer.pkl")
print("Model loaded successfully!")
print()
# Use the loaded model
new_email = "Congratulations! You won a free trip! Click here to claim!"
features = loaded_vectorizer.transform([new_email])
prediction = loaded_model.predict(features)[0]
probability = max(loaded_model.predict_proba(features)[0])
print(f"New email: '{new_email}'")
print(f"Prediction: {'SPAM' if prediction==1 else 'Not Spam'} ({probability*100:.0f}% confidence)")Important Rule
Warning
Always save both the model AND the vectorizer together. The vectorizer converts text to features in exactly the same way as during training. If you use a different vectorizer at inference time, the features will not match what the model was trained on, and predictions will be meaningless.
Diagram
Loading diagram…
Educational visual guide for step 7 save and load the model.
Finished this lesson?
0 of 12 in Module 11