深度學(xué)習(xí)PyTorch庫介紹

https://colab.research.google.com/
張量
import torch
創(chuàng)建張量
# Tensor with Single number
t1 = torch.tensor(5.)
print(t1)
Output : tensor(5.)
print(t1.dtype)
Output: torch.float32
# Tensor with 1D vector
t2 = torch.tensor([1, 2, 3., 4])
print(t2)
Output: tensor([1., 2., 3., 4.])
# Matrix
t3 = torch.tensor([[1., 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(t3)
Output: tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
t4 = torch.tensor([
[[10. , 11, 12],
[13, 14, 15]],
[[16, 17, 18],
[19, 20, 21]]
])
print(t4)
Output: tensor([[[10., 11., 12.],
[13., 14., 15.]],
[[16., 17., 18.],
[19., 20., 21.]]])
print(t1.shape)
Output: torch.Size([])
print(t2.shape)
Output: torch.Size([4])
print(t3.shape)
Output: torch.Size([3, 3])
print(t4.shape)
Output: torch.Size([2, 2, 3])
張量運算與梯度計算
x = torch.tensor(3.)
w = torch.tensor(4. ,requires_grad=True)
z = torch.tensor(5. ,requires_grad=True)
x , w , z
Output: (tensor(3.), tensor(4., requires_grad=True), tensor(5., requires_grad=True))
y = x*w + z
print(y)
Output: tensor(17., grad_fn=<AddBackward0>)
自動計算導(dǎo)數(shù)
#Compute derivatives
y.backward()
print("dy/dx =", x.grad)
print("dy/dw =", w.grad)
print("dy/dz =", z.grad)
Output : dy/dx = None
dy/dw = tensor(3.)
dy/dz = tensor(1.)
y wrt x的導(dǎo)數(shù)的值為“None”,因為參數(shù)requires_grad需要設(shè)置為False y wrt w的導(dǎo)數(shù)的值是3,因為dy/dw=x=3 y wrt z的導(dǎo)數(shù)的值是1,因為dy/dz=1
帶NumPy的PyTorch
#First create a numpy array
import numpy as np
x = np.array([1, 2., 3])
print(x)
Output: array([1., 2., 3.])
#Create a tensor from numpy array
y. = torch.from_numpy(x)
print(y)
Output: tensor([1., 2., 3.], dtype=torch.float64)
print(x.dtype)
print(y.dtype)
Output: float64
torch.float64
z = y.numpy()
print(z)
Output: array([1., 2., 3.])
AutoGrad:為張量運算計算梯度的能力是一種強大的能力,對于訓(xùn)練神經(jīng)網(wǎng)絡(luò)和執(zhí)行反向傳播是必不可少的。 GPU支持:在處理大量數(shù)據(jù)集和大型模型時,PyTorch張量操作在圖形處理單元(GPU)中執(zhí)行,這將使普通cpu所需的時間減少40倍到50倍。
?------------------------------------------------
雙一流高校研究生團隊創(chuàng)建
專注于計算機視覺原創(chuàng)并分享相關(guān)知識?
聞道有先后,術(shù)業(yè)有專攻,如是而已╮(╯_╰)╭
評論
圖片
表情
