请帮我写出基于pytorch resnet实现图片2分类的代码
时间: 2023-11-03 21:04:14 浏览: 156
好的,以下是一个简单的基于PyTorch实现图片2分类的代码,使用的是ResNet18模型:
```python
import torch
import torch.nn as nn
import torchvision.models as models
# 定义ResNet18模型
class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.resnet18 = models.resnet18(pretrained=True)
self.fc = nn.Linear(1000, 2) # 全连接层,输出2类
def forward(self, x):
x = self.resnet18(x)
x = self.fc(x)
return x
# 训练函数
def train(model, train_loader, criterion, optimizer):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
return running_loss / len(train_loader)
# 测试函数
def test(model, test_loader, criterion):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print('Accuracy of the network on the test images: %d %%' % (accuracy))
return accuracy
# 主函数
if __name__ == '__main__':
# 加载数据集,这里假设使用的是torchvision.datasets.ImageFolder
train_dataset = torchvision.datasets.ImageFolder('train', transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=4, shuffle=True, num_workers=2)
test_dataset = torchvision.datasets.ImageFolder('test', transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=4, shuffle=False, num_workers=2)
# 定义模型、损失函数和优化器
model = ResNet18()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练和测试
for epoch in range(10):
train_loss = train(model, train_loader, criterion, optimizer)
test_accuracy = test(model, test_loader, criterion)
print('Epoch: %d, Training Loss: %.3f, Test Accuracy: %.3f' % (epoch + 1, train_loss, test_accuracy))
```
需要注意的是,这只是一个简单的示例代码,具体实现还需要根据数据集和应用场景进行相应的修改和调整。
阅读全文