使用pytorch 训练分类器

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.optim as optim
#数据集加载完的输出是在[0,1]之间的PILImage,将其标准化为范围在[-1,1]之间的张量 Compose串联多个图片变换的操作
transform=transforms.Compose(
    [transforms.ToTensor(),# 转换为Tensor
     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)# 从pytorch中下载图片数据集
trainloader=torch.utils.data.DataLoader(trainset,batch_size=4,shuffle=True,num_workers=0)# shuffle随机打乱
testset=torchvision.datasets.CIFAR10(root='./data/',train=False,download=True,transform=transform)
testloader=torch.utils.data.DataLoader(testset,batch_size=4,shuffle=True,num_workers=0)# 进程数
classes=('plane','car','bird','cat','deer','dog','frog','horse','ship','truck')


#输出图像的函数
def imshow(img):
    img=img/2+0.5 #不归一化:归一话的时候是先减去平均值0.5 ,然后再除以标准偏差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)))

# 定义一个卷积神经网络
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()
# 定义损失函数:使用多分类的交叉熵损失函数和随机梯度下降优化器
criterion=nn.CrossEntropyLoss()
optimzer=optim.SGD(net.parameters(),lr=0.01,momentum=0.9)
# 引入动量momentum能够使得物体在下落过程中,当遇到一个局部最优的时候有可能在原有动量的基础上冲出这个局部最优点
# 训练网络
for epoch in range(2):# 遍历数据迭代器,将数据喂给网络和优化函数
    running_loss=0.0
    for i,data in enumerate(trainloader,0):
        inputs,labels=data # 获取输入
        optimzer.zero_grad()# 清除梯度
        outputs=net(inputs) #神经网络的输出
        loss=criterion(outputs,labels)
        optimzer.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)
imshow(torchvision.utils.make_grid(images))
print('GroudTruth:',''.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('precited:',''.join('%5s'%classes[predicted[j]]for j in range(4)))
# 判断网络在整个数据集上的表现
correct=0
total=0
with torch.no_grad():
    for data in testloader:
        images,labels=data
        outputs=net(images)
        _, predicted = torch.max( outputs, 1 )
        total+=labels.size(0)
        correct+=(predicted==labels).sum().item()
print('Acc:%d %%'%(100*correct/total))




你可能感兴趣的:(pytorch,pytorch)