Lesson 11 of 12
Practice: AI App Production Checklist
Build your own text classifier from scratch using the complete pipeline.
Practice: Build Your Own Classifier
Practice: Build Your Own Classifier
# Practice: Build a news topic classifier
# Classify news headlines as technology, sports, or politics
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
# Dataset
headlines = [
("Apple releases new AI features in latest iPhone update", "tech"),
("Google announces breakthrough in quantum computing research", "tech"),
("Python becomes the most popular programming language worldwide", "tech"),
("OpenAI launches new version of ChatGPT with improved reasoning", "tech"),
("Electric vehicles overtake petrol cars in European market share", "tech"),
("Team wins championship after dramatic final match overtime", "sports"),
("Player signs record-breaking contract worth 300 million dollars", "sports"),
("Cricket world cup final draws highest TV audience in history", "sports"),
("Athlete breaks world record in hundred meter sprint finals", "sports"),
("Football club announces signing of top striker from rival team", "sports"),
("Government announces new policy on healthcare funding increases", "politics"),
("Prime minister meets world leaders at annual summit conference", "politics"),
("Election results show major shift in voter preferences nationwide", "politics"),
("Parliament debates new bill on digital privacy and data protection", "politics"),
("Trade negotiations between countries reach historic agreement", "politics"),
("New machine learning model achieves breakthrough image recognition", "tech"),
("Stadium renovation project awarded to leading construction firm", "sports"),
("Budget proposal includes tax cuts for middle income families", "politics"),
("Tech giant acquires AI startup for two billion dollars", "tech"),
("National team prepares for international tournament next month", "sports"),
]
df = pd.DataFrame(headlines, columns=["headline", "topic"])
print(f"Dataset: {len(df)} headlines")
print(f"Topics: {df['topic'].value_counts().to_dict()}")
print()
# Build the classifier
vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
X = vectorizer.fit_transform(df["headline"])
y = df["topic"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
model = LogisticRegression(max_iter=200, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred)*100:.1f}%")
print()
print(classification_report(y_test, y_pred))
# Predict new headlines
new_headlines = [
"Scientists develop new AI chip that runs faster than GPU",
"Fans celebrate as team wins trophy in penalty shootout",
"Government approves new law on renewable energy targets",
]
print("Predictions on new headlines:")
for h in new_headlines:
features = vectorizer.transform([h])
pred = model.predict(features)[0]
probs = model.predict_proba(features)[0]
conf = max(probs)
print(f" '{h[:60]}'")
print(f" -> {pred} ({conf*100:.0f}% confidence)")
print()Diagram
Loading diagram…
Educational visual guide for practice ai app production checklist.
Finished this lesson?
0 of 12 in Module 11