感知机是二类分类的线性模型,其输入为实例的特征向量,输出为实例的类别,取+1和-1二值。感知机对应于输入空间(特征空间)中将实例划分为正负二类的分离超平面,属于判别模型。
感知机学习旨在求出将训练数据进行线性划分的分离超平面。为此,导入基于误分类的损失函数,利用梯度下降法对损失函数进行极小化。
感知机预测是用学习得到的感知机模型对新的输入实例进行分类。
(1)感知机模型
(2)感知机学习的损失函数
(3)感知机算法的原始形式
#感知机学习算法的原始形式
import numpy as np
from matplotlib import pyplot as plt
x=np.array([[1,1],[3,3],[4,3]])
y=np.array([[-1],[1],[1]])
w=[0,0]
b=0
def Train(x,y,w,b):
length = x.shape[0]
j=0
while True:
count=0
for i in range(length):
print("迭代次数为:%d w=[%d,%d] b=%d"%(j,w[0],w[1],b))
if y[i]*(np.dot(w,x[i])+b)<=0: #未被正确分类
#更新w,b
w=w+y[i]*x[i]
b=b+y[i]
count+=1
j+=1
if count==0:
f="f(x)=sign(%d*x+%d*x+%d)"%(w[0],w[1],b)
print("感知机模型为:%s"%f)
return w,b,f
w,b,f=Train(x,y,w,b)
#画分离超平面图
def fun(x):
y=(-b-w[0]*x)/w[1]
return y
x_data=np.linspace(0,5)
y_data=fun(x_data)
plt.plot(x_data,y_data,color='r')
plt.title("perceptron")
#画散点图
for i in range(x.shape[0]):
if y[i] < 0:
plt.scatter(x[i][0], x[i][1], marker='x',s=50)
else:
plt.scatter(x[i][0], x[i][1])
plt.show()
运行结果:
(3)感知机算法的对偶形式
感知机的对偶形式与原始形式并没有多大的区别,运算的过程都是一样的,但通过对偶形式会事先计算好一些步骤的结果并存储到Gray矩阵中,因此可以加快一些运算速度,数据越多节省的计算次数就越多,因此比原始形式更加的优化。
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[3, 3], [4, 3], [1, 1]])
y = np.array([[1], [1], [-1]])
# 创建gram矩阵
z = np.transpose(x)
m = np.dot(x,z)
print("构建的Gram矩阵为:\n",m)
print("-------------------------")
a = np.zeros((x.shape[0], 1))
b = 0
def train(x,y,m,a,b):
length = x.shape[0]
while True:
count = 0
for i in range(length):
n = np.dot(m[i], a * y ) + b
if n* y[i] <= 0:
a[i] = a[i] + 1
b = b + y[i]
count += 1
if count == 0:
w = np.sum(x * a* y, axis=0)
print(w,b)
print("感知机模型:\nf(x) = sign(%dx+%dy+(%d))\n"%(w[0],w[1],b))
return w,b
w,b = train(x,y,m,a,b)
def fun(x):
y = (-b -w[0] * x) / w[1]
return y
x_data = np.linspace(0, 5, 100) # 创建等差数组
y_data = fun(x_data)
plt.plot(x_data, y_data, color='r', label='y1 data')
for i in range(x.shape[0]):
if y[i] < 0:
plt.scatter(x[i][0], x[i][1], marker='x', s=50)
else:
plt.scatter(x[i][0], x[i][1], s=50)
plt.show()
运行结果: