天天看點

ML之NN:利用神經網絡的BP算法解決XOR類(異或非)問題(BP solve XOR Problem)

輸出結果

ML之NN:利用神經網絡的BP算法解決XOR類(異或非)問題(BP solve XOR Problem)

實作代碼

#BP solve XOR Problem

import numpy as np

X = np.array ([[1, 0, 0],

              [1, 0, 1],

              [1, 1, 0],

              [1, 1, 1]])

#标簽

Y = np.array ([[0, 1, 1, 0]])

V = np.random.randn(3,4)*2-1

W = np.random.randn(4,1)*2-1

print (V)

print (W)

#設定學習率

lr = 0.11

def update():  #更新權值的函數

   global X,Y,W,V,lr  

   L1=sigmoid(np.dot(X,V))

   L2=sigmoid(np.dot(L1,W))

   L2_delta=(Y.T-L2)*dsigmoid(L2)  

   L1_delta=L2_delta.dot(W.T)*dsigmoid(L1)

   W_C=lr*L1.T.dot(L2_delta)

   V_C=lr*X.T.dot(L1_delta)

   W=W+W_C

   V=V+V_C

for i in range(20000):

   update()

   if i%500==0:

       L1=sigmoid(np.dot(X,V))  #隐藏層輸出4*4

       L2=sigmoid(np.dot(L1,W)) #輸出層輸出4*1

       print("error:",np.mean(np.abs(Y.T-L2)))

L1=sigmoid(np.dot(X,V))  

L2=sigmoid(np.dot(L1,W))

print(L2)

def judge(x):

   if x>=0.5:

       return 1

   else:

       return 0

for i in map(judge,L2):

   print(i)