宁波建设网站报价,温州通告最新,南昌企业建站系统,wordpress付费主题破解版我们打开Pytorch官网#xff0c;找到torch.nn中的loss function#xff0c;进去如下图所示。 L1LOSS
我们先来看看 L1LOSS 损失函数的使用。下图是官网给出的描述。 L1loss有两种方式#xff0c;一种是将所有误差累加作为总损失#xff0c;另一种是将所有误差累加之后求平…我们打开Pytorch官网找到torch.nn中的loss function进去如下图所示。 L1LOSS
我们先来看看 L1LOSS 损失函数的使用。下图是官网给出的描述。 L1loss有两种方式一种是将所有误差累加作为总损失另一种是将所有误差累加之后求平均作为总损失。 例如给定输入为input [1,2,3]期望目标为target [1,2,5]若L1loss采用累加求和求总损失那么会有总损失L|1-1||2-2||5 -3|2。如示例2所示。 若L1loss采用累计求和后求平均作为总损失那么则有总损失L|1-1||2-2||5 -3|/30.6667。如示例1所示。
我们用代码来实现L1loss功能。
示例1L1loss的方式为累加求和后求平均。
import torch
from torch.nn import L1Loss
inputs torch.tensor([1, 2, 3], dtypetorch.float32)
targets torch.tensor([1, 2, 5], dtypetorch.float32)inputs torch.reshape(inputs, (1, 1, 1, 3))
targets torch.reshape(targets, (1, 1, 1, 3))loss L1Loss()
result loss(inputs, targets)
print(result) # tensor(0.6667)
示例2L1loss的方式为累加求和。 此时L1loss中的参数reduction应为 sum。默认为’mean‘。
import torch
from torch.nn import L1Loss
inputs torch.tensor([1, 2, 3], dtypetorch.float32)
targets torch.tensor([1, 2, 5], dtypetorch.float32)inputs torch.reshape(inputs, (1, 1, 1, 3))
targets torch.reshape(targets, (1, 1, 1, 3))loss L1Loss(reductionsum)
result loss(inputs, targets)
print(result) # tensor(2.)
MSELOSS
我们再来看看 MSELOSS 损失函数的使用。下图是官网给出的描述。 MSELOSS 与 L1LOSS唯一的区别是MSELOSS在计算每一项损失时都考虑平方。我们以上面的例子为例。 给定输入为input [1,2,3]期望目标为target [1,2,5]若MSEloss采用累加求和求总损失那么会有总损失L1-1^22-2^25 -3^24。如示例3所示。 若 MSEloss 采用累计求和后求平均作为总损失那么则有总损失L {1-1^22-2^25 -3^2 } /34/3。如示例4所示。
示例3
import torch
from torch.nn import MSELoss
inputs torch.tensor([1, 2, 3], dtypetorch.float32)
targets torch.tensor([1, 2, 5], dtypetorch.float32)inputs torch.reshape(inputs, (1, 1, 1, 3))
targets torch.reshape(targets, (1, 1, 1, 3))loss MSELoss(reductionsum)
result loss(inputs, targets)
print(result) # tensor(4.)
示例4
import torch
from torch.nn import MSELoss
inputs torch.tensor([1, 2, 3], dtypetorch.float32)
targets torch.tensor([1, 2, 5], dtypetorch.float32)inputs torch.reshape(inputs, (1, 1, 1, 3))
targets torch.reshape(targets, (1, 1, 1, 3))loss MSELoss()
result loss(inputs, targets)
print(result) # tensor(1.3333)