from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_iris
生成线性可分数据集
def creat_data(n):
np.random.seed(1)
x_11=np.random.randint(0,100,(n,1))
x_12=np.random.randint(0,100,(n,1))
x_13=20+np.random.randint(0,10,(n,1))
x_21=np.random.randint(0,100,(n,1))
x_22=np.random.randint(0,100,(n,1))
x_23=10-np.random.randint(0,10,(n,1))
new_x_12=x_12*np.sqrt(2)/2-x_13*np.sqrt(2)/2
new_x_13=x_12*np.sqrt(2)/2+x_13*np.sqrt(2)/2
new_x_22=x_22*np.sqrt(2)/2-x_23*np.sqrt(2)/2
new_x_23=x_22*np.sqrt(2)/2+x_23*np.sqrt(2)/2
plus_samples=np.hstack([x_11,new_x_12,new_x_13,np.ones((n,1))])
minus_samples=np.hstack([x_21,new_x_22,new_x_23,-np.ones((n,1))])
samples=np.vstack([plus_samples,minus_samples])
np.random.shuffle(samples)
return samples
参数:
- n:n=正类的样本点数量=负类的样本点数量(总的样本点数量为2n)
返回值:
- 所有样本点组成的数组,形状为(2*n,4).数组中的每一行代表一个样本点,由其特征x⃗ x→和标记y组成
绘制数据集
def plot_samples(ax,samples):
Y=samples[:,-1]
Y=samples[:,-1]
position_p=Y==1
position_m=Y==-1
ax.scatter(samples[position_p,0],samples[position_p,1],
samples[position_p,2],marker='+',label='+',color='b')
ax.scatter(samples[position_m,0],samples[position_m,1],
samples[position_m,2],marker='^',label='-',color='y')
fig=plt.figure()
ax=Axes3D(fig)
data=creat_data(100)
plot_samples(ax,data)
ax.legend(loc='best')
plt.show()
参数:
- ax:一个Axes3D实例,负责绘制图形
- samples:代表训练数据集的数组,形状为(N,n_features+1),其中N为样本点的个数,n_features代表特征数量
感知机学习算法的原始形式算法
def perceptron(train_data,eta,w_0,b_0):
x=train_data[:,:-1]
y=train_data[:,-1]
length=train_data.shape[0]
w=w_0
b=b_0
step_num=0
while True:
i=0
while(i<length):
step_num+=1
x_i=x[i].reshape((x.shape[1],1))
y_i=y[i]
if y_i*(np.dot(np.transpose(w),x_i)+b)<=0:
w+=eta*y_i*x_i
b+=eta*y_i
break
else:
i+=1
if(i==length):
break
return(w,b,step_num)
参数:
- train_data
- eta:学习率
- w_0:即 w⃗ 0 ,是一个列向量
- b_0:即 b0 ,是一个标量
返回值:
- 一个元组,成员为w⃗ 0w→0,b以及迭代次数
生成分离超平面
def creat_hyperplane(x,y,w,b):
return (-w[0][0]*x-w[1][0]*y-b)/w[2][0]
data=creat_data(100)
eta,w_0,b_0=0.1,np.ones((3,1),dtype=float),1
w,b,num=perceptron(data,eta,w_0,b_0)
fig=plt.figure()
plt.suptitle('perceptron')
ax=Axes3D(fig)
#绘制样本点
plot_samples(ax,data)
#绘制分离超平面
x=np.linspace(-30,100,100)
y=np.linspace(-30,100,100)
x,y=np.meshgrid(x,y)
z=creat_hyperplane(x,y,w,b)
ax.plot_surface(x,y,z,rstride=1,cstride=1,color='g',alpha=0.2)
ax.legend(loc='best')
plt.show()
参数:
- x:分离超平面上点的x坐标组成的数组
- y:分离超平面上点的y坐标组成的数组
- w:即 w⃗ ,超平面的法向量,是一个列向量
- b:即 b0 ,超平面的截距
返回值:
- 分离超平面上的点的z坐标组成的数组