|
| 1 | +import numpy as np |
| 2 | +from sklearn.datasets import load_iris |
| 3 | +from sklearn.model_selection import train_test_split |
| 4 | +from utils.plot import plot_decision_regions |
| 5 | + |
| 6 | +class Perceptron(object): |
| 7 | + """ |
| 8 | + 原始形态感知机 |
| 9 | + """ |
| 10 | + |
| 11 | + def __init__(self, eta=0.01, n_iter=10): |
| 12 | + self.eta = eta #学习率 |
| 13 | + self.n_iter = n_iter |
| 14 | + |
| 15 | + def fit(self, X, y): |
| 16 | + """ |
| 17 | + 拟合函数,使用训练集来拟合模型 |
| 18 | + :param X:training sets |
| 19 | + :param y:training labels |
| 20 | + :return:self |
| 21 | + """ |
| 22 | + # X's each col represent a feature |
| 23 | + # initialization wb(weight plus bias) |
| 24 | + self.wb = np.zeros(1 + X.shape[1]) |
| 25 | + # the main process of fitting |
| 26 | + self.errors_ = [] # store the errors for each iteration |
| 27 | + for _ in range(self.n_iter): |
| 28 | + errors = 0 |
| 29 | + for xi, yi in zip(X, y): |
| 30 | + update = self.eta * (yi - self.predict(xi)) |
| 31 | + self.wb[1:] += update * xi |
| 32 | + self.wb[0] += update |
| 33 | + errors += int(update != 0.0) |
| 34 | + self.errors_.append(errors) |
| 35 | + |
| 36 | + return self |
| 37 | + |
| 38 | + def net_input(self, xi): |
| 39 | + """ |
| 40 | + 计算净输入 |
| 41 | + :param xi: |
| 42 | + :return:净输入 |
| 43 | + """ |
| 44 | + return np.dot(xi, self.wb[1:]) + self.wb[0] |
| 45 | + |
| 46 | + def predict(self, xi): |
| 47 | + """ |
| 48 | + 计算预测值 |
| 49 | + :param xi: |
| 50 | + :return:-1 or 1 |
| 51 | + """ |
| 52 | + return np.where(self.net_input(xi) <= 0.0, -1, 1) |
| 53 | + |
| 54 | + |
| 55 | +def main(): |
| 56 | + iris = load_iris() |
| 57 | + X = iris.data[:100, [0, 2]] |
| 58 | + y = iris.target[:100] |
| 59 | + y = np.where(y == 1, 1, -1) |
| 60 | + X_train, X_test, y_train, y_test = \ |
| 61 | + train_test_split(X, y, test_size=0.3) |
| 62 | + ppn = Perceptron(eta=0.1, n_iter=10) |
| 63 | + ppn.fit(X_train, y_train) |
| 64 | + plot_decision_regions(ppn,X,y) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments