import numpy as np import matplotlib.pyplot as plt #输入数据 X=np.array([[1,0,0],[1,0,1],[1,1,0],[1,1,1]]) #标签 Y=np.array([0,1,1,0]) #权值初始化,1行3列,取值范围-1到1 W=(np.random.random((4,1))-0.5)*2 V=(np.random.random((3,4))-0.5)*2 print(W) #学习率 lr=0.11 #计算迭代次数 n=0 #神经网络输出 O=0 def sigmoid(x): return 1/(1+np.exp(-x)) def dsigmoid(x): return x*(1-x) def update(): global X,Y,W,V,n,lr n=n+1 L1=sigmoid(np.dot(X,V)) L2=sigmoid(np.dot(L1,W)) L2_delta=(Y.T-L2)*dsigmoid(L1) print(L2_delta) L1_delta=L2_delta*(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 def result(t): if t>=0.5: return 1 else: return 0 def fun(): for i in range(1000): update() L1 = sigmoid(np.dot(X, V)) L2= sigmoid(np.dot(L1,W)) print(np.mean(np.abs(Y.T - L2))) for i in map(result,L2): print(i) fun()
BP网络
最新推荐文章于 2024-02-26 21:17:25 发布