×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Python
Posted by: Elon Lin
Added: Dec 28, 2017 2:14 PM
Modified: Dec 28, 2017 2:41 PM
Views: 4
Tags: no tags
定义一个神经网络,使用CIFAR10数据集。 我们要进行的分类的类别有:'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'。 这个数据集中的图像都是3通道,32x32像素的图片。

来源于 : https://zhuanlan.zhihu.com/p/25572330
  1. # 获得输入数据
  2. import torchvision
  3. import torchvision.transforms as transforms
  4.  
  5. # torchvision数据集的输出是在[0, 1]范围内的PILImage图片。
  6. # 我们此处使用归一化的方法将其转化为Tensor,数据范围为[-1, 1]
  7.  
  8. transform=transforms.Compose([transforms.ToTensor(),
  9.                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
  10.                              ])
  11. trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
  12. trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
  13.                                           shuffle=True, num_workers=2)
  14.  
  15. testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
  16. testloader = torch.utils.data.DataLoader(testset, batch_size=4,
  17.                                           shuffle=False, num_workers=2)
  18. classes = ('plane', 'car', 'bird', 'cat',
  19.            'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
  20.  
  21. # link start...
  22.  
  23. import torch.nn as nn
  24. import torch.nn.functional as F
  25.  
  26. # 定义一个卷积神经网络
  27. class Net(nn.Module):
  28.     def __init__(self):
  29.         super(Net, self).__init__()
  30.         self.conv1 = nn.Conv2d(3, 6, 5)
  31.         self.pool  = nn.MaxPool2d(2,2)
  32.         self.conv2 = nn.Conv2d(6, 16, 5)
  33.         self.fc1   = nn.Linear(16*5*5, 120)
  34.         self.fc2   = nn.Linear(120, 84)
  35.         self.fc3   = nn.Linear(84, 10)
  36.  
  37.     def forward(self, x):
  38.         x = self.pool(F.relu(self.conv1(x)))
  39.         x = self.pool(F.relu(self.conv2(x)))
  40.         x = x.view(-1, 16*5*5)
  41.         x = F.relu(self.fc1(x))
  42.         x = F.relu(self.fc2(x))
  43.         x = self.fc3(x)
  44.         return x
  45.  
  46. net = Net()
  47.  
  48. #定义代价函数和优化器
  49. criterion = nn.CrossEntropyLoss() # use a Classification Cross-Entropy loss
  50. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
  51.  
  52. #训练网络
  53. # 我们只需一轮一轮迭代然后不断通过输入来进行参数调整就行了
  54. for epoch in range(2): # loop over the dataset multiple times
  55.    
  56.     running_loss = 0.0
  57.     for i, data in enumerate(trainloader, 0):
  58.         # get the inputs
  59.         inputs, labels = data
  60.        
  61.         # wrap them in Variable
  62.         inputs, labels = Variable(inputs), Variable(labels)
  63.        
  64.         # zero the parameter gradients
  65.         optimizer.zero_grad()
  66.        
  67.         # forward + backward + optimize
  68.         outputs = net(inputs)
  69.         loss = criterion(outputs, labels)
  70.         loss.backward()        
  71.         optimizer.step()
  72.        
  73.         # print statistics
  74.         running_loss += loss.data[0]
  75.         if i % 2000 == 1999: # print every 2000 mini-batches
  76.             print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss / 2000))
  77.             running_loss = 0.0
  78. print('Finished Training')