反向传播算法如何在python项目中实现

  介绍

本篇文章为大家展示了反向传播算法如何在python项目中实现,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

反向传播的目的是计算成本函数C对网络中任意w或b的偏导数。一旦我们有了这些偏导数,我们将通过一些常数α的乘积和该数量相对于成本函数的偏导数来更新网络中的权重和偏差。这是流行的梯度下降算法。而偏导数给出了最大上升的方向,因此,关于反向传播算法,我们继续查看下文。

我们向相反的方向迈出了一小步——最大下降的方向,也就是将我们带到成本函数的局部最小值的方向。

<强>图示演示:

反向传播算法如何在python项目中实现

<强>反向传播算法中乙状结肠函数代码演示:

 #实现乙状结肠函数
  返回1/(1 + np.exp (- x))
  def sigmoid_derivative (x):
  #乙状结肠导数的计算
  返回乙状结肠(x) * (1-sigmoid (x)) 

<强>反向传播算法中ReLU函数导数函数代码演示:

 def relu_derivative (x): # ReLU函数的导数
  d=np。数组(x,复制=True) #用于保存梯度的张量
  d [x & lt;0)=0 #元素为负的导数为0
  d (x祝辞=0)=1 #元素为正的导数为1
  返回d 

BP反向传播算法Python简单实现

进口numpy np
  
  #“pd"偏导
  def乙状结肠(x):
  返回1/(1 + np.exp (- x))
  
  def sigmoidDerivationx (y):
  返回y * (1 - y)
  
  
  if __name__==癬_main__":
  #初始化
  偏见=[0.35,0.60]
  重量=(0.15,0.2,0.25,0.3,0.4,0.45,0.5,0.55)
  output_layer_weights=(0.4, 0.45, 0.5, 0.55)
  i1=0.05
  i2=0.10
  target1=0.01
  target2=0.99
  α=0.5 #学习速率
  numIter=10000 #迭代次数
  因为我在范围(numIter):
  #正向传播
  neth2=i1和i2 * *体重[1]+[2]+重量偏差[0]
  neth3=i1和i2 * *体重[3:1]+[4:1]+重量偏差[0]
  outh2=乙状结肠(neth2)
  outh3=乙状结肠(neth3)
  neto1=outh2 *重量[5:1]+ outh3 *重量(6 - 1)+偏见[1]
  neto2=outh3 *重量(7 - 1)+ outh3 *重量(8 - 1)+偏见[1]
  outo1=乙状结肠(neto1)
  outo2=乙状结肠(neto2)
  打印(str(我)+“target1:“+ str (target1-outo1) +“target2:“+ str (target2-outo2))
  如果我==numIter-1:
  打印(最近的结果:“;+ str (outo1) +“;“;+ str (outo2))
  #反向传播
  #计算w5-w8(输出层权重)的误差
  pdEOuto1=- (target1 - outo1)
  pdOuto1Neto1=sigmoidDerivationx (outo1)
  pdNeto1W5=outh2
  pdEW5=pdEOuto1 * pdOuto1Neto1 * pdNeto1W5
  pdNeto1W6=outh3
  pdEW6=pdEOuto1 * pdOuto1Neto1 * pdNeto1W6
  pdEOuto2=- (target2 - outo2)
  pdOuto2Neto2=sigmoidDerivationx (outo2)
  pdNeto1W7=outh2
  pdEW7=pdEOuto2 * pdOuto2Neto2 * pdNeto1W7
  pdNeto1W8=outh3
  pdEW8=pdEOuto2 * pdOuto2Neto2 * pdNeto1W8
  
  #计算w1-w4(输出层权重)的误差
  pdEOuto1=- (target1 - outo1) #之前算过
  pdEOuto2=- (target2 - outo2) #之前算过
  pdOuto1Neto1=sigmoidDerivationx (outo1) #之前算过
  pdOuto2Neto2=sigmoidDerivationx (outo2) #之前算过
  pdNeto1Outh2=体重[5:1]
  pdNeto2Outh3=重量(7 - 1)
  
  pdEOuth2=pdEOuto1 * pdOuto1Neto1 * pdNeto1Outh2 + pdEOuto2 * pdOuto2Neto2 * pdNeto1Outh2
  pdOuth2Neth2=sigmoidDerivationx (outh2)
  pdNeth2W1=i1
  pdNeth2W2=i2
  pdEW1=pdEOuth2 * pdOuth2Neth2 * pdNeth2W1
  pdEW2=pdEOuth2 * pdOuth2Neth2 * pdNeth2W2
  pdNeto1Outh3=重量(6 - 1)
  pdNeto2Outh3=重量(8 - 1)
  pdOuth3Neth3=sigmoidDerivationx (outh3)
  pdNeth3W3=i1
  pdNeth3W4=i2
  pdEOuth3=pdEOuto1 * pdOuto1Neto1 * pdNeto1Outh3 + pdEOuto2 * pdOuto2Neto2 * pdNeto2Outh3
  pdEW3=pdEOuth3 * pdOuth3Neth3 * pdNeth3W3
  pdEW4=pdEOuth3 * pdOuth3Neth3 * pdNeth3W4
  #权重更新
  重量(1 - 1)=重量(1 - 1)-α* pdEW1
  体重[2]=[2]-α* pdEW2重量
  体重[3:1]=[3:1]-α* pdEW3重量
  体重[4:1]=[4:1]-α* pdEW4重量
  体重[5:1]=[5:1]-α* pdEW5重量
  重量(6 - 1)=(6 - 1)-α* pdEW6重量
  重量(7 - 1)=重量(7 - 1)-α* pdEW7
  重量(8 - 1)=重量(8 - 1)-α* pdEW8
  #打印(重量(1 - 1))
  #打印(体重[2])
  #打印(体重[3:1])
  #打印(体重[4:1])
  #打印(体重[5:1])
  #打印(重量(6 - 1))
  #打印(重量(7 - 1))
  #打印(重量(8 - 1))
反向传播算法如何在python项目中实现