前言:
這個博客是為了解決異或問題,原理是利用非線性的量來進行划分,和前面的知識有些類似。
正文:
import numpy as np
import matplotlib.pyplot as plt
#輸入數據
X = np.array([[1,0,0,0,0,0],
[1,0,1,0,0,1],
[1,1,0,1,0,0],
[1,1,1,1,1,1]])
#標簽
Y = np.array([-1,1,1,-1])
#權值初始化,1行6列,取值范圍-1到1
W = (np.random.random(6)-0.5)*2
print(W)
#學習率設置
lr = 0.11
#計算迭代次數
n = 0
#神經網絡輸出
O = 0
#除以x.shape()防止每次更新權值過大
#給x轉置是為了符合矩陣乘法的規范
def update():
global X,Y,W,lr,n
n+=1
O = np.dot(X,W.T)
W_C = lr*((Y-O.T).dot(X))/int(X.shape[0])
W = W + W_C
for _ in range(1000):
update()#更新權值
#正樣本
x1 = [0,1]
y1 = [1,0]
#負樣本
x2 = [0,1]
y2 = [0,1]
def calculate(x,root):
a = W[5]
b = W[2]+x*W[4]
c = W[0]+x*W[1]+x*x*W[3]
if root == 1:
return (-b+np.sqrt(b*b-4*a*c))/(2*a)
if root == 2:
return (-b-np.sqrt(b*b-4*a*c))/(2*a)
xdata = np.linspace(-1,2)
plt.figure()
plt.plot(xdata,calculate(xdata,1),'r')
plt.plot(xdata,calculate(xdata,2),'r')
plt.scatter(x1,y1,c='b')
plt.scatter(x2,y2,c='y')
plt.show()
總結:
這個專門用來解決異或問題,和單層感知器的知識有所不同的是用了不同的激活函數,以及用n來計數,引入了6個輸入量,相當於在求解一個二次方程(關於y的二次方程),再利用求根公式來進行畫線。