感知器的流程:
- y=f(Wx+b) W是权值 b是偏置量(bias)→其实可写成y=f(WTx) 因为可以b可以处理成W0*x0
- Wi←Wi+ΔWi
- b←b+Δb
- ΔWi=η(t-y)xi η是学习率(learning-rate),t是真实值(label),y是预测值(output)
- Δb=η(t-y)
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def perception(W, w1, w2): flag = False while flag != True: for i in range(len(w1)): t1 = 0 t2 = 0 for j in range(len(W)): t1 += W[j] * w1[i][j] t2 += W[j] * w2[i][j] if (t1 <= 0): for j in range(len(W)): W[j] += w1[i][j] flag = False break if (t2 >= 0): for j in range(len(W)): W[j] -= w2[i][j] flag = False break flag = True print("判别函数:" + "d(x)= %d" % (W[0]) + "x" + "%d" % (W[1]) + "y" + "%d" % (W[2]) + "z+" + "%d" % (W[3])) return W if __name__ == '__main__': W = [-1, -2, -2, 0] w1 = [[0, 0, 0, 1], [1, 0, 0, 1], [1, 0, 1, 1], [1, 1, 0, 1]] w2 = [[0, 0, 1, 1], [0, 1, 1, 1], [0, 1, 0, 1], [1, 1, 1, 1]] W = perception(W, w1, w2) fig = plt.figure() ax = Axes3D(fig) for i in range(len(w1)): ax.scatter(w1[i][0], w1[i][1], w1[i][2], c='r', marker='*') ax.scatter(w2[i][0], w2[i][1], w2[i][2], c='b', marker='o') plt.grid() xmin = min(min(w1[:][0]), min(w2[:][0])) xmax = max(max(w1[:][0]), max(w2[:][0])) ymin = min(min(w1[:][1]), min(w2[:][1])) ymax = max(max(w1[:][1]), max(w2[:][1])) x = np.linspace(xmin, xmax, 10) y = np.linspace(ymin, ymax, 10) x, y = np.meshgrid(x, y) z = [] for i in range(len(x)): z.append(((W[0] * x[i] + W[1] * y[i] + W[3]) / (-W[2]))) ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='rainbow') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()