Bài này hoàn thiện code perceptron Python theo phong cách scikit-learn estimator: fit, predict, thuộc tính w_, b_, lịch sử lỗi
Mục tiêu
- Viết class
Perceptronvới API quen thuộcfit(X, y)vàpredict(X). - Theo dõi số lỗi phân loại qua từng epoch (
errors_). - So sánh implementation tự viết với
sklearn.linear_model.Perceptron.
Lý thuyết
Quy ước API giống scikit-learn
Estimator chuẩn gồm:
__init__(self, eta, n_iter, random_state)— hyperparameter, không học dữ liệu.fit(self, X, y)— huấn luyện, gánself.w_,self.b_.predict(self, X)— dự đoán nhãn.- Thuộc tính kết thúc
_—w_,b_,errors_chỉ có saufit.
Điều này giúp object của bạn drop-in trong pipeline hoặc cross-validation sau này.
Luồng huấn luyện
Khởi tạo w, b
for epoch in 1..n_iter:
errors = 0
for (xi, yi) in training set:
if predict(xi) != yi:
w += eta * (yi - y_hat) * xi
b += eta * (yi - y_hat)
errors += 1
lưu errors
if errors == 0: break
Validation đầu vào
X:array-like, shape(n_samples, n_features).y: nhãn nhị phân{0, 1}hoặc chuyển từ{-1, +1}nếu cần.- Nên dùng
check_X_ytừsklearn.utils.validationtrong production; bài học giữ NumPy thuần cho rõ logic.
Mở rộng: net_input và activation
Tách net_input(X) và activation(z) giúp tái sử dụng khi viết Adaline — cùng skeleton, khác hàm kích hoạt và rule học.
Code Python
Implementation đầy đủ, có thể chạy độc lập:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
class Perceptron:
"""Perceptron classifier — API kiểu scikit-learn."""
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=X.shape[1])
self.b_ = np.float64(0.0)
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_ += update * xi
self.b_ += update
errors += int(update != 0.0)
self.errors_.append(errors)
if errors == 0:
break
return self
def net_input(self, X):
return np.dot(X, self.w_) + self.b_
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, 0)
def plot_decision_regions(X, y, classifier, resolution=0.02):
"""Vẽ vùng quyết định 2D."""
markers = ("s", "x", "o", "^", "v")
colors = ("red", "blue", "lightgreen", "gray", "cyan")
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.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(
x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.8,
c=colors[idx],
marker=markers[idx],
label=cl,
)
plt.xlabel("feature 1")
plt.ylabel("feature 2")
plt.legend(loc="upper left")
plt.show()
# --- Demo nhanh trên dữ liệu 2D giả lập ---
X = np.array([[2, 2], [1, 1], [3, 3], [0, 1], [4, 4], [1, 3]])
y = np.array([0, 0, 0, 1, 1, 1])
ppn = Perceptron(eta=0.1, n_iter=40, random_state=1)
ppn.fit(X, y)
print("Trọng số:", ppn.w_)
print("Bias:", ppn.b_)
print("Dự đoán:", ppn.predict(X))
print("Lỗi theo epoch:", ppn.errors_)
# So sánh sklearn
from sklearn.linear_model import Perceptron as SkPerceptron
sk_ppn = SkPerceptron(max_iter=40, eta0=0.1, random_state=1)
sk_ppn.fit(X, y)
print("sklearn predict:", sk_ppn.predict(X))
Chạy plot_decision_regions(X, y, ppn) nếu môi trường có matplotlib — bạn sẽ thấy đường biên tuyến tính tách hai cụm.
Lỗi thường gặp
- Gọi
predicttrướcfit:AttributeError: w_— luônfittrước. predict(xi)với xi 1D trong vòng lặp: Đúng cho từng mẫu; nếu truyền batch 2D cần đảm bảonet_inputxử lý cả hai shape.- Không set
random_state: Mỗi lần chạyw_khác nhau — khó reproduce demo sách. - Nhầm
n_itervới số sample:n_iterlà số epoch (lượt duyệt toàn tập), không phải số mẫu.
Bài tập
- Refactor: Thêm method
score(X, y)trả về accuracy = tỷ lệ dự đoán đúng. Kiểm tra trên tập demo. - Visualization: Vẽ biểu đồ
errors_theo epoch. Epoch nào hội tụ? - So sánh: Trên cùng
X, y, in chênh lệch trọng số giữa class tự viết vàSkPerceptron. Giải thích vì sao có thể khác dù cùng accuracy.
Tóm tắt
Code perceptron Python = class OOP với fit/predict, perceptron learning rule bên trong, và errors_ để debug hội tụ. Pattern này lặp lại cho Adaline — chỉ đổi hàm loss và cập nhật gradient.