apple = 100 apple_num = 2 orange = 150 orange_num = 3 tax = 1.1 # Layer mul_apple_layer = MulLayer() mul_orange_layer = MulLayer() add_fruit_layer = AddLayer() mul_tax_layer = MulLayer() # Forward apple_price = mul_apple_layer.forward(apple, apple_num) orange_price = mul_orange_layer.forward(orange, orange_num) price = add_fruit_layer.forward(apple_price, orange_price) total_price = mul_tax_layer.forward(price, tax) # Backward dtotal_price = 1 dprice, dtax = mul_tax_layer.backward(dtotal_price) dapple_price, dorange_price = add_fruit_layer.backward(dprice) dapple, dapple_num = mul_apple_layer.backward(dapple_price) dorange, dorange_num = mul_orange_layer.backward(dorange_price) print('apple_price: ', apple_price) print('orange_price:', orange_price) print('price:', price) print('total_price:', int(total_price)) print('=' * 50) print('dprice: ', dprice)
apple = 100 apple_num = 2 orange = 150 orange_num = 3 tax = 1.1 # layer mul_apple_layer = MulLayer() mul_orange_layer = MulLayer() add_apple_orange_layer = AddLayer() mul_tax_layer = MulLayer() # forward apple_price = mul_apple_layer.forward(apple, apple_num) # (1) orange_price = mul_orange_layer.forward(orange, orange_num) # (2) all_price = add_apple_orange_layer.forward(apple_price, orange_price) # (3) price = mul_tax_layer.forward(all_price, tax) # (4) # backward dprice = 1 dall_price, dtax = mul_tax_layer.backward(dprice) # (4) dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price) # (3 dorange, dorange_num = mul_orange_layer.backward(dorange_price) # (2) dapple, dapple_num = mul_apple_layer.backward(dapple_price) # (1) print("price:", int(price)) print("dApple:", dapple) print("dApple_num:", int(dapple_num)) print("dOrange:", dorange) print("dOrange_num:", int(dorange_num)) print("dTax:", dtax)
from layer_naive import MultiLayer from layer_naive import AddLayer apple_price = 100 apple_unit = 2 orange_price = 150 orange_unit = 3 tax = 1.1 mul_apple_cost_layer = MultiLayer() mul_orange_cost_layer = MultiLayer() mul_cost_layer = AddLayer() mul_amount_layer = MultiLayer() apple_cost = mul_apple_cost_layer.forward(apple_price, apple_unit) orange_cost = mul_orange_cost_layer.forward(orange_price, orange_unit) cost = mul_cost_layer.forward(apple_cost, orange_cost) amount = mul_amount_layer.forward(cost, tax) print(amount) d_amount = 1 d_cost, d_tax = mul_amount_layer.backward(d_amount) d_apple_cost, d_orange_cost = mul_cost_layer.backward(d_cost) d_apple_price, d_apple_unit = mul_apple_cost_layer.backward(d_apple_cost) d_orange_price, d_orange_unit = mul_orange_cost_layer.backward(d_orange_cost) print(d_apple_price, d_apple_unit, d_orange_price, d_orange_unit, d_tax)