pytorch如何使用GPU
在本文中,我將介紹簡單如何使用GPU
pytorch是一個非常優秀的深度學習的框架,具有速度快,代碼簡潔,可讀性強的優點。
我們使用pytorch做一個簡單的回歸。
首先准備數據
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import torch.nn as nn
x = np.random.randn(1000, 1)*4
w = np.array([0.5,])
bias = -1.68
y_true = np.dot(x, w) + bias #真實數據
y = y_true + np.random.randn(x.shape[0])#加噪聲的數據
#我們需要使用x和y,以及y_true回歸出w和bias
1
2
3
4
5
6
7
8
9
10
11
12
定義回歸網絡的類
class LinearRression(nn.Module):
def __init__(self, input_size, out_size):
super(LinearRression, self).__init__()
self.x2o = nn.Linear(input_size, out_size)
#初始化
def forward(self, x):
return self.x2o(x)
#前向傳遞
1
2
3
4
5
6
7
8
接下來介紹將定義模型和優化器
batch_size = 10
model = LinearRression(1, 1)#回歸模型
criterion = nn.MSELoss() #損失函數
#調用cuda
model.cuda()
criterion.cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
losses = []
1
2
3
4
5
6
7
8
9
下面就是訓(練)練(丹)了
for i in range(epoches):
loss = 0
optimizer.zero_grad()#清空上一步的梯度
idx = np.random.randint(x.shape[0], size=batch_size)
batch_cpu = Variable(torch.from_numpy(x[idx])).float()
batch = batch_cpu.cuda()#很重要
target_cpu = Variable(torch.from_numpy(y[idx])).float()
target = target_cpu.cuda()#很重要
output = model.forward(batch)
loss += criterion(output, target)
loss.backward()
optimizer.step()
if (i +1)%10 == 0:
print('Loss at epoch[%s]: %.3f' % (i, loss.data[0]))
losses.append(loss.data[0])
plt.plot(losses, '-or')
plt.xlabel("Epoch")
plt.xlabel("Loss")
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
下面是訓練結果
Loss at epoch[9]: 5.407
Loss at epoch[19]: 3.795
Loss at epoch[29]: 2.352
Loss at epoch[39]: 1.725
Loss at epoch[49]: 1.722
Loss at epoch[59]: 1.044
Loss at epoch[69]: 1.044
Loss at epoch[79]: 0.771
Loss at epoch[89]: 1.248
Loss at epoch[99]: 1.862
1
2
3
4
5
6
7
8
9
10
總結一下。要調用cuda執行代碼需要一下步驟
model.cuda()
criterion.cuda()
1
2
3
以及
batch_cpu = Variable(torch.from_numpy(x[idx])).float()
batch = batch_cpu.cuda()
target_cpu = Variable(torch.from_numpy(y[idx])).float()
target = target_cpu.cuda()
1
2
3
4
就是將模型和輸入數據變為cuda執行的
,簡直超級方便,良心推薦一波pytorch
---------------------
作者:小川愛學習
來源:CSDN
原文:https://blog.csdn.net/wuichuan/article/details/66969315
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!