赞
踩
单层感知器的理论知识上一节已经介绍过,这一节主要结合代码实现单层感知器的学习过程
这里我们用python3实现,用到numpy库
- import numpy as np
- import matplotlib.pyplot as plt
-
-
-
-
- X = np.array([[1,3,3],[1,4,3],[1,1,1]])
-
-
- Y = np.array([1,1,-1])
-
-
- W = (np.random.random(3)-0.5)*2
-
-
- print(W)
- #学习率
- lr = 0.11
-
-
- n = 0
-
-
- o = 0
-
-
- def update():
- global X,Y,W,lr,n
- n += 1
- o = np.sign(np.dot(X,W.T)/X.shape[0])
- W_C = lr*((Y-o.T).dot(X))
- W = W + W_C
-
-
- def predict(X):
- global W
- y = np.sign(np.dot(X,W.T))
- return y
-
-
- for i in range(100):
- update()
- print(W)
- print(n)
- o = np.sign((np.dot(X,W.T))/X.shape[0])
- if(o == Y.T).all():
- print('finish')
- break
-
- for e in X:
- print(predict(e))
-
-
- x1 = [3,4]
- y1 = [3,3]
- x2 = [1]
- y2 = [1]
- xdata = np.linspace(0,5)
-
-
- k = -W[1]/W[2]
- d = -W[0]/W[2]
-
-
- plt.figure()
- plt.plot(xdata,xdata*k+d,'r')
- plt.plot(x1,y1,'bo')
- plt.plot(x2,y2,'yo')
- plt.show()
-
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。