实际上,中间的z1,z2,z3的寻找,如果要某个为1,其他都为0,只需要用t1 + t2 + t3 - bias = 0来求得,具体得,如果要010输出为1,我们只需要让t2为1,t1和t3为-1,再调整bias即可
那么我们就会得到这样的网络结构:
这样,就可以将(000,111,110)中区域的点与其他区域分开
这可能就是下面这张图的直观理解了:
具体执行迭代计算的代码量很小,大部分的代码都是在画出三维的平面图
import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def main(): path = 'data.txt' data = pd.read_csv(path, header=None, names=['x', 'y','z']) #读入数据 X = np.array(data.iloc[:,:]) X = np.column_stack((X, np.ones((len(X),1)))) # 构成增广向量 X[4:,:] = - X[4:,:] # 规范化 #初始化参数 c = 1 w = np.array([-1,-2,-2,0]) flag = True cnt = 0 while flag: cnt += 1 flag = False for x in X: if w @ x <= 0: w = w + c*x # 更新权向量 flag = True print("after {} iterations:c = {}, w={}".format(cnt,c,w)) fig = plt.figure(figsize=(12, 8)) ax = fig.gca(fc='whitesmoke', projection='3d' ) x1 = np.linspace(0, 2, 9) x2 = np.linspace(0, 2, 9) x1,x2 = np.meshgrid(x1, x2) x3 = (-w[3] - w[0]*x1 -w[1]*x2)/w[2] ax.plot_surface(X=x1, Y=x2, Z=x3, color='b', alpha=0.2 ) half = int(len(X)/2) X[4:,:] = - X[4:,:] x = X[:half, 0] y = X[:half, 1] z = X[:half, 2] ax.scatter(x, y, z,c='y',marker='o',label='class 1') x2 = X[half:, 0] y2 = X[half:, 1] z2 = X[half:, 2] ax.scatter(x2, y2, z2,c='r',marker='x',label = 'class 2') ax.legend() for i_x, i_y,i_z in zip(X[:,0],X[:,1],X[:,2]): ax.text(i_x, i_y,i_z, '({}, {},{})'.format(int(i_x), int(i_y),int(i_z))) ax.set(xlabel='X', ylabel='Y', zlabel='Z', xlim=(0, 2), ylim=(0, 2), zlim=(0, 2), xticks=np.arange(0, 2, 1), yticks=np.arange(0, 2, 1), zticks=np.arange(0, 2, 1) ) plt.show() main()