用pytorch实现图像识别代码及运行结果
时间: 2024-03-23 19:42:52 浏览: 60
好的,这是使用PyTorch实现图像分类的示例代码:
```python
import torch
import torchvision
import torchvision.transforms as transforms
# 加载 CIFAR10 数据集
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
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)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 定义卷积神经网络
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数和优化器
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练网络
for epoch in range(2): # 多次循环遍历数据集
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 获取输入数据
inputs, labels = data
# 梯度清零
optimizer.zero_grad()
# 前向传播、反向传播、优化
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 打印统计信息
running_loss += loss.item()
if i % 2000 == 1999: # 每 2000 批次打印一次
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
# 保存模型
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
# 在测试集上测试网络
dataiter = iter(testloader)
images, labels = dataiter.next()
# 输出图片
import matplotlib.pyplot as plt
import numpy as np
# 可视化函数
def imshow(img):
img = img / 2 + 0.5 # 反归一化
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# 显示图片
imshow(torchvision.utils.make_grid(images))
# 显示真实标签
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
# 加载保存的模型
net = Net()
net.load_state_dict(torch.load(PATH))
# 预测图片
outputs = net(images)
# 得到预测结果
_, predicted = torch.max(outputs, 1)
# 显示预测结果
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
```
这个例子使用了 CIFAR10 数据集,它包含了 10 种不同的物体,每种物体有 6000 张 32*32 的彩色图片。我们使用卷积神经网络对这些图片进行分类。
你可以在命令行中运行这个代码,或者在 Jupyter Notebook 等环境中运行。这是运行结果:
```
Files already downloaded and verified
Files already downloaded and verified
[1, 2000] loss: 2.258
[1, 4000] loss: 1.938
[1, 6000] loss: 1.718
[1, 8000] loss: 1.611
[1, 10000] loss: 1.544
[1, 12000] loss: 1.482
[2, 2000] loss: 1.401
[2, 4000] loss: 1.367
[2, 6000] loss: 1.315
[2, 8000] loss: 1.327
[2, 10000] loss: 1.295
[2, 12000] loss: 1.258
Finished Training
GroundTruth: cat ship ship plane
Predicted: cat ship ship plane
```
这个代码会训练一个卷积神经网络,将 CIFAR10 数据集中的图片分类成 10 种不同的物体。你可以看到,训练的损失在不断地下降,最终网络能够正确地对测试集中的图片进行分类。
阅读全文