时间:2021-05-22
步骤如下:
1.使用torchvision加载并预处理CIFAR-10数据集、
2.定义网络
3.定义损失函数和优化器
4.训练网络并更新网络参数
5.测试网络
运行环境:
windows+python3.6.3+pycharm+pytorch0.3.0import torchvision as tvimport torchvision.transforms as transformsimport torch as tfrom torchvision.transforms import ToPILImageshow=ToPILImage() #把Tensor转成Image,方便可视化import matplotlib.pyplot as pltimport torchvisionimport numpy as np###############数据加载与预处理transform = transforms.Compose([transforms.ToTensor(),#转为tensor transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)),#归一化 ])#训练集trainset=tv.datasets.CIFAR10(root='/python projects/test/data/', train=True, download=True, transform=transform)trainloader=t.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=0)#测试集testset=tv.datasets.CIFAR10(root='/python projects/test/data/', train=False, download=True, transform=transform)testloader=t.utils.data.DataLoader(testset, batch_size=4, shuffle=True, num_workers=0)classes=('plane','car','bird','cat','deer','dog','frog','horse','ship','truck')(data,label)=trainset[100]print(classes[label])show((data+1)/2).resize((100,100))# dataiter=iter(trainloader)# images,labels=dataiter.next()# print(''.join('11%s'%classes[labels[j]] for j in range(4)))# show(tv.utils.make_grid(images+1)/2).resize((400,100))def imshow(img): img = img / 2 + 0.5 npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0)))dataiter = iter(trainloader)images, labels = dataiter.next()print(images.size())imshow(torchvision.utils.make_grid(images))plt.show()#关掉图片才能往后继续算#########################定义网络import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super(Net,self).__init__() self.conv1=nn.Conv2d(3,6,5) 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 = F.max_pool2d(F.relu(self.conv1(x)),2) x = F.max_pool2d(F.relu(self.conv2(x)),2) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet=Net()print(net)#############定义损失函数和优化器from torch import optimcriterion=nn.CrossEntropyLoss()optimizer=optim.SGD(net.parameters(),lr=0.01,momentum=0.9)##############训练网络from torch.autograd import Variableimport timestart_time = time.time()for epoch in range(2): running_loss=0.0 for i,data in enumerate(trainloader,0): #输入数据 inputs,labels=data inputs,labels=Variable(inputs),Variable(labels) #梯度清零 optimizer.zero_grad() outputs=net(inputs) loss=criterion(outputs,labels) loss.backward() #更新参数 optimizer.step() # 打印log running_loss += loss.data[0] if i % 2000 == 1999: print('[%d,%5d] loss:%.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('finished training')end_time = time.time()print("Spend time:", end_time - start_time)以上这篇利用pytorch实现对CIFAR-10数据集的分类就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
pytorch之ImageFoldertorchvision已经预先实现了常用的Dataset,包括前面使用过的CIFAR-10,以及ImageNet、COCO
Tebsorflow开源实现多GPU训练cifar10数据集:cifar10_multi_gpu_train.pyTensorflow开源实现cifar10神经
前言在tensorflow的官方文档中得卷积神经网络一章,有一个使用cifar-10图片数据集的实验,搭建卷积神经网络倒不难,但是那个cifar10_input
pytorch在torchvision包里面有很多的的打包好的数据集,例如minist,Imagenet-12,CIFAR10和CIFAR100。在torchv
模型VGG,数据集cifar。对照这份代码走一遍,大概就知道整个pytorch的运行机制。来源定义模型:'''VGG11/13/16/19inPytorch.'