正向传播方向的计算,很简单,这里我不在累赘。
重点我讲一下反方向的传播:
反向的输入是1
我想看以下消费税对总金额的影响:f(x)=200x
消费税下面的数字:f'(x)×1=200
再看一个,苹果总金额对总金额的影响:
令 f(x)=1.1x
苹果总金额下面的数字:f'(x)×1=1.1
我想知道苹果个数对总金额的影响:
令 f(x)=100x
苹果个数下面的数字:100×1.1=110
class MulLayer: def __init__(self): self.x = None self.y = None def forward(self,x,y): self.x = x self.y = y out = x*y return out def backward(self,dout): dx = dout*self.y dy = dout*self.x return dx,dy '''---------------------正向传播----------------------------------''' # 生成苹果层 mul_apple_layer = MulLayer() mul_tax_layer = MulLayer() apple =100 apple_num = 2 tax = 1.1 # 正向传播 apple_price = mul_apple_layer.forward(apple,apple_num) total_price = mul_tax_layer.forward(apple_price,tax) print("总金额为%f"%total_price) '''-----------------------propagation--------------------------------''' dprice = 1 dapple_price, dtax = mul_tax_layer.backward(dprice) dapple, dapple_num = mul_apple_layer.backward(dapple_price) print(dapple, dapple_num, dtax)