pytorch生成一个基于resnet50的图像分类模型训练代码
时间: 2024-01-21 16:04:25 浏览: 84
好的,以下是基于PyTorch训练基于ResNet50的图像分类模型的代码:
```python
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torchvision.models.resnet import resnet50
# 定义超参数
num_epochs = 10
batch_size = 32
learning_rate = 0.001
# 加载数据集并进行预处理
transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor()
])
train_dataset = ImageFolder('train/', transform=transform)
test_dataset = ImageFolder('test/', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型和损失函数
model = resnet50(pretrained=True)
model.fc = nn.Linear(model.fc.in_features, 2) # 全连接层的输出为2(前景和背景)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播并优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 20 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))
```
希望这个代码能对你有所帮助!
阅读全文