1.选择运行类型
- 更改运行时类型
- 查看分配到的GPU
!/opt/bin/nvidia-smi
2.连接Google Drive
from google.colab import drive
drive.mount('/content/drive/')
-
点击链接
-
连接成功
3.配置查看
- python
! python --version
- Cuda
! nvcc --version
4.测试
- pytorch深度学习框架
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.utils.data as Data
import matplotlib.pyplot as plt
# Hyper Parameters
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
# MNIST Dataset
train_dataset = dsets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = dsets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor())
# Data Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
test_y=test_dataset.targets
# Neural Network Model (1 hidden layer)
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
net = Net(input_size, hidden_size, num_classes)
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
# Train the Model
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Convert torch tensor to Variable
images = Variable(images.view(-1, 28*28))
labels = Variable(labels)
# Forward + Backward + Optimize
optimizer.zero_grad() # zero the gradient buffer
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f'
%(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.item()))
# Test the Model
correct = 0
total = 0
for images, labels in test_loader:
images = Variable(images.view(-1, 28*28))
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
# Save the Model
for i in range(1,4):
plt.imshow(train_dataset.data[i].numpy(), cmap='gray')
plt.title('%i' % train_dataset.targets[i])
plt.show()
torch.save(net.state_dict(), 'model.pkl')
test_output = net(images[:20])
pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
print('prediction number',pred_y)
print(' real number',test_y[:20].numpy())
Epoch [1/5], Step [100/600], Loss: 0.3598
Epoch [1/5], Step [200/600], Loss: 0.3726
Epoch [1/5], Step [300/600], Loss: 0.2781
Epoch [1/5], Step [400/600], Loss: 0.1206
Epoch [1/5], Step [500/600], Loss: 0.1357
Epoch [1/5], Step [600/600], Loss: 0.0890
Epoch [2/5], Step [100/600], Loss: 0.0708
Epoch [2/5], Step [200/600], Loss: 0.1120
Epoch [2/5], Step [300/600], Loss: 0.0501
Epoch [2/5], Step [400/600], Loss: 0.1040
Epoch [2/5], Step [500/600], Loss: 0.1595
Epoch [2/5], Step [600/600], Loss: 0.0892
Epoch [3/5], Step [100/600], Loss: 0.1311
Epoch [3/5], Step [200/600], Loss: 0.0346
Epoch [3/5], Step [300/600], Loss: 0.0387
Epoch [3/5], Step [400/600], Loss: 0.1334
Epoch [3/5], Step [500/600], Loss: 0.1118
Epoch [3/5], Step [600/600], Loss: 0.0246
Epoch [4/5], Step [100/600], Loss: 0.0488
Epoch [4/5], Step [200/600], Loss: 0.0776
Epoch [4/5], Step [300/600], Loss: 0.0255
Epoch [4/5], Step [400/600], Loss: 0.0419
Epoch [4/5], Step [500/600], Loss: 0.0815
Epoch [4/5], Step [600/600], Loss: 0.0220
Epoch [5/5], Step [100/600], Loss: 0.0271
Epoch [5/5], Step [200/600], Loss: 0.0281
Epoch [5/5], Step [300/600], Loss: 0.0397
Epoch [5/5], Step [400/600], Loss: 0.0790
Epoch [5/5], Step [500/600], Loss: 0.0731
Epoch [5/5], Step [600/600], Loss: 0.1081
Accuracy of the network on the 10000 test images: 97 %
prediction number [8 9 0 1 0 3 4 5 6 7 8 0 1 2 3 4 7 8 9 7]
real number [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4]