Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 9 of 10

Mini Project: End-to-End Iris & Penguin Multi-Class Classifier

Synthesize all Module 1 foundational concepts into a complete, leak-free, production-structured machine learning application. We ingest real-world botanical morphology measurements, implement stratified train-test partitioning, construct an atomic preprocessing and classification Pipeline, evaluate performance using cross-validation and confusion matrices, and export model artifacts ready for downstream inference serving.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete Production-Grade Classifier Implementation

Complete Production-Grade Classifier Implementation
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

# 1. DATA INGESTION & EXPLORATION
raw = load_iris(as_frame=True)
df = raw.frame
X = df[raw.feature_names]
y = df['target']
target_names = raw.target_names

print(f"Dataset Shape: {X.shape} | Classes: {target_names.tolist()}")
print(f"Class Balance:\n{y.value_counts()}")

# 2. STRATIFIED TRAIN-TEST PARTITIONING (Preserves class proportions)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

# 3. ATOMIC PIPELINE FORMULATION
# Candidate 1: Standardized Multinomial Logistic Regression
lr_pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression(C=1.0, max_iter=200, random_state=42))
])

# Candidate 2: Non-Linear Random Forest Classifier
rf_pipeline = Pipeline([
    ('clf', RandomForestClassifier(n_estimators=100, max_depth=4, random_state=42))
])

# 4. ROBUST STRATIFIED 5-FOLD CROSS-VALIDATION
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

for name, model in [("Logistic Regression", lr_pipeline), ("Random Forest", rf_pipeline)]:
    cv_scores = cross_val_score(model, X_train, y_train, cv=cv, scoring='accuracy')
    print(f"[{name}] 5-Fold CV Accuracy: {cv_scores.mean():.4f} (± {cv_scores.std():.4f})")

# 5. FINAL RETRAINING & EVALUATION ON HELD-OUT TEST DATA
lr_pipeline.fit(X_train, y_train)
y_pred = lr_pipeline.predict(X_test)

print("\n--- HELD-OUT TEST PERFORMANCE REPORT ---")
print(classification_report(y_test, y_pred, target_names=target_names))
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))

# 6. INFERENCE ON UNSEEN LIVE DATA
new_sample = pd.DataFrame([[5.1, 3.5, 1.4, 0.2]], columns=raw.feature_names)
predicted_class = target_names[lr_pipeline.predict(new_sample)[0]]
confidence = np.max(lr_pipeline.predict_proba(new_sample)) * 100
print(f"\nLive Sample Prediction: '{predicted_class}' ({confidence:.1f}% confidence)")

Pro Tip: Baseline Comparison Rule

Never present model results without comparing against a naive baseline (such as `DummyClassifier(strategy='most_frequent')`). If your sophisticated neural network achieves 88% accuracy on a dataset where the majority class is 87%, your model has learned almost nothing beyond the prior distribution.

Diagram
Loading diagram…

MlIrisClassifierProject Visual Representation

Hands-On Challenge: Export & Re-Load Model Artifacts

Use Python's `joblib` library to serialize the fitted `lr_pipeline` object to disk (`iris_classifier_v1.joblib`). Write a separate inference script that loads the file and makes predictions without needing access to the training dataset.

Quick Quiz & Key Concept Checks

Common Pitfall: Evaluating Only on Training Data

A model that achieves 100% training accuracy but 50% test accuracy is memorizing noise rather than learning invariant patterns. Always report test metrics from an untouched, held-out evaluation set.

Topics in This Module

0/10 done