1.感知机是根据输入实例的特征向量 𝑥 对其进行二类分类的线性分类模型:
感知机 - 图1
感知机模型对应于输入空间(特征空间)中的分离超平面感知机 - 图2

2.感知机学习的策略是极小化损失函数:
感知机 - 图3

损失函数对应于误分类点到分离超平面的总距离

3.感知机学习算法是基于随机梯度下降法的对损失函数的最优化算法,有原始形式对偶形式。算法简单且易于实现。原始形式中,首先任意选取一个超平面,然后用梯度下降法不断极小化目标函数。在这个过程中一次随机选取一个误分类点使其梯度下降。

4.当训练数据集线性可分时,感知机学习算法是收敛的。感知机算法在训练数据集上的误分类次数𝑘满足不等式:
感知机 - 图4
当训练数据集线性可分时,感知机学习算法存在无穷多个解,其解由于不同的初值或不同的迭代顺序而可能有所不同。

二分类模型

感知机 - 图5
感知机 - 图6
给定训练集:
感知机 - 图7
定义感知机的损失函数
感知机 - 图8

算法

随即梯度下降法 Stochastic Gradient Descent
随机抽取一个误分类点使其梯度下降。
感知机 - 图9
感知机 - 图10
当实例点被误分类,即位于分离超平面的错误侧,则调整𝑤 , 𝑏 的值,使分离超平面向该无分类点的一侧移动,直至误分类点被正确分类

拿出iris数据集中两个分类的数据和[sepal length,sepal width]作为特征

  1. import pandas as pd
  2. import numpy as np
  3. from sklearn.datasets import load_iris
  4. import matplotlib.pyplot as plt
  5. %matplotlib inline
  6. # load data
  7. iris = load_iris()
  8. df = pd.DataFrame(iris.data, columns=iris.feature_names)
  9. df['label'] = iris.target
  10. df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
  11. df.label.value_counts()

Out:
2 50
1 50
0 50
Name: label, dtype: int64

  1. plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
  2. plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
  3. plt.xlabel('sepal length')
  4. plt.ylabel('sepal width')
  5. plt.legend()

image.png

  1. data = np.array(df.iloc[:100, [0, 1, -1]])
  2. X, y = data[:,:-1], data[:,-1]
  3. y = np.array([1 if i == 1 else -1 for i in y])

Perceptron

  1. # 数据线性可分,二分类数据
  2. # 此处为一元一次线性方程
  3. class Model:
  4. def __init__(self):
  5. self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
  6. self.b = 0
  7. self.l_rate = 0.1
  8. # self.data = data
  9. def sign(self, x, w, b):
  10. y = np.dot(x, w) + b
  11. return y
  12. # 随机梯度下降法
  13. def fit(self, X_train, y_train):
  14. is_wrong = False
  15. while not is_wrong:
  16. wrong_count = 0
  17. for d in range(len(X_train)):
  18. X = X_train[d]
  19. y = y_train[d]
  20. if y * self.sign(X, self.w, self.b) <= 0:
  21. self.w = self.w + self.l_rate * np.dot(y, X)
  22. self.b = self.b + self.l_rate * y
  23. wrong_count += 1
  24. if wrong_count == 0:
  25. is_wrong = True
  26. return 'Perceptron Model!'
  27. def score(self):
  28. pass
  1. In [9]:
  2. perceptron = Model()
  3. perceptron.fit(X, y)
  4. Out[9]:
  5. 'Perceptron Model!'
  1. x_points = np.linspace(4, 7, 10) # 在指定的间隔内返回均匀间隔的数字
  2. y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
  3. plt.plot(x_points, y_)
  4. plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
  5. plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
  6. plt.xlabel('sepal length')
  7. plt.ylabel('sepal width')
  8. plt.legend()

image.png

scikit-learn实例

  1. import sklearn
  2. from sklearn.linear_model import Perceptron
  3. sklearn.__version__
  4. # '0.23.1'
  5. clf = Perceptron(fit_intercept=True,
  6. max_iter=1000,
  7. shuffle=True)
  8. clf.fit(X, y)
  9. Out[13]:
  10. Perceptron()
  11. # Weights assigned to the features.
  12. print(clf.coef_)
  13. # [[ 23.2 -38.7]]
  14. # 截距 Constants in decision function.
  15. print(clf.intercept_)
  16. [-5.]
  1. # 画布大小
  2. plt.figure(figsize=(10,10))
  3. # 中文标题
  4. plt.rcParams['font.sans-serif']=['SimHei']
  5. plt.rcParams['axes.unicode_minus'] = False
  6. plt.title('鸢尾花线性数据示例')
  7. plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Iris-setosa',)
  8. plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')
  9. # 画感知机的线
  10. x_ponits = np.arange(4, 8)
  11. y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
  12. plt.plot(x_ponits, y_)
  13. # 其他部分
  14. plt.legend() # 显示图例
  15. plt.grid(False) # 不显示网格
  16. plt.xlabel('sepal length')
  17. plt.ylabel('sepal width')
  18. plt.legend()

image.png
注意 !
在上图中,有一个位于左下角的蓝点没有被正确分类,这是因为 SKlearn 的 Perceptron 实例中有一个tol参数。
tol 参数规定了如果本次迭代的损失和上次迭代的损失之差小于一个特定值时,停止迭代。所以我们需要设置 tol=None 使之可以继续迭代:

  1. clf = Perceptron(fit_intercept=True,
  2. max_iter=1000,
  3. tol=None,
  4. shuffle=True)
  5. clf.fit(X, y)
  6. # 画布大小
  7. plt.figure(figsize=(10,10))
  8. # 中文标题
  9. plt.rcParams['font.sans-serif']=['SimHei']
  10. plt.rcParams['axes.unicode_minus'] = False
  11. plt.title('鸢尾花线性数据示例')
  12. plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Iris-setosa',)
  13. plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')
  14. # 画感知机的线
  15. x_ponits = np.arange(4, 8)
  16. y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
  17. plt.plot(x_ponits, y_)
  18. # 其他部分
  19. plt.legend() # 显示图例
  20. plt.grid(False) # 不显示网格
  21. plt.xlabel('sepal length')
  22. plt.ylabel('sepal width')
  23. plt.legend()

image.png
现在可以看到,所有的两种鸢尾花都被正确分类了。