pytorch初学图像分类器

本文介绍了一个基于PyTorch实现的CIFAR10数据集上的图像分类任务,包括数据预处理、构建卷积神经网络模型、训练及测试等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

训练一个图像分类器

1.使用torchvision加载和正则化CIFAR10训练集和测试集

2.构造一个CNN

3.构造损失函数

4.训练网络

5.测试网络

1. 加载和正规化CIFAR10

import torch
import torchvision
import torchvision.transforms as transforms
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')
Files already downloaded and verified
Files already downloaded and verified
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()

dataiter = iter(trainloader)
images, labels = dataiter.next()

imshow(torchvision.utils.make_grid(images))
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

在这里插入图片描述

truck   car  bird  ship

2. 定义一个卷积神经网络

import torch.nn as nn
import torch.nn.functional as F

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
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()
net.to(device)
Net(
  (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)

3. 定义损失函数和优化器

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # momentum为动量,解决局部最优解问题

4. 训练CNN


for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # inputs, labels = data # 使用cpu训练
        inputs, labels = data[0].to(device), data[1].to(device) # 使用gpu训练

        optimizer.zero_grad()

        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 2000 == 1999: # 每两千次,计算一下loss的总和,看总体的降低
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
[1,  2000] loss: 2.139
[1,  4000] loss: 1.818
[1,  6000] loss: 1.678
[1,  8000] loss: 1.575
[1, 10000] loss: 1.523
[1, 12000] loss: 1.490
[2,  2000] loss: 1.417
[2,  4000] loss: 1.345
[2,  6000] loss: 1.356
[2,  8000] loss: 1.314
[2, 10000] loss: 1.291
[2, 12000] loss: 1.279
Finished Training
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)

5. 测试网络

dataiter = iter(testloader) # dataload迭代器
images, labels = dataiter.next() 

# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

在这里插入图片描述

GroundTruth:    cat  ship  ship plane
net = Net()
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_, predicted = torch.max(outputs, 1) # dim = 1, 将维度压缩为1
print(outputs) # 每一行代表一个图片的输出值
print(predicted) # 每张图片最大输出值的下边

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))
tensor([[-2.5090, -3.2349,  1.7301,  2.9694,  3.0115,  2.8149,  3.4539,  0.7578,
         -3.6328, -3.4352],
        [-0.8140, -4.5701,  2.3966,  2.8336, -0.1575,  5.3245, -0.4004,  1.8420,
         -3.9213, -2.3566],
        [ 1.6518,  0.1281,  2.1819, -0.2296,  4.1228, -0.2814,  1.4106, -0.8388,
         -2.4360, -3.0393],
        [-1.2521, -3.1468,  0.3812,  0.9961,  4.1565,  1.7851,  0.2695,  6.6411,
         -5.3557, -1.3407]])
tensor([6, 5, 4, 7])
Predicted:   frog   dog  deer horse
correct = 0
total = 0
with torch.no_grad(): # 预测的话不需要计算gradient
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1) 
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))
Accuracy of the network on the 10000 test images: 56 %
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值