python gpu加速 显卡_PyTorch-GPU加速实例
硬件:NVIDIA-GTX1080
軟件:Windows7、python3.6.5、pytorch-gpu-0.4.1
一、基礎知識
將數據和網絡都推到GPU,接上.cuda()
二、代碼展示
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
# torch.manual_seed(1)
EPOCH = 1
BATCH_SIZE = 50
LR = 0.001
DOWNLOAD_MNIST = False
train_data = torchvision.datasets.MNIST(root='./mnist/', train=True, transform=torchvision.transforms.ToTensor(), download=DOWNLOAD_MNIST,)
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
# !!!!!!!! Change in here !!!!!!!!! #
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000].cuda()/255. # Tensor on GPU
test_y = test_data.test_labels[:2000].cuda()
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2,),
nn.ReLU(), nn.MaxPool2d(kernel_size=2),)
self.conv2 = nn.Sequential(nn.Conv2d(16, 32, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2),)
self.out = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1)
output = self.out(x)
return output
cnn = CNN()
# !!!!!!!! Change in here !!!!!!!!! #
cnn.cuda() # Moves all model parameters and buffers to the GPU.
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()
for epoch in range(EPOCH):
for step, (x, y) in enumerate(train_loader):
# !!!!!!!! Change in here !!!!!!!!! #
b_x = x.cuda() # Tensor on GPU
b_y = y.cuda() # Tensor on GPU
output = cnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
test_output = cnn(test_x)
# !!!!!!!! Change in here !!!!!!!!! #
pred_y = torch.max(test_output, 1)[1].cuda().data # move the computation in GPU
accuracy = torch.sum(pred_y == test_y).type(torch.FloatTensor) / test_y.size(0)
print('Epoch: ', epoch, '| train loss: %.4f' % loss, '| test accuracy: %.2f' % accuracy)
test_output = cnn(test_x[:10])
# !!!!!!!! Change in here !!!!!!!!! #
pred_y = torch.max(test_output, 1)[1].cuda().data # move the computation in GPU
print(pred_y, 'prediction number')
print(test_y[:10], 'real number')
三、結果展示
補充知識:pytorch使用gpu對網絡計算進行加速
1.基本要求
你的電腦里面有合適的GPU顯卡(NVIDA),并且需要支持CUDA模塊
你必須安裝GPU版的Torch,(詳細安裝方法請移步pytorch官網)
2.使用GPU訓練CNN
利用pytorch使用GPU進行加速方法主要就是將數據的形式變成GPU能讀的形式,然后將CNN也變成GPU能讀的形式,具體辦法就是在后面加上.cuda()。
例如:
#如何檢查自己電腦是否支持cuda
print torch.cuda.is_available()
# 返回True代表支持,False代表不支持
'''
注意在進行某種運算的時候使用.cuda()
'''
test_data=test_data.test_labels[:2000].cuda()
'''
對于CNN與損失函數利用cuda加速
'''
class CNN(nn.Module):
...
cnn=CNN()
cnn.cuda()
loss_f = t.nn.CrossEntropyLoss()
loss_f = loss_f.cuda()
而在train時,對于train_data訓練過程進行GPU加速。也同樣+.cuda()。
for epoch ..:
for step, ...:
1
'''
若你的train_data在訓練時需要進行操作
若沒有其他操作僅僅只利用cnn()則無需另加.cuda()
'''
#eg
train_data = torch.max(teain_data, 1)[1].cuda()
補充:取出數據需要從GPU切換到CPU上進行操作
eg:
loss = loss.cpu()
acc = acc.cpu()
理解并不全,如有紕漏或者錯誤還望各位大佬指點迷津
以上這篇PyTorch-GPU加速實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持python博客。
總結
以上是生活随笔為你收集整理的python gpu加速 显卡_PyTorch-GPU加速实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pythonenumapi_Python
- 下一篇: python watchdog 同时检测