问题如下:
【要求】给出如下图所示的训练数据集,其中正实例点是x1 = (3,3),x2 = (4,3),负实例点是x3 = (1,1),用感知机算法的原始形式求感知机模型将正负实例正确分类.
如上图所示,蓝色的点为正实例点,红色的点为负实例点,现在需要通过感知机算法找出一个超平面(在本题中为一条直线,直线就是二维超平面)将正负实例正确分开.
【思路】参考《统计学习方法》第二章.
代码实现:
# encoding = utf8
import numpy as np
import matplotlib.pyplot as plt
def perceptron(x_train, y_train):
m = x_train.shape[0] # m为训练集向量的个数
c = 0 # c用来记录训练次数
w = np.zeros(x_train.shape[1]) # w为权值向量
b = 0 # b为偏置向量
r = 1 # r为学习率
x = x_train
y = y_train
i = 0
while i < m:
if y[i] * (np.dot(w, x[i]) + b) <= 0: # 如果分类出错则更新参数
w = w + (r * y[i] * x[i])
b = b + (r * y[i])
c += 1
i = 0
else:
i += 1
print('w的值是:')
print(w)
print('b的值是')
print(b)
print('训练次数是:%d' % c)
def draw():
x1 = np.linspace(0, 6)
x2 = 3 - x1
plt.xlabel('x1')
plt.ylabel('x2')
plt.axis([0, 6, 0, 6])
plt.scatter(3, 3, color='blue')
plt.scatter(4, 3, color='blue')
plt.scatter(1, 1, color='red')
plt.plot(x1, x2)
plt.show()
if __name__ == '__main__':
x_train = np.array([[3, 3], [4, 3], [1, 1]])
y_train = np.array([1, 1, -1])
perceptron(x_train, y_train)
draw()
运行结果:
从输出结果可以看到训练完成后w = (1,1),b = -3,总共进行了7次更新,与书上的答案一致,且从输出图像可以看到,样本已经被正确分类.
以上.