pytorch猫狗分类
时间: 2023-05-23 08:05:41 浏览: 192
基于resnet50和vgg16网络pytorch框架实现猫狗分类-源码
4星 · 用户满意度95%
A:要使用PyTorch进行猫狗分类,可以使用以下步骤:
1. 导入必要的库和模块:
```python
import torch
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from torchvision.transforms import Compose, Resize, ToTensor, Normalize
from torchvision.datasets import ImageFolder
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
```
2. 定义训练、验证、测试数据集的数据预处理:
```python
# 数据预处理
transform = Compose([
Resize((128, 128)), # 将图片调整为指定大小
ToTensor(), # 将图片转为Tensor格式
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 标准化
])
```
3. 加载数据集:
```python
# 数据集路径
TRAIN_PATH = './train/'
VAL_PATH = './val/'
TEST_PATH = './test/'
# 获取训练、验证、测试集
train_dataset = ImageFolder(TRAIN_PATH, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=4)
val_dataset = ImageFolder(VAL_PATH, transform=transform)
val_loader = DataLoader(val_dataset, batch_size=64, shuffle=False, num_workers=4)
test_dataset = ImageFolder(TEST_PATH, transform=transform)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=4)
```
4. 定义模型:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(128 * 16 * 16, 512)
self.fc2 = nn.Linear(512, 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = x.view(-1, 128 * 16 * 16)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
```
5. 训练模型:
```python
# 定义训练函数
def train(model, loader, criterion, optimizer, device):
model.train()
running_loss = 0.0
correct = 0
total = 0
for inputs, labels in loader:
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() * inputs.size(0)
_, predicted = outputs.max(1)
correct += predicted.eq(labels).sum().item()
total += labels.size(0)
train_loss = running_loss / total
train_acc = correct / total
return train_loss, train_acc
# 定义验证函数
def validate(model, loader, criterion, device):
model.eval()
running_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
running_loss += loss.item() * inputs.size(0)
_, predicted = outputs.max(1)
correct += predicted.eq(labels).sum().item()
total += labels.size(0)
val_loss = running_loss / total
val_acc = correct / total
return val_loss, val_acc
# 训练模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for epoch in range(10):
train_loss, train_acc = train(model, train_loader, criterion, optimizer, device)
val_loss, val_acc = validate(model, val_loader, criterion, device)
print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Val Loss: {:.4f}, Val Acc: {:.4f}'
.format(epoch+1, 10, train_loss, train_acc, val_loss, val_acc))
```
6. 测试模型:
```python
# 测试模型
def test(model, loader, device):
model.eval()
running_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
running_loss += loss.item() * inputs.size(0)
_, predicted = outputs.max(1)
correct += predicted.eq(labels).sum().item()
total += labels.size(0)
test_loss = running_loss / total
test_acc = correct / total
return test_loss, test_acc
test_loss, test_acc = test(model, test_loader, device)
print('Test Loss: {:.4f}, Test Acc: {:.4f}'.format(test_loss, test_acc))
```
以上就是使用PyTorch进行猫狗分类的简单实现。
阅读全文