pytorch求梯度, MSE损失函数用sum和mean的区别

pytorch求梯度, MSE损失函数用sum和mean的区别

1.  z.mean()取均值操作,梯度计算如下

import torch
x = torch.ones(2, 2, requires_grad=True)
print(x)
# tensor([[1., 1.],
#        [1., 1.]], requires_grad=True)

y = x + 2
print(y)
# tensor([[3., 3.],
#         [3., 3.]], grad_fn=<AddBackward0>)

print(y.grad_fn)
# <AddBackward0 object at 0x7f268025e080>

z = y * y * 3
print(z)
# tensor([[27., 27.],
#        [27., 27.]], grad_fn=<MulBackward0>)

out = z.mean()
print(out)
# tensor(27., grad_fn=<MeanBackward0>)

out.backward() # 梯度回传,必须要这一步才能计算z对x的梯度
print(x.grad)
# tensor([[4.5000, 4.5000],
#        [4.5000, 4.5000]])

解析:
z=3*y*y=3*(x+2)(x+2)
out=z.mean=\frac{1}{4}\times \sum_{i=1}^{4}z _{i}=\frac{1}{4}\times \sum_{i=1}^{4}3\left ( x_{i}+2 \right )^{^{^{2}}}
out 对各个x_i 求导 \frac{d out}{d x_{i}}=\frac{1}{4}\times \sum_{i=1}^{4}6\left ( x_{i}+2 \right )
将x的值带入,得到结果
# tensor([[4.5000, 4.5000],
#        [4.5000, 4.5000]])

2.  z.sum()取求和操作,梯度计算如下

import torch
x1 = torch.ones(2, 2, requires_grad=True)
print(x1)
# tensor([[1., 1.],
#        [1., 1.]], requires_grad=True)

y1 = x1 + 2
print(y1)
# tensor([[3., 3.],
#         [3., 3.]], grad_fn=<AddBackward0>)

print(y1.grad_fn)
# <AddBackward0 object at 0x7f268025e080>

z1 = y1 * y1 * 3
print(z1)
# tensor([[27., 27.],
#        [27., 27.]], grad_fn=<MulBackward0>)

out2 = z1.sum()
print(out2)
# tensor(27., grad_fn=<MeanBackward0>)

out2.backward() # 梯度回传,必须要这一步才能计算z对x的梯度
print(x1.grad)
# tensor([[18., 18.],
#        [18., 18.]])

解析:
z1=3*y1*y1=3*(x1+2)(x1+2)
out2=z1.sum=\sum_{i=1}^{4}z _{i}= \sum_{i=1}^{4}3\left ( x_{i}+2 \right )^{^{^{2}}}
out2 对x1 求导 =6\left ( x_{i}+2 \right )
将x的值带入,得到结果
# tensor([[18., 18.],
#        [18., 18.]])

下面是一个使用PyTorch实现函数逼近的简单示例代码: ```python import torch import time # 定义函数:f(x) = 2x + 1 def true_func(x): return 2 * x + 1 # 生成数据集 x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) y = true_func(x) + torch.randn(x.size()) * 0.1 # 定义模型 model = torch.nn.Sequential( torch.nn.Linear(1, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1) ) # 定义损失函数和优化器 criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 训练模型 start_time = time.time() for epoch in range(1000): y_pred = model(x) loss = criterion(y_pred, y) optimizer.zero_grad() loss.backward() optimizer.step() end_time = time.time() total_time = end_time - start_time # 计算均差和总误差 with torch.no_grad(): y_pred = model(x) average_diff = torch.mean(torch.abs(y_pred - y)) total_error = torch.sum(torch.abs(y_pred - y)) print("运行时间:", total_time) print("均差:", average_diff.item()) print("总误差:", total_error.item()) ``` 在这个示例中,我们使用一个简单的线性函数f(x) = 2x + 1作为真实函数,并生成带有噪声的数据集。然后,我们使用一个包含两个线性层和一个ReLU激活函数的神经网络模型来逼近这个函数。我们使用均方误差损失函数和随机梯度下降优化器进行训练。最后,我们计算运行时间、均差和总误差。 请注意,这只是一个简单的示例,实际中可能需要更复杂的模型和训练过程来实现更准确的函数逼近。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值