
本文旨在帮助读者理解和解决 PyTorch 二分类模型训练过程中可能出现的准确率异常低的问题。通过分析常见的错误原因,例如精度计算方式、数据类型不匹配等,并提供相应的代码示例,帮助读者提升模型的训练效果,保证模型性能。
当你在 PyTorch 中训练二分类模型时,可能会遇到模型准确率始终很低,甚至接近随机猜测的情况。这通常表明模型训练过程中存在问题。下面列出一些常见的原因和相应的调试方法:
精度计算错误
这是最常见的问题之一。在提供的代码中,准确率的计算方式存在错误。原始代码使用 torch.sum(predictions_binary == test_Y) / (len(test_Y) * 100),这导致计算结果被错误地缩小了 100 倍。正确的计算方式应该先计算预测正确的样本数量,然后除以总样本数,最后乘以 100 得到百分比。
with torch.no_grad():
model.eval()
predictions = model(test_X).squeeze()
predictions_binary = (predictions.round())
accuracy = torch.sum(predictions_binary == test_Y).item() / predictions.size(0) * 100
print("Test accuracy is {:.2f}%".format(accuracy))注意:
数据类型不匹配
PyTorch 中的张量需要具有匹配的数据类型才能进行比较和计算。确保你的预测结果 predictions_binary 和真实标签 test_Y 具有相同的数据类型。如果数据类型不一致,可能会导致比较结果错误,从而影响准确率的计算。
predictions_binary = (predictions.round()).long() # 或者 .int(),取决于 test_Y 的类型 test_Y = test_Y.long() # 确保 test_Y 也是 long 类型
梯度消失或爆炸
如果你的网络很深,可能会遇到梯度消失或梯度爆炸的问题。这会导致模型无法有效地学习。可以尝试以下方法来缓解这个问题:
过拟合
如果你的模型在训练集上表现很好,但在测试集上表现很差,那么可能是过拟合了。可以尝试以下方法来缓解过拟合:
标签错误
检查你的标签数据是否正确。如果标签数据存在错误,模型将无法正确学习。可以使用数据可视化技术来检查标签数据。
下面是修正后的 PyTorch 代码示例,包含了精度计算和数据类型匹配的修正:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
# 假设 data 已经加载,并转换为 numpy 数组
data = np.random.rand(1000, 5) # 示例数据
data[:, -1] = np.random.randint(0, 2, size=1000) # 最后一列作为标签
# 数据预处理
train, test = train_test_split(data, test_size=0.056)
train_X = train[:, :-1]
test_X = test[:, :-1]
train_Y = train[:, -1]
test_Y = test[:, -1]
train_X = torch.tensor(train_X, dtype=torch.float32)
test_X = torch.tensor(test_X, dtype=torch.float32)
train_Y = torch.tensor(train_Y, dtype=torch.float32).view(-1, 1)
test_Y = torch.tensor(test_Y, dtype=torch.float32) .view(-1, 1)
batch_size = 64
train_dataset = TensorDataset(train_X, train_Y)
test_dataset = TensorDataset(test_X, test_Y)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
class SimpleClassifier(nn.Module):
def __init__(self, input_size, hidden_size1, hidden_size2, output_size):
super(SimpleClassifier, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size1)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(hidden_size1, hidden_size2)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(hidden_size2, output_size)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu1(self.fc1(x))
x = self.relu2(self.fc2(x))
x = self.sigmoid(self.fc3(x))
return x
input_size = train_X.shape[1]
hidden_size1 = 64
hidden_size2 = 32
output_size = 1
model = SimpleClassifier(input_size, hidden_size1, hidden_size2, output_size)
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
num_epochs = 50
for epoch in range(num_epochs):
model.train()
for inputs, labels in train_dataloader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Evaluation on the test set
with torch.no_grad():
model.eval()
predictions = model(test_X).squeeze()
predictions_binary = (predictions.round())
correct_predictions = (predictions_binary == test_Y.squeeze()).sum().item()
total_samples = test_Y.size(0)
accuracy = correct_predictions / total_samples * 100
if(epoch%25 == 0):
print("Epoch " + str(epoch) + " passed. Test accuracy is {:.2f}%".format(accuracy))总结
在 PyTorch 中训练二分类模型时,如果遇到准确率异常低的问题,首先检查精度计算方式和数据类型是否匹配。如果问题仍然存在,可以尝试调整网络结构、优化器参数、以及使用正则化等方法来提高模型的性能。通过仔细地调试和分析,可以找到问题的根源,并最终获得一个高性能的二分类模型。
以上就是PyTorch 二分类模型准确率异常低的调试与优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号