(1)PyTorch损失函数
loss = nn.L1Loss() #(MAE平均绝对误差)
loss = nn.CrossEntropyLoss() #交叉熵验证
loss = nn.MSELoss() #均方误差
pytorch损失函数: 常见pytorch损失函数
(2)自定义损失函数
1、torch.randn()函数
2、torch.pow()函数
3、torch.mean()函数
1、torch.randn()函数
a = torch.randn(4) #随机生成一行四列
print(a)
a = torch.randn(3,4) #随机生成三行四列
print(a)
总结:用来生成随机数字的tensor,这些随机数字满足标准正态分布
运行结果:
2、torch.pow()函数
input = torch.randn(4)
print('input:',input)
exponent = 2
b = torch.pow(input,exponent)
print('b:',b)
c = torch.pow(input,exponent + 1)
print('c:',c)
总结:将tensor内的数字加上exponent的幂
运行结果:
3、torch.mean()函数
input = torch.randn(3)
print('input:',input)
mean = torch.mean(input)
print('mean函数:',mean)
总结:将tensor内的数字求其均值
运行结果:
(3)自定义损失函数与pytorch损失函数验证对比
1、验证 L1 Loss (MAE平均绝对误差)
import torch.nn as nn
import torch
output = torch.randn(3)
target = torch.randn(3)
class test_loss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
return torch.mean(torch.abs(x-y))
#调用torch损失函数
criterion_1 = nn.L1Loss()
loss_1 = criterion_1(output, target)
#自定义损失函数
criterion_2 = test_loss()
loss_2 = criterion_2(output, target)
print(loss_1)
print(loss_2)
运行结果:
由运行结果可知,自定义没有问题
2、验证L2 Loss(均方误差)
import torch.nn as nn
import torch
output = torch.randn(3) #生成随机数
target = torch.randn(3) #生成随机数
class test_loss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
return torch.mean(torch.pow((x - y), 2))
#调用torch损失函数
criterion_1 = nn.MSELoss()
loss_1 = criterion_1(output, target)
#自定义继承torch损失函数
criterion_2 = test_loss()
loss_2 = criterion_2(output, target)
print(loss_1)
print(loss_2)
运行结果:
由运行结果可知,自定义没有问题