Iris dataset sklearn là bộ dữ liệu kinh điển để thử thuật toán phân loại đầu tiên. Bài này huấn luyện perceptron trên hai loài hoa Iris: load data → tiền xử lý → fit → đánh giá → trực quan hóa.
Mục tiêu
- Load và khám phá
sklearn.datasets.load_iris. - Giảm bài toán về phân loại nhị phân (2 loài, 2 đặc trưng).
- Huấn luyện perceptron và vẽ decision boundary.
Lý thuyết
Giới thiệu bộ Iris
Bộ gồm 150 mẫu, 4 đặc trưng số (chiều dài/rộng đài và cánh hoa), 3 loài:
- Iris-setosa (0)
- Iris-versicolor (1)
- Iris-virginica (2)
Perceptron gốc chỉ xử lý nhị phân. Chúng tôi chọn setosa vs versicolor vì hai loài này tách tuyến tính rõ trên không gian 2D (sepal length vs petal length).
Pipeline thực hành
- Chọn lớp và feature: Lọc 100 mẫu (bỏ virginica), lấy 2 cột đặc trưng.
- Chia train/test (tùy chọn): thường fit toàn bộ để minh họa; production nên dùng
train_test_split. - Huấn luyện perceptron: Class từ bài trước hoặc sklearn.
- Đánh giá: Accuracy, confusion matrix.
- Trực quan:
plot_decision_regions.
Tại sao setosa vs versicolor?
Hai loài này linearly separable trên nhiều cặp đặc trưng — perceptron hội tụ với ít epoch. Thử versicolor vs virginica sẽ thấy ranh giới không tách hoàn toàn bằng đường thẳng — bài học quan trọng về giới hạn mô hình.
Liên quan tiền xử lý
Ch.2 Iris demo thường chưa chuẩn hóa (perceptron rule không nhạy scale như gradient descent). Bài sau về Adaline và feature scaling sẽ bổ sung StandardScaler.
Code Python
Workflow hoàn chỉnh — cần class Perceptron từ bài trước hoặc dùng sklearn:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score, classification_report
# 1. Load Iris
iris = datasets.load_iris()
X = iris.data[:, [0, 2]] # sepal length, petal length
y = iris.target
# 2. Nhị phân: setosa (0) vs versicolor (1)
mask = y < 2
X, y = X[mask], y[mask]
# 3. Chia train/test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1, stratify=y
)
# 4. Huấn luyện perceptron sklearn
ppn = Perceptron(max_iter=40, eta0=0.1, random_state=1)
ppn.fit(X_train, y_train)
# 5. Đánh giá
y_pred = ppn.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=["setosa", "versicolor"]))
# 6. Decision boundary (2D)
from matplotlib.colors import ListedColormap
def plot_decision_regions(X, y, classifier, resolution=0.02):
markers, colors = ("o", "x", "s"), ("red", "blue", "lightgreen")
cmap = ListedColormap(colors[: len(np.unique(y))])
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(
np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution),
)
Z = classifier.predict(np.c_[xx1.ravel(), xx2.ravel()])
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
for idx, cl in enumerate(np.unique(y)):
plt.scatter(
X[y == cl, 0], X[y == cl, 1],
alpha=0.8, c=colors[idx], marker=markers[idx], label=iris.target_names[cl],
)
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[2])
plt.legend(loc="upper left")
plt.tight_layout()
plt.show()
plot_decision_regions(X_train, y_train, ppn)
Thử đổi feature sang (1, 3) (sepal width, petal width) và so sánh accuracy.
Lỗi thường gặp
- Quên lọc 3 lớp: Perceptron nhị phân với
ycó giá trị 2 sẽ sai — luônmaskhoặcLabelBinarizer. - Nhầm index cột:
iris.data[:, [0, 2]]không phải hai cột liên tiếp — kiểm trafeature_names. stratify=ykhi ít mẫu: Với 100 mẫu, test 30 vẫn ổn; nếu lớp cực kỳ mất cân bằng cầnstratify.- Kỳ vọng 100% trên versicolor vs virginica: Hai loài chồng lấn — accuracy ~90% là bình thường, không phải lỗi code.
Bài tập
- Thực nghiệm: Huấn luyện trên versicolor vs virginica (
y >= 1, remap nhãn). Báo cáo accuracy và nhận xét decision boundary. - Feature sweep: Thử 6 cặp đặc trưng có thể từ 4 cột. Cặp nào cho accuracy cao nhất với setosa vs versicolor?
- Cross-validation: Dùng
cross_val_score(ppn, X, y, cv=5). So sánh với accuracy một lần split.
Tóm tắt
Iris dataset sklearn giúp bạn thực hành end-to-end: load → lọc nhị phân → Perceptron.fit → metric → plot. Setosa vs versicolor minh họa hội tụ tuyến tính; thử thêm loài thứ ba cho thấy giới hạn perceptron đơn lớp.