Lesson 8 of 10 · 3 min
Practical Exercise — Multiclass Classification (Iris Dataset)
Dataset: Iris — 150 flowers, 4 measurements, 3 species
Task: Build a classifier that identifies the species from measurements
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score, classification_report,
confusion_matrix, ConfusionMatrixDisplay,
roc_auc_score
)
# ---- 1. Load Data ----
iris = load_iris()
X = iris.data # 4 features: sepal/petal length & width
y = iris.target # 0=setosa, 1=versicolor, 2=virginica
class_names = iris.target_names # ['setosa', 'versicolor', 'virginica']
print("Dataset shape:", X.shape) # (150, 4)
print("Classes:", class_names) # ['setosa' 'versicolor' 'virginica']
print("Samples per class:", np.bincount(y)) # [50 50 50] — balanced!
# ---- 2. Split ----
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
) # stratify=y ensures each class keeps its proportion in train/test
# ---- 3. Scale ----
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # fit on train only
X_test = scaler.transform(X_test) # apply same transform to test
# ---- 4. Train ----
model = LogisticRegression(max_iter=200, random_state=42)
model.fit(X_train, y_train)
# ---- 5. Predict ----
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test) # shape: (30, 3) — probability for each class
# ---- 6. Accuracy ----
acc = accuracy_score(y_test, y_pred)
print(f"\nTest Accuracy: {acc:.4f}") # Output: Test Accuracy: 0.9667
# ---- 7. Classification Report ----
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=class_names))
# Output:
# precision recall f1-score support
# setosa 1.00 1.00 1.00 10
# versicolor 0.91 1.00 0.95 10
# virginica 1.00 0.90 0.95 10
# accuracy 0.97 30
# ---- 8. Confusion Matrix ----
cm = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:")
print(cm)
# Output:
# [[10 0 0]
# [ 0 10 0]
# [ 0 1 9]]
# 1 virginica was misclassified as versicolor
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=class_names)
disp.plot(cmap='Blues')
plt.title('Iris — Multiclass Confusion Matrix')
plt.tight_layout()
plt.show()
# ---- 9. AUC for multiclass (one-vs-rest) ----
auc = roc_auc_score(y_test, y_prob, multi_class='ovr', average='macro')
print(f"\nMulticlass AUC (OvR, macro): {auc:.4f}")
# Output: Multiclass AUC (OvR, macro): 0.9983Reading the Output
| Cell in CM | Meaning |
|---|---|
| cm[0][0] = 10 | All 10 setosa predicted correctly |
| cm[1][1] = 10 | All 10 versicolor predicted correctly |
| cm[2][2] = 9 | 9 virginica predicted correctly |
| cm[2][1] = 1 | 1 virginica was wrongly predicted as versicolor |
Why does virginica get confused with versicolor? Their petal measurements overlap slightly — setosa is clearly different from both.
