04_Pytorch生态、PyTorch能做什么、PyTorch之Autograd、autograd案例、GPU加速案例
1.4.初見PyTorch
1.4.1.PyTorch生態
1.4.2.PyTorch能做什么?
?GPU加速
?自動求導
?常用網絡層
1.4.3.PyTorch之Autograd
以下部分來自:https://www.cnblogs.com/xueqiuqiu/p/7513721.html
在PyTorch中,autograd是所有神經網絡的核心內容,為Tensor所有操作提供自動求導方法。
它是一個按運行方式定義的框架,這意味著backprop是由代碼的運行方式定義的。
1.4.3.1.Variable
autograd.Variable是autograd中最核心的類。它包裝了一個Tensor,并且幾乎支持所有在其上定義的操作。一旦完成了你的運算,你可以調用.backward()來自動計算出所有的梯度。
Variable有三個屬性:data , grad以及creator。
訪問原始的tensor使用屬性.data; 關于這一Variable的梯度則集中于 .grad; .creator反映了創建者,標識了是否由用戶使用.Variable直接創建(None)。
還有一個對autograd的實現非常重要的類—Function。Variable和Function數是相互關聯的,并建立一個非循環圖,從而編碼完整的計算過程。每個變量都有一個.grad_fn屬性引用創建變量的函數(除了用戶創建的變量,它們的grad_fn是None)。
創建變量X:
x = Variable(torch.ones(2, 2), requires_grad=True) print(x)輸出結果:
tensor([[1., 1.],[1., 1.]], requires_grad=True)在X基礎上進行運算:
y = x + 2 print(y)輸出結果:
tensor([[3., 3.],[3., 3.]], grad_fn=<AddBackward0>)查看x的grad_fn:
print(x.grad_fn)
輸出結果為:
None
查看y的grad_fn:
print(y.grad_fn)輸出結果為:
<AddBackward0 object at 0x000001BA69C73E48>可以看到y是作為運算的結果產生的,所以y有grad_fn,而x是直接創建的,所以x沒有grad_fn。
在y基礎上進行運算:
z = y * y * 3 #前兩個相當于是矩陣相乘 out = z.mean() print(z) print(out)輸出結果為:
tensor([[27., 27.], [27., 27.]], grad_fn=<MulBackward0>)tensor(27., grad_fn=<MeanBackward0>)1.4.4.autograd案例
# -*- coding: UTF-8 -*-import torch from torch import autogradx = torch.tensor(1.) a = torch.tensor(1., requires_grad=True) b = torch.tensor(2., requires_grad=True) c = torch.tensor(3., requires_grad=True)y = a**2 * x + b ** 3 * x + cprint('before:', a.grad, b.grad, c.grad) # 分別對a,b,c求導(對某個值進行求導的時候,別的作為常量) grads = autograd.grad(y, [a, b, c]) print('after :', grads[0], grads[1], grads[2]) 運行結果: before: None None None after : tensor(2.) tensor(12.) tensor(1.)1.4.5.GPU加速案例
# -*- coding: UTF-8 -*-import torch import timeprint(torch.__version__) print(torch.cuda.is_available())a = torch.randn(10000, 1000) b = torch.randn(1000, 2000)t0 = time.time() c = torch.matmul(a, b) t1 = time.time() print(a.device, t1 - t0, c.norm(2))# 使用cuda device = torch.device('cuda') a = a.to(device) b = b.to(device)t0 = time.time() c = torch.matmul(a, b) t2 = time.time() print(a.device, t2 - t0, c.norm(2))t0 = time.time() c = torch.matmul(a, b) t2 = time.time() print(a.device, t2 - t0, c.norm(2))總結
以上是生活随笔為你收集整理的04_Pytorch生态、PyTorch能做什么、PyTorch之Autograd、autograd案例、GPU加速案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开家自习室怎样 很符合现在年轻人的需要
- 下一篇: 基金如果跌了是加仓还是减仓 需要根据