在CentOS上评估PyTorch模型的效果,通常涉及以下几个步骤:
准备数据集:
加载模型:
.pth
或.pt
文件。设置模型为评估模式:
model.eval()
来实现。处理数据:
进行预测:
计算评估指标:
分析结果:
下面是一个简单的示例代码,展示了如何在CentOS上使用PyTorch评估一个分类模型的效果:
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from your_model import YourModel # 假设你的模型定义在这个文件中
from sklearn.metrics import accuracy_score, classification_report
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 加载评估数据集
transform = transforms.Compose([
# 定义你的数据预处理操作
])
test_dataset = datasets.YourDataset(root='path/to/your/test/data', transform=transform)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 加载模型
model = YourModel() # 假设你的模型类定义在这个文件中
model.load_state_dict(torch.load('path/to/your/model.pth'))
model.to(device)
model.eval()
# 进行预测并计算评估指标
predictions = []
true_labels = []
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
predictions.extend(predicted.cpu().numpy())
true_labels.extend(labels.cpu().numpy())
# 计算准确率
accuracy = accuracy_score(true_labels, predictions)
print(f'Accuracy: {accuracy:.2f}')
# 打印分类报告
print(classification_report(true_labels, predictions))
请根据你的具体情况调整上述代码,例如数据集路径、模型定义、预处理操作等。