用 Python 实现购买2个苹果和3个橙子,苹果单价为100,橙子单价为150,消费税为10%,要求输出每个计算节点的结果:a、苹果和橙子的总价(含消费税),b、苹果数量,苹果单价,橙子单价,橙子数量和消费税这五个参数的反向传播值。
import torch
# 定义变量,并设置requires_grad=True以追踪计算历史
apple_count = torch.tensor(2., requires_grad=True)
apple_price = torch.tensor(100., requires_grad=True)
orange_count = torch.tensor(3., requires_grad=True)
orange_price = torch.tensor(150., requires_grad=True)
tax_rate = torch.tensor(0.10, requires_grad=True)
# 计算苹果和橙子的总价
apple_total = apple_count * apple_price
orange_total = orange_count * orange_price
subtotal = apple_total + orange_total
total_with_tax = subtotal * (1 + tax_rate)
# 输出每个计算节点的结果
print("苹果总价(不含税):", apple_total.item())
print("橙子总价(不含税):", orange_total.item())
print("总价(含消费税):", total_with_tax.item())
# 进行反向传播计算梯度
total_with_tax.backward()
# 输出各参数的梯度(反向传播值)
print("\n反向传播值:")
print(f"苹果数量的梯度:{apple_count.grad.item()}")
print(f"苹果单价的梯度:{apple_price.grad.item()}")
print(f"橙子数量的梯度:{orange_count.grad.item()}")
print(f"橙子单价的梯度:{orange_price.grad.item()}")
print(f"消费税率的梯度:{tax_rate.grad.item()}")
运行结果: