BP神经网络-XOR运算

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.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))
    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))
        l2 = sigmoid(np.dot(l1,w))
        print(np.mean(np.abs(y.T-l2)))
l1 = sigmoid(np.dot(x,v))
l2 = sigmoid(np.dot(l1,w))

print(l2)

你可能感兴趣的:(机器学习)