pytorch实现VGG19
时间: 2023-08-01 22:09:51 浏览: 153
PyTorch可以使用预训练的VGG16模型来进行图片识别。以下是实现步骤:
1. 导入必要的库和模块:
```
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
```
2. 加载数据集并进行预处理:
```
transform = transforms.Compose(
[transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[.485, .456, .406],
std=[.229, .224, .225])])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
```
3. 加载预训练的VGG16模型:
```
vgg16 = torchvision.models.vgg16(pretrained=True)
```
4. 修改模型的最后一层,使其适应于CIFAR10数据集:
```
vgg16.classifier[6] = nn.Linear(4096, 10)
```
5. 定义损失函数和优化器:
```
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(vgg16.parameters(), lr=.001, momentum=.9)
```
6. 训练模型:
```
for epoch in range(2): # 进行2个epoch的训练
running_loss = .
for i, data in enumerate(trainloader, ):
# 获取输入数据
inputs, labels = data
# 梯度清零
optimizer.zero_grad()
# 前向传播、反向传播、优化
outputs = vgg16(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 统计损失值
running_loss += loss.item()
if i % 200 == 1999: # 每200个batch输出一次损失值
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 200))
running_loss = .
print('Finished Training')
```
7. 测试模型:
```
correct =
total =
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = vgg16(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size()
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
以上就是使用PyTorch实现VGG16图片识别的步骤。
阅读全文