日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

04_Pytorch生态、PyTorch能做什么、PyTorch之Autograd、autograd案例、GPU加速案例

發布時間:2024/9/27 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 04_Pytorch生态、PyTorch能做什么、PyTorch之Autograd、autograd案例、GPU加速案例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.4.初見PyTorch

1.4.1.PyTorch生態

1.4.2.PyTorch能做什么?

?GPU加速
?自動求導
?常用網絡層

nn.Linear nn.Conv2d nn.LSTMnn.ReLU nn.Sigmoidnn.Softmax nn.CrossEntropyLoss nn.MSE

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)。

# -*- coding: UTF-8 -*-import torch from torch.autograd import Variable

創建變量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加速案例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。