pytorch猫狗分类写一段代码
时间: 2024-11-06 17:20:19 浏览: 4
基于pytorch的猫狗分类
5星 · 资源好评率100%
在PyTorch中,我们通常会使用深度学习库来进行图像分类任务,例如猫狗分类。这里是一个简单的例子,展示如何使用ResNet18模型对CIFAR-10数据集进行训练。请注意,这只是一个基本框架,实际项目中需要更完整的数据预处理、模型配置等步骤。
```python
# 导入必要的模块
import torch
import torch.nn as nn
from torchvision import datasets, transforms
# 数据加载和预处理
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32, padding=4),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=128, shuffle=True)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=128, shuffle=False)
# 使用预训练的ResNet18模型作为基础网络
model = models.resnet18(pretrained=True)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 2) # 将最后一层改为我们的分类层,这里是2类:猫和狗
# 模型选择GPU运行(如果有可用)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练过程
for epoch in range(10): # 设置几个epoch
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f'Epoch [{epoch+1}/{10}], Loss: {loss.item()}')
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Test Accuracy of the model on the 10000 test images: {100 * correct / total}%')
```
阅读全文