用pytorch做CNN的新冠肺炎患者图像分类代码
时间: 2025-01-02 07:44:43 浏览: 7
在PyTorch中,做新冠病毒(COVID-19)患者图像分类通常涉及到深度学习,特别是卷积神经网络(Convolutional Neural Networks,简称CNN)。以下是一个基本的步骤概述:
```python
# 首先,确保安装了必要的库
import torch
import torchvision
import torchvision.transforms as transforms
# 数据预处理
data_transforms = {
'train': transforms.Compose([
transforms.Resize((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
]),
'val': transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
])
}
# 加载数据集,例如从Covid Chest X-ray dataset
train_dataset = torchvision.datasets.CxrDataset(
root='./data', train=True, transform=data_transforms['train'])
val_dataset = torchvision.datasets.CxrDataset(
root='./data', train=False, transform=data_transforms['val'])
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=32)
# 定义CNN模型,如ResNet、VGG等
import torchvision.models as models
model = models.resnet18(pretrained=True) # 使用预训练的模型作为基础
num_classes = len(train_dataset.classes) # 确定类别数
model.fc = torch.nn.Linear(model.fc.in_features, num_classes) # 修改最后一层为分类层
# 损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练过程
for epoch in range(num_epochs):
for inputs, labels in train_loader:
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad() # 清零梯度
loss.backward() # 反向传播
optimizer.step() # 更新参数
# 测试模型
model.eval() # 转换到评估模式
with torch.no_grad():
correct = 0
total = 0
for inputs, labels in val_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"验证集准确率: {correct / total * 100:.2f}%")
#
阅读全文