在机器学习和深度学习中,交叉熵损失(Cross-Entropy Loss)和二元交叉熵损失(Binary Cross-Entropy Loss)是两种常用的损失函数,它们在分类任务中发挥着重要作用。本文将详细介绍这两种损失函数的区别和联系,并通过具体的代码示例来说明它们的实现细节。
交叉熵损失(Cross-Entropy Loss)常用于多类分类问题,即每个样本只能属于一个类别,但总类别数量较多。例如,在手写数字识别中,一个图片只能代表一个数字(0-9)。
在 PyTorch 中,你可以使用
torch.nn.CrossEntropyLoss
作为多类分类的交叉熵损失函数。这个损失函数结合了
Softmax
层和交叉熵损失,可以更稳定地处理数值问题。我们使用MNIST数据集作为示例,这是一组手写数字(0-9)的图片,每个图片属于一个类别,代码如下。
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# 设置超参数
batch_size = 64
learning_rate = 0.001
num_epochs = 5
# 定义数据转换
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
# 加载MNIST数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
self.pool = nn.MaxPool2d(2)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 64 * 7 * 7)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# 实例化模型和损失函数
model = SimpleCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
model.train()
for images, labels in train_loader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Accuracy: {100 * correct / total:.2f}%')
二元交叉熵损失(Binary Cross-Entropy Loss)常用于多标签分类问题,即每个样本可以属于多个类别。例如,在多标签图像分类中,一个图片可以同时包含多种物体(猫、狗、车等)。
在 PyTorch 中,你可以使用
torch.nn.BCEWithLogitsLoss
作为二元交叉熵损失函数。这个损失函数结合了
Sigmoid
层和二元交叉熵损失,可以更稳定地处理数值问题。
为了演示多标签分类,我们假设有一个自定义的数据集,每个样本可以同时属于多个类别。
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
# 自定义数据集
class MultiLabelDataset(Dataset):
def __init__(self, num_samples, num_features, num_classes):
self.num_samples = num_samples
self.num_features = num_features
self.num_classes = num_classes
self.data = np.random.randn(num_samples, num_features).astype(np.float32)
self.labels = np.random.randint(0, 2, (num_samples, num_classes)).astype(np.float32)
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
sample = self.data[idx]
label = self.labels[idx]
return sample, label
# 设置超参数
num_samples = 1000
num_features = 20
num_classes = 5
batch_size = 64
learning_rate = 0.001
num_epochs = 5
# 创建数据集和数据加载器
dataset = MultiLabelDataset(num_samples, num_features, num_classes)
data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# 定义模型
class SimpleMLP(nn.Module):
def __init__(self, input_size, num_classes):
super(SimpleMLP, self).__init__()
self.fc1 = nn.Linear(input_size, 128)
self.fc2 = nn.Linear(128, num_classes)
def forward(self, x):
x = F.relu(self.fc1(x))
x = torch.sigmoid(self.fc2(x))
return x
# 实例化模型和损失函数
model = SimpleMLP(num_features, num_classes)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
model.train()
for samples, labels in data_loader:
optimizer.zero_grad()
outputs = model(samples)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# 测试模型
model.eval()
with torch.no_grad():
total_loss = 0
for samples, labels in data_loader:
outputs = model(samples)
loss = criterion(outputs, labels)
total_loss += loss.item()
print(f'Test Loss: {total_loss / len(data_loader):.4f}')
通过本文的介绍和代码示例,希望读者能更好地理解这两种损失函数的区别与联系,并能在实际项目中正确选择和应用它们。
版权归原作者 专业发呆业余科研 所有, 如有侵权,请联系我们删除。