预测任务--Pytorch常用损失函数

# Pytorch常用损失函数

model = nn.Sigmoid()
# 优化器设置 ,并传入模型参数和相应的学习率
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

# 常用损失函数
# L1Loss(L1 norm) 创建一个criterion计算input x和target y的每个元素的平均绝对误差(mean absolute error (MAE))
criterion = nn.L1Loss()
input = torch.randn(1, 2, requires_grad=True)#tensor([[-0.0625, -2.1603]], requires_grad=True)
target = torch.randn(1, 2)#tensor([[0.6789, 0.9831]])
loss = criterion(input, target)#tensor(1.9424, grad_fn=<L1LossBackward>)
# output = (|-0.0625-0.6789| + |-2.1603-0.9831|) / 2 = 1.9424
# 反向传播与优化
# 清空上一步的残余更新参数值
optimizer.zero_grad()
# 反向传播
loss.backward()
# 将参数更新值施加到model的parameters上
optimizer.step()


# MSELoss(L2 norm)  创建一个criterion计算input x和target y的每个元素的均方误差(mean absolute error (MAE))
criterion = nn.MSELoss()
input = torch.randn(1, 2, requires_grad=True)#tensor([[-1.4445, -2.4888]], requires_grad=True)
target = torch.randn(1, 2)#tensor([[ 0.7117, -0.1200]])
loss = criterion(input, target)#tensor(5.1303, grad_fn=<MseLossBackward>)
# output = ( (-1.4445-0.7117)2 + ( -2.4888 + 0.1200 )2 ) / 2 = 5.1303
# 反向传播与优化
# 清空上一步的残余更新参数值
optimizer.zero_grad()
# 反向传播
loss.backward()
# 将参数更新值施加到model的parameters上
optimizer.step()


# SmoothL1Loss  创建一个criterion,如果绝对元素误差低于1,则使用平方项,否则使用L1项。与MSELoss相比,它对异常值的敏感度较低; 在某些情况下,它可以防止梯度的爆炸式增长
criterion = nn.SmoothL1Loss()
input = torch.randn([2, 3, 32, 32], requires_grad=True)
target = torch.randn([2, 3, 32, 32])
loss = criterion(input, target)
# 反向传播与优化
# 清空上一步的残余更新参数值
optimizer.zero_grad()
# 反向传播
loss.backward()
# 将参数更新值施加到model的parameters上
optimizer.step()

# torch.randn 与 torch.rand
# 标准正态分布  返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数。
x1 = torch.randn([2, 3, 32, 32])
# 均匀分布  返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数。
x2 = torch.rand([2, 3, 32, 32])