基于ResNet18残差网络完成图像分类代码
时间: 2024-03-02 10:53:34 浏览: 114
Residual Attention Network for Image Classification 相关复现代码
好的,以下是基于PyTorch搭建ResNet18模型完成图像分类的代码示例:
```python
import torch
import torch.nn as nn
import torchvision.models as models
# 加载ResNet18模型
resnet18 = models.resnet18(pretrained=False)
# 替换最后一层全连接层
num_features = resnet18.fc.in_features
resnet18.fc = nn.Linear(num_features, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(resnet18.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
for images, labels in train_loader:
# 将数据加载到GPU上
images, labels = images.to(device), labels.to(device)
# 前向传播
outputs = resnet18(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每个epoch结束后计算模型在验证集上的准确率
with torch.no_grad():
correct = 0
total = 0
for images, labels in val_loader:
images, labels = images.to(device), labels.to(device)
outputs = resnet18(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print('Epoch [{}/{}], Accuracy: {:.2f}%'.format(epoch+1, num_epochs, accuracy))
```
在上述代码中,我们首先加载了ResNet18模型,并替换了最后一层全连接层以适应我们的分类任务。然后定义了损失函数和优化器,并在每个epoch结束后计算模型在验证集上的准确率。在训练过程中,我们对训练集进行迭代,每次迭代都进行前向传播、反向传播和优化操作,直至达到预设的epoch数。
阅读全文