1 前言
感知机是二分类的线性分类模型。输入为:实例的特征向量;输出:实例的类别【一般取-1和+1二值】。
感知机对应于输入空间(特征空间)中将实例划分为正负两类的分离超平面,属于判别模型。感知机学习旨在求出将训练数据进行线性划分的超平面,为此,导入基于误分类的损失函数,利用梯度下降法对损失函数进行极小化,求出感知机模型。
感知机分为原始模式和对偶形式。
2 感知机模型
定义2.1(感知机) 假设输入空间(特征空间)是
χ
⊆
R
n
\chi \subseteq R^n
χ⊆Rn ,输入空间是
Y
⊆
{
−
1
,
+
1
}
\mathcal{Y} \subseteq \left \{ -1,+1 \right \}
Y⊆{−1,+1},输入
x
∈
χ
x\in \chi
x∈χ 表示实例的特征向量,对应于输入空间(特征空间)的点;输入
y
∈
Y
y \in \mathcal{Y}
y∈Y 表示实例的类别。由输入空间到输出空间的如下函数:
f
(
x
)
=
s
i
g
n
(
w
⋅
x
+
b
)
f(x)=sign(w\cdot x+b)
f(x)=sign(w⋅x+b)
称为感知机。其中,
w
w
w 和
b
b
b为感知机模型参数,
w
∈
R
n
w\in R^n
w∈Rn叫做权值或权值向量,
b
∈
R
b \in R
b∈R叫做偏置,
w
⋅
x
w\cdot x
w⋅x 叫做
w
w
w 和
b
b
b的内积。sign是符号函数,即
s
i
g
n
=
{
+1
,
x
≥
0
-1
,
x
<
0
sign=\begin{cases} & \text{ +1 }, x\ge 0 \\ & \text{ -1 } ,x< 0 \end{cases}
sign={ +1 ,x≥0 -1 ,x<0
感知机
s
i
n
g
(
w
⋅
x
)
sing(w\cdot x)
sing(w⋅x) 学习的损失函数定义为
L
(
w
,
b
)
=
−
∑
x
i
∈
M
y
i
(
w
⋅
x
i
+
b
)
L(w,b)=-\sum_{x_i\in M}^{} y_i(w\cdot x_i+b)
L(w,b)=−xi∈M∑yi(w⋅xi+b)
其中
M
M
M为误分类点的集合。这个损失函数就是感知机学习的经验风险函数。
L
(
w
,
b
)
L(w,b)
L(w,b)是非负的。
3 感知机学习算法的原始形式
输入:
训练数据集 T = { ( x 1 , y 1 ) ( x 2 , y 2 ) , … , ( x N , y N ) } T = \left \{ \left ( x_1,y_1 \right ) \left ( x_2,y_2 \right ),\dots ,\left ( x_N,y_N \right ) \right \} T={(x1,y1)(x2,y2),…,(xN,yN)} ,其中 x i ∈ X = R n x_i\in X=R^n xi∈X=Rn, y i ∈ Y = − 1 , + 1 y_i\in Y={-1,+1} yi∈Y=−1,+1, i = 1 , 2 , … , N i=1,2,…,N i=1,2,…,N;学习率 η ( 0 < η ≤ 1 ) η(0<η≤1) η(0<η≤1);
输出:
w w w, b b b;感知机模型 f ( x ) = s i g n ( w ⋅ x + b ) f(x)=sign(w⋅x+b) f(x)=sign(w⋅x+b)。
-
选取初始值 w 0 , b 0 w_0,b_0 w0,b0;
-
在训练集中选取数据 ( x i , y i ) (x_i,y_i) (xi,yi);
-
如果 y i ( w ⋅ x + b ) ≤ 0 y_i (w⋅x+b)≤0 yi(w⋅x+b)≤0,
w = w + η y i x i b = b + η y i w=w+ηy_i x_i\\ b=b+ηy_i w=w+ηyixib=b+ηyi转2,直至训练集中没有误分类点。
import numpy as np
# 数据线性可分
# 此处为一元一次线性方程
class Model:
def __init__(self, data):
self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
self.b = 0
self.eta = 0.1 # 学习率
# 随机梯度下降法
def fit(self, X_train, y_train):
train_complete_flag = False
while not train_complete_flag:
wrong_count = 0
for d in range(len(X_train)):
X = X_train[d]
y = y_train[d]
if y * np.sign(np.dot(X, self.w) + self.b) <= 0:
self.w = self.w + self.eta * np.dot(y, X)
self.b = self.b + self.eta * y
wrong_count += 1
if wrong_count == 0:
train_complete_flag = True
print("训练完成")
print("权重w:", self.w)
print("偏置b:", self.b)
4 感知机学习算法的对偶形式
输入:
训练数据集 T = { ( x 1 , y 1 ) ( x 2 , y 2 ) , … , ( x N , y N ) } T = \left \{ \left ( x_1,y_1 \right ) \left ( x_2,y_2 \right ),\dots ,\left ( x_N,y_N \right ) \right \} T={(x1,y1)(x2,y2),…,(xN,yN)} ,其中 x i ∈ X = R n x_i\in X=R^n xi∈X=Rn, y i ∈ Y = − 1 , + 1 y_i\in Y={-1,+1} yi∈Y=−1,+1, i = 1 , 2 , … , N i=1,2,…,N i=1,2,…,N;学习率 η ( 0 < η ≤ 1 ) η(0<η≤1) η(0<η≤1);
输出:
α i , b α_i,b αi,b;感知机模型 f ( x ) = s i g n ( ∑ j = 1 N α j y j x j ⋅ x + b ) f(x)=sign(\sum_{j=1}^{N} \alpha_j y_j x_j ⋅x+b) f(x)=sign(∑j=1Nαjyjxj⋅x+b),其中 α = ( α 1 , α 2 , … , α n ) T α=(α_1,α_2,…,α_n )^T α=(α1,α2,…,αn)T。
- α = 0 , b = 0 α=0,b=0 α=0,b=0;
- 在训练集中选取数据 ( x i , y i ) (x_i,y_i) (xi,yi);
- 如果
y
i
(
∑
j
=
1
N
α
j
y
j
x
j
⋅
x
+
b
)
≤
0
y_i(\sum_{j=1}^{N} \alpha_j y_j x_j ⋅x+b)≤0
yi(∑j=1Nαjyjxj⋅x+b)≤0,
α i = α i + η b = b + η y i α_i=α_i+η\\ b=b+ηy_i αi=αi+ηb=b+ηyi
转至2,直至训练集中没有误分类点。
对偶形式中训练实例仅以内积的形式出现。为了方便,可以预先将训练集中实例间的内积计算出来并以矩阵的形式存储,这个矩阵就是所谓的Gram矩阵(Grammatrix)
G
=
[
x
i
∙
y
i
]
N
×
N
G=[x_i∙y_i ]_{N \times N}
G=[xi∙yi]N×N
# Dual form
import numpy as np
# 数据线性可分
# 此处为一元一次线性方程
class Model:
def __init__(self, X):
self.alpha = np.zeros(X.shape[0])
self.b = 0
self.eta = 0.1 # 学习率
self.Gram = np.dot(X, X.T) # 存放两两相乘的Gram矩阵
# 随机梯度下降法
def fit(self, X_train, y_train):
train_complete_flag = False
while not train_complete_flag:
wrong_count = 0
for i in range(len(X_train)):
X = X_train[i]
y = y_train[i]
# 当有一个点分类错误时,更新alpha_i和偏执
tmp_sum = np.dot(np.multiply(self.alpha, y_train), self.Gram[:, i])
# tmp_sum = 0
# for j in range(X.shape[0]):
# tmp_sum += self.alpha[j] * y_train[j] * self.Gram[j, i]
if y * (tmp_sum + self.b) <= 0:
self.alpha[i] += self.eta
self.b += self.eta * y
wrong_count += 1
if wrong_count == 0:
train_complete_flag = True
# 训练完成后计算权重
self.w = np.dot(np.multiply(self.alpha, y_train), X_train)
print("训练完成")
print("权重w:", self.w)
print("偏置b:", self.b)
5 内置函数
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import sklearn
from sklearn.linear_model import Perceptron
# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = [
'sepal length', 'sepal width', 'petal length', 'petal width', 'label'
]
df.label.value_counts()
plt.figure()
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
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])
sklearn.__version__
clf = Perceptron(fit_intercept=True, max_iter=1000, shuffle=True)
clf.fit(X, y)
print("Weights assigned to the features: ", clf.coef_)
print("Constants in decision function:", clf.intercept_)
# 画布大小
plt.figure(figsize=(10, 10))
# 中文标题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title('鸢尾花线性数据示例')
plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Tris-setosa')
plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')
# 画感知机的线
x_points = np.arange(4, 8)
y_ = -(clf.coef_[0][0] * x_points + clf.intercept_) / clf.coef_[0][1]
plt.plot(x_points, y_)
# 其他部分
plt.legend()
plt.grid(False)
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()
6 其他
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris # 导入莺尾花数据
import matplotlib.pyplot as plt
import Perceptron_Dual
import Perceptron
from timeit import default_timer as timer
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = [
'sepal length', 'sepal width', 'petal length', 'petal width', 'label'
]
df.label.value_counts()
plt.subplot(1, 3, 1)
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('萼片长度')
plt.ylabel('萼片宽度')
plt.title('初始状态')
plt.legend()
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])
'''
原始形式
'''
tic = timer()
perceptron = Perceptron.Model(X)
perceptron.fit(X, y)
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.subplot(1, 3, 2)
plt.plot(x_points, y_)
plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('萼片长度')
plt.ylabel('萼片宽度')
plt.title('感知机(原始形式)')
plt.legend()
toc = timer()
print("运行时间:", toc - tic)
'''
对偶形式
'''
tic = timer()
perceptron = Perceptron_Dual.Model(X)
perceptron.fit(X, y)
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.subplot(1, 3, 3)
plt.plot(x_points, y_)
plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('萼片长度')
plt.ylabel('萼片宽度')
plt.title('感知机(对偶形式)')
plt.legend()
toc = timer()
print("运行时间:", toc - tic)
plt.show()
运行结果: