Pytorch中有哪些损失函数?

一、常见的损失

PyTorch提供了丰富的损失函数,用于各种不同的任务,如分类、回归、生成对抗网络(GANs)等。以下是一些常用的损失函数,并给出了它们的调用方法:

1. 均方误差损失(Mean Squared Error Loss):nn.MSELoss

  • 用于回归任务。
```python
import torch
import torch.nn as nn

criterion = nn.MSELoss()
```

2. 交叉熵损失(Cross-Entropy Loss):nn.CrossEntropyLoss

  • 用于分类任务,特别是多类别分类。
```python
import torch
import torch.nn as nn

criterion = nn.CrossEntropyLoss()
```

3. 二分类交叉熵损失(Binary Cross-Entropy Loss):nn.BCELoss

  • 用于二分类任务。
```python
import torch
import torch.nn as nn

criterion = nn.BCELoss()
```

4. Kullback-Leibler 散度损失(Kullback-Leibler Divergence Loss):nn.KLDivLoss

  • 用于衡量两个概率分布之间的相似性。
```python
import torch
import torch.nn as nn

criterion = nn.KLDivLoss()
```

5. 交叉熵损失(多标签):nn.MultiLabelSoftMarginLoss

  • 用于多标签分类任务。
```python
import torch
import torch.nn as nn

criterion = nn.MultiLabelSoftMarginLoss()
```

6. 负对数似然损失(Negative Log Likelihood Loss):nn.NLLLoss

  • 通常与 nn.LogSoftmax 结合使用,用于多类别分类。
```python
import torch
import torch.nn as nn

criterion = nn.NLLLoss()
```

7. Hinge Embedding Loss:nn.HingeEmbeddingLoss

  • 用于支持向量机(SVM)训练。
```python
import torch
import torch.nn as nn

criterion = nn.HingeEmbeddingLoss()
```

以上只是一些损失函数的示例,PyTorch还提供了许多其他损失函数,可以根据任务的不同选择适当的损失函数。在使用损失函数时,通常将其实例化为一个对象,然后在训练循环中使用模型的输出和目标值计算损失。

二、案例

PyTorch中提供了多种损失函数,涵盖了分类、回归和图像处理等不同领域的任务,以下是其中一些常用的损失函数及其使用示例:

1. 交叉熵损失函数(CrossEntropyLoss)

适用于多分类任务,通常与Softmax层结合使用。

import torch.nn as nn
import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self, num_classes):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, num_classes)
    def forward(self, x):
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x
# 创建模型实例、损失函数和优化器
net = Net(num_classes=3) # 假设有3个类别
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data)
loss = criterion(output, target)
loss.backward()
optimizer.step()

2. 均方误差损失函数(MSELoss)

适用于回归任务,用于度量模型输出和目标值之间的平均平方误差。

import torch.nn as nn
import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, 1)
    def forward(self, x):
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x
# 创建模型实例、损失函数和优化器
net = Net()
criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data)
loss = criterion(output, target)
loss.backward()
optimizer.step()

3. 平滑的L1损失函数(SmoothL1Loss)

适用于回归任务,与MSELoss不同,SmoothL1Loss对异常值更加鲁棒。

import torch.nn as nn
import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, 1)
    def forward(self, x):
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x
# 创建模型实例、损失函数和优化器
net = Net()
criterion = nn.SmoothL1Loss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data)
loss = criterion(output, target)
loss.backward()
optimizer.step()

4. 二分类交叉熵损失函数(BCELoss)

适用于二分类任务,将模型输出视为一个概率值,用于度量模型输出和目标值之间的交叉熵。

import torch.nn as nn
import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, 1)
    def forward(self, x):
        x = nn.functional.relu(self.fc1(x))
        x = nn.functional.sigmoid(self.fc2(x))
        return x
# 创建模型实例、损失函数和优化器
net = Net()
criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data)
loss= criterion(output, target) loss.backward() optimizer.step()
= criterion(output, target) loss.backward() optimizer.step()
import torch.nn as nn import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module): def init(self): super(Net, self).init() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 1)
def forward(self, x):
    x = nn.functional.relu(self.fc1(x))
    x = self.fc2(x)
    return x

# 创建模型实例、损失函数和优化器
net = Net() criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([5.0])) optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data) loss = criterion(output, target) loss.backward() optimizer.step()

这里设置了一个正样本的权重为5,表示模型在训练时应该更加关注正样本。

5. 像素级别交叉熵损失函数(CrossEntropyLoss2d)

适用于图像分割任务,将每个像素点的预测结果视为一个概率值,用于度量模型输出和目标值之间的交叉熵。

import torch.nn as nn
import torch.optim as optim
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self, num_classes):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
        self.conv3 = nn.Conv2d(128, num_classes, kernel_size=3, stride=1, padding=1)
    def forward(self, x):
        x = nn.functional.relu(self.conv1(x))
        x = nn.functional.max_pool2d(x, kernel_size=2, stride=2)
        x = nn.functional.relu(self.conv2(x))
        x = nn.functional.max_pool2d(x, kernel_size=2, stride=2)
        x = self.conv3(x)
        return x
# 创建模型实例、损失函数和优化器
net = Net(num_classes=2) # 假设有2个类别
criterion = nn.CrossEntropyLoss2d()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 在每次迭代中,计算并反向传播损失
output = net(input_data)
loss = criterion(output, target)
loss.backward()
optimizer.step()

这里使用了一个简单的卷积神经网络来进行二分类图像分割,输出层使用了两个通道,分别代表两种类别(前景和背景)。损失函数为CrossEntropyLoss2d,用于计算每个像素点的预测结果与真实标签之间的交叉熵损失。

除了以上列出的常见损失函数外,PyTorch还提供了许多其他类型的损失函数,如L1Loss、NLLLoss、KLDivLoss等,可以根据具体应用场景选择适合的损失函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高山莫衣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值