使用pytorch猫狗
时间: 2023-10-24 12:12:47 浏览: 70
基于pytorch的猫狗分类
5星 · 资源好评率100%
要使用 PyTorch 进行猫狗分类,首先需要收集猫狗图片数据集,然后对数据集进行预处理和划分。接下来,可以使用 PyTorch 的 torchvision 库来加载数据集,构建模型,定义损失函数和优化器,以及进行模型训练和评估。
以下是一个简单的猫狗分类示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 定义数据集路径和预处理操作
data_path = "/path/to/dataset"
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# 加载训练集和测试集数据
train_dataset = torchvision.datasets.ImageFolder(
root=data_path + "/train",
transform=transform
)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=32,
shuffle=True,
num_workers=4
)
test_dataset = torchvision.datasets.ImageFolder(
root=data_path + "/test",
transform=transform
)
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=32,
shuffle=False,
num_workers=4
)
# 定义模型
model = torchvision.models.resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 评估模型
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
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('Accuracy of the network on the test images: %d %%' % (
100 * correct / total))
```
在这个示例中,我们使用了 ResNet-18 模型进行分类,使用交叉熵损失函数和随机梯度下降优化器进行训练。通过运行 10 个 epoch,我们可以得到一个简单的猫狗分类器。
阅读全文