第5章 误差反向传播法

5.4 简单层的实现

 

  • 5.4.1、乘法层的实现

 

class MulLayer:
 def __init__(self):
   self.x = None  #None是特殊类型,它用来表示“空”或“无值”。
   self.y = None #这里对x,y声明,backward和forward都可以使用

 def forward(self, x, y):
   self.x = x
   self.y = y
   out = x * y
   return out

 def backward(self, dout):
   dx = dout * self.y # 翻转x和y 这里dx其实是dL/dx, dout是dL/dout
   dy = dout * self.x
   return dx, dy

 
init()中会初始化实例变量x和y,它们用于保存正向传播时的输入值。
  forward()接收x和y两个参数,将它们相乘后输出。
  backward()将从上游传来的导数(dout)乘以正向传播的翻转值,然后传给下游。
 

  • 5.4.2、 加法层的实现

 

class AddLayer:
 def __init__(self):
   pass

 def forward(self, x, y):
   out = x + y
   return out

 def backward(self, dout):
   dx = dout * 1
   dy = dout * 1
   return dx, dy

 
  加法层不需要特意进行初始化,所以__init__()中什么也不运行(pass语句表示“什么也不运行”)。
  加法层的forward()接收x和y两个参数,将它们相加后输出。
  backward()将上游传来的导数(dout)原封不动地传递给下游。
 

  • 为什么这里不需要初始化呢?因为没有数据需要在forward和backward之间传递,简而言之,就是$ \frac{\partial out}{\partial x}$ =1了,是个常量
     

5.5 激活函数层的实现

 

  • 5.5.1 ReLu

ReLu 导数
 
class Relu:
 def __init__(self):
   self.mask = None  
   def forward(self, x):  #如果 x [5,-5,0,1,-1]
   self.mask = (x <= 0)  #[False, True, True, False, True] 
   out = x.copy()  #[5, -5, 0, 1, -1]
   out[self.mask] = 0 #[5, 0, 0, 1, 0] 
   return out

 def backward(self, dout):
   dout[self.mask] = 0 #根据self.mask来决定,简言之,就是x<=0处,对应值赋值为0 ,[ , 0,0 , , 0]
   dx = dout 
   return dx

 

  • 5.5.2 Sigmoid

 

 

sigmoid正向传播

 
 

sigmoid反向传播计算

 

 

sigmoid反向传播简化表达

 

class Sigmoid:
 def __init__(self):
   self.out = None

 def forward(self, x):
   out = 1 / (1 + np.exp(-x))
   self.out = out
   return out
 def backward(self, dout):
   dx = dout * (1.0 - self.out) * self.out
   return dx

 

5.6 Affine/Softmax层的实现

 

  • 5.6.1 Affine层

 

posted @ 2025-12-29 17:11  limh991  阅读(4)  评论(0)    收藏  举报