第2章 感知机
第2章 感知机
1.感知机是根据输入实例的特征向量\(x\)对其进行二类分类的线性分类模型: \[ f(x)=\operatorname{sign}(w \cdot x+b) \]
感知机模型对应于输入空间(特征空间)中的分离超平面\(w \cdot x+b=0\)。
2.感知机学习的策略是极小化损失函数: \[ \min _{w, b} L(w, b)=-\sum_{x_{i} \in M} y_{i}\left(w \cdot x_{i}+b\right) \]
损失函数对应于误分类点到分离超平面的总距离。
3.感知机学习算法是基于随机梯度下降法的对损失函数的最优化算法,有原始形式和对偶形式。算法简单且易于实现。原始形式中,首先任意选取一个超平面,然后用梯度下降法不断极小化目标函数。在这个过程中一次随机选取一个误分类点使其梯度下降。
4.当训练数据集线性可分时,感知机学习算法是收敛的。感知机算法在训练数据集上的误分类次数\(k\)满足不等式:
\[ k \leqslant\left(\frac{R}{\gamma}\right)^{2} \]
当训练数据集线性可分时,感知机学习算法存在无穷多个解,其解由于不同的初值或不同的迭代顺序而可能有所不同。
二分类模型
\[ f(x) = sign(w\cdot x + b) \]
\[ \operatorname{sign}(x)=\left\{\begin{array}{ll}{+1,} & {x \geqslant 0} \\ {-1,} & {x<0}\end{array}\right. \]
给定训练集:
\[ T=\left\{\left(x_{1}, y_{1}\right),\left(x_{2}, y_{2}\right), \cdots,\left(x_{N}, y_{N}\right)\right\} \] 定义感知机的损失函数
\[ L(w, b)=-\sum_{x_{i} \in M} y_{i}\left(w \cdot x_{i}+b\right) \]
算法
随即梯度下降法 Stochastic Gradient Descent
随机抽取一个误分类点使其梯度下降。
\[ \begin{aligned} w&=w+\eta y_i x_i \\ b&=b+\eta y_i \end{aligned} \] 当实例点被误分类,即位于分离超平面的错误侧,则调整\(w\), \(b\)的值,使分离超平面向该无分类点的一侧移动,直至误分类点被正确分类
拿出iris
数据集中两个分类的数据和[sepal length,sepal width]
作为特征
import pandas as pd |
# load data |
df.columns = [ |
Output[ ]
2 50
1 50
0 50
Name: label, dtype: int64
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0') |
Output[ ]
<matplotlib.legend.Legend at 0x1781578e588>
data = np.array(df.iloc[:100, [0, 1, -1]]) |
X, y = data[:,:-1], data[:,-1] |
y = np.array([1 if i == 1 else -1 for i in y]) |
Perceptron
# 数据线性可分,二分类数据 |
perceptron = Model() |
Output[ ]
'Perceptron Model!'
x_points = np.linspace(4, 7, 10) |
Output[ ]
<matplotlib.legend.Legend at 0x178158adfc8>
scikit-learn
实例
import sklearn |
sklearn.__version__ |
Output[ ]
'0.23.1'
clf = Perceptron(fit_intercept=True, |
Output[ ]
Perceptron()
# Weights assigned to the features. |
Output[ ]
[[ 23.2 -38.7]]
# 截距 Constants in decision function. |
Output[ ]
[-5.]
# 画布大小 |
Output[ ]
<matplotlib.legend.Legend at 0x17815902248>
注意 !
在上图中,有一个位于左下角的蓝点没有被正确分类,这是因为SKlearn
的Perceptron
实例中有一个tol
参数。
tol
参数规定了如果本次迭代的损失和上次迭代的损失之差小于一个特定值时,停止迭代。所以需要设置
tol=None
使之可以继续迭代:
clf = Perceptron(fit_intercept=True, |
Output[ ]
<matplotlib.legend.Legend at 0x1781588e608>
现在可以看到,所有的两种鸢尾花都被正确分类了。
第2章感知机-习题
Minsky 与 Papert
指出:感知机因为是线性模型,所以不能表示复杂的函数,如异或 (XOR)
。验证感知机为什么不能表示异或。
解答:
对于异或函数XOR,全部的输入与对应的输出如下:
\(x^{(1)}\) | \(x^{(2)}\) | \(y\) |
---|---|---|
1 | 1 | -1 |
1 | -1 | 1 |
-1 | 1 | 1 |
-1 | -1 | -1 |