神经网络学习之----进军多层-BP神经网络-解决异或问题(代码实现)

思路:

  首先有三个输入X0, X1, X2神经元,隐层有四个神经元Y0, Y1, Y2, Y3。最后是一个输出Output。其中:

    X0与Y0, Y1, Y2, Y3的权值分别用V00, V01, V02, V03表示

    X1与Y0, Y1, Y2, Y3的权值分别用V10, V11, V12, V13表示

    X2与Y0, Y1, Y2, Y3的权值分别用V20, V21, V22, V23表示

    Y0与Output的权值用W0表示

    Y1与Output的权值用W1表示

    Y2与Output的权值用W2表示

    Y3与Output的权值用W3表示

  那么,中间隐层的四个神经元Y0, Y1, Y2, Y3得到的结果为:

    Y0=X0*V00+X1*V10+X2*V20

    Y1=X0*V01+X1*V11+X2*V21

    Y2=X0*V02+X1*V12+X2*V22

    Y3=X0*V03+X1*V13+X2*V23

  这样可以得到(Y0, Y1, Y2, Y3)

  最后,我们需要求Output的值:

    Output=Y0*W0 + Y1*W1 + Y2*W2 + Y3*W3

代码实现:

import numpy as np


# In[8]:

#输入数据
X = np.array([[1,0,0],
              [1,0,1],
              [1,1,0],
              [1,1,1]])
#标签
Y = np.array([[0,1,1,0]])
#权值初始化,取值范围-1到1
V = np.random.random((3,4))*2-1 
W = np.random.random((4,1))*2-1
print(V)
print(W)
#学习率设置
lr = 0.11

def sigmoid(x):
    return 1/(1+np.exp(-x))

def dsigmoid(x):
    return x*(1-x)

def update():
    global X,Y,W,V,lr
    
    L1 = sigmoid(np.dot(X,V))#隐藏层输出(4,4)
    L2 = sigmoid(np.dot(L1,W))#输出层输出(4,1)
    
    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


# In[10]:

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))#隐藏层输出(4,4)
L2 = sigmoid(np.dot(L1,W))#输出层输出(4,1)
print(L2)

def judge(x):
    if x>=0.5:
        return 1
    else:
        return 0

for i in map(judge,L2):
    print(i)


# In[ ]:
原文地址:https://www.cnblogs.com/mengqimoli/p/11103003.html