import torch
import torchvision
import torchvision.transforms as transforms
device = torch.device("cuda:0"if torch.cuda.is_available()else"cpu")# Assuming that we are on a CUDA machine, this should print a CUDA device:print(device)
Files already downloaded and verified
Files already downloaded and verified
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# functions to show an imagedefimshow(img):
img = img /2+0.5# unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg,(1,2,0)))
plt.show()# get some random training images
dataiter =iter(trainloader)
images, labels = dataiter.next()# show images
imshow(torchvision.utils.make_grid(images))# print labelsprint(' '.join('%5s'% classes[labels[j]]for j inrange(4)))
cat ship deer car
import torch.nn as nn
import torch.nn.functional as F
classNet(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)defforward(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()
for epoch inrange(2):# loop over the dataset multiple times
running_loss =0.0for i, data inenumerate(trainloader,0):# get the inputs
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)# zero the parameter gradients
optimizer.zero_grad()# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()# print statistics
running_loss += loss.item()if i %2000==1999:# print every 2000 mini-batchesprint('[%d, %5d] loss: %.3f'%(epoch +1, i +1, running_loss /2000))
running_loss =0.0print('Finished Training')
correct =0
total =0with torch.no_grad():for data in testloader:
images, labels = data
images = images.to(device)
labels = labels.to(device)
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: 53 %
您可能感兴趣的与本文相关的镜像
PyTorch 2.5
PyTorch
Cuda
PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理