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
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
apple = 100
apple_num = 2
tax = 1.1
apple_mul_layer = MulLayer()
tax_num_layer = MulLayer()
apple_price = apple_mul_layer.forward(apple,apple_num)
price = tax_num_layer.forward(apple_price,tax)
print(apple_price)
print(price)#最後的總價價
dprice = 1
dapple_price, dtax = tax_num_layer.backward(dprice)
dapple, dapple_num = apple_mul_layer.backward(dapple_price)
print(dapple, dapple_num,dtax)#每一項增加1,price最後會增加多少
orange = 150
orange_num = 3
#Layer
add_layer = AddLayer()
orange_mul_layer = MulLayer()
#forward
orange_price = orange_mul_layer.forward(orange,orange_num)
all_price = add_layer.forward(apple_price,orange_price)
price = tax_num_layer.forward(all_price,tax)
#backward
dprice = 1
dall_price, dtax = tax_num_layer.backward(dprice)
dapple, dorange_price = add_layer.backward(dall_price)
dorange, dorange_num = orange_mul_layer.backward(dorange_price)
dapple, dapple_num = apple_mul_layer.backward(dapple_price)
#每一項增加1,price最後會增加多少
print(dapple,dorange,dapple_num,dorange_num,dtax/100)
輸出
200
220.00000000000003
2.2 110.00000000000001 200
2.2 3.3000000000000003 110.00000000000001 165.0 6.5