resnet18网络结构,举一个利用resnet18网络进行图像分类的python代码示例
时间: 2023-08-04 07:27:48 浏览: 111
好的,这是一个使用PyTorch框架和resnet18网络进行图像分类的示例代码:
```python
import torch
import torch.nn as nn
import torchvision.models as models
# 加载预训练的ResNet18模型
resnet18 = models.resnet18(pretrained=True)
# 冻结模型的所有参数
for param in resnet18.parameters():
param.requires_grad = False
# 替换最后一层全连接层,将输出类别数改为10
num_classes = 10
resnet18.fc = nn.Linear(resnet18.fc.in_features, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(resnet18.fc.parameters(), lr=0.001)
# 加载数据集并进行训练
# 这里使用的是CIFAR10数据集,可以根据需要替换为其他数据集
train_dataset = ...
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
for epoch in range(10):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = resnet18(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, 10, i+1, len(train_loader), loss.item()))
# 对测试集进行评估
test_dataset = ...
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False)
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = resnet18(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: {} %'.format(100 * correct / total))
```
这个代码示例加载了预训练的ResNet18模型,并将其用于对CIFAR10数据集中的图像进行分类。在训练过程中,只更新全连接层的权重,而将卷积层的权重保持不变。最后,使用测试集对模型进行评估,输出其在测试集上的准确率。
阅读全文