- 上游的值乘以输入数据的“翻转值”
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):
"""反向传播,传播参数为导数dout"""
dx = dout * self.y
dy = dout * self.x
return dx, dy
apple = 100
apple_num = 2
tax = 1.1
mul_apple_layer = Mullayer()
mul_tax_layer = Mullayer()
apple_price = mul_apple_layer.forward(apple, apple_num)
price = mul_tax_layer.forward(apple_price, tax)
print(price)
"""与前面的正向传播完全反过来,并且输入是apple_price的导数"""
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
dapple, dapple_num = mul_apple_layer.backward(dapple_price)
print(dapple, dapple_num, dtax)