高唐建筑公司網(wǎng)站seo關(guān)鍵詞優(yōu)化要多少錢
3-Pytorch張量的運算、形狀改變、自動微分
- 1 導(dǎo)入必備庫
- 2 張量的運算
- 3 張量的算數(shù)運算
- 4 一個元素的張量可以使用tensor.item()方法轉(zhuǎn)成標(biāo)量
- 5 torch.from_numpy()和tensor.numpy()
- 6 張量的變形
- 7 張量的自動微分
- 8 使用with torch.no_grad():包含上下文中使其不再跟蹤計算
- 9 使用tensor.detach()分離出張量的值
- 10 requirs_grad_()方法改變張量的跟蹤屬性,是否需要追蹤計算
1 導(dǎo)入必備庫
import torch
import numpy as np
2 張量的運算
張量的運算規(guī)則、切片索引規(guī)則與numpy類似,運算中遵循廣播原則和同形狀同位置元素對齊運算原則
t1 = torch.randn(2,3)
t2 = torch.ones(2,3)
print('t1=',t1)
print('t1+3=',t1+3)
print('t1+t2=',t1+t2) #同位置元素相加
print('t1.add(t2)=',t1.add(t2)) #等價t1+t2print('t1=',t1)
t1.add_(t2) # add_方法表示就地改變原值,不需要存放在其它變量內(nèi)
print('t1.add_(t2)=',t1)
輸出:
t1= tensor([[-1.1872, 1.4624, 0.1379],[ 1.0701, -2.6139, -1.2106]])
t1+3= tensor([[1.8128, 4.4624, 3.1379],[4.0701, 0.3861, 1.7894]])
t1+t2= tensor([[-0.1872, 2.4624, 1.1379],[ 2.0701, -1.6139, -0.2106]])
t1.add(t2)= tensor([[-0.1872, 2.4624, 1.1379],[ 2.0701, -1.6139, -0.2106]])
t1= tensor([[-1.1872, 1.4624, 0.1379],[ 1.0701, -2.6139, -1.2106]])
t1.add_(t2)= tensor([[-0.1872, 2.4624, 1.1379],[ 2.0701, -1.6139, -0.2106]])
3 張量的算數(shù)運算
張量的算數(shù)運算包括:abs(絕對值)、cunsum(累加)、divide(除)、floor_divide(整除)、mean(均值)、min(最小值)、max(最大值)、multiply(乘)等,矩陣轉(zhuǎn)置常用(tensor.T)和矩陣乘法用(matmul或@)
print('t1.matmul(t2.T)=',t1.matmul(t2.T))
print('t1 @ (t2.T)=',t1 @ (t2.T))
輸出:
t1.matmul(t2.T)= tensor([[3.4131, 3.4131],[0.2456, 0.2456]])
t1 @ (t2.T)= tensor([[3.4131, 3.4131],[0.2456, 0.2456]])
4 一個元素的張量可以使用tensor.item()方法轉(zhuǎn)成標(biāo)量
t3 = t1.sum()
print('t3=',t3,type(t3))
print('t3.item()=', t3.item(),type(t3.item()))
輸出:
t3= tensor(3.6586) <class 'torch.Tensor'>
t3.item()= 3.658644914627075 <class 'float'>
5 torch.from_numpy()和tensor.numpy()
使用torch.from_numpy()方法將ndarray轉(zhuǎn)成張量,使用tensor.numpy()方法得到對應(yīng)的ndarray數(shù)組,它們共用相同內(nèi)存
a = np.random.randn(2,3)
print('a= ', a)
t = torch.from_numpy(a)
print('t= ', t)
print('t.numpy()=',t.numpy())
輸出:
a= [[-0.17144614 0.03711562 -0.40770295][ 0.64600264 -1.39858095 0.41699902]]
t= tensor([[-0.1714, 0.0371, -0.4077],[ 0.6460, -1.3986, 0.4170]], dtype=torch.float64)
t.numpy()= [[-0.17144614 0.03711562 -0.40770295][ 0.64600264 -1.39858095 0.41699902]]
6 張量的變形
tensor.size()方法和tensor.shape屬性返回張量的形狀。
改變張量的形狀用tensor.view()方法,相當(dāng)于numpy中的reshape方法
t = torch.randn(4,6)
print('shape返回張量的形狀: t.shape=',t.shape)
t1 = t.view(3,8)
print('view改變形狀: t1.shape=',t1.shape)
# 將tensor矩陣展平,-1表示長度自動計算
t1 = t.view(-1,1)
print('view展平: t1.shape=',t1.shape)# 使用view增加維度,總元素個數(shù)不變
t1 = t.view(1,4,6)
print('view增加維度: t1.shape=',t1.shape)# 當(dāng)維度為1時,使用torch.squeeze()去掉長度為1的維度,相應(yīng)的torch.unsqueeze()增加長度為1的維度
print('t1.shape=',t1.shape)
t2 = torch.squeeze(t1) # 去掉長度為1的維度
print('squeeze去掉1維度: t2.shape=',t2.shape)
t3 = torch.unsqueeze(t2,0)
print('unsqueeze增加1維度: t2.shape=',t3.shape)
輸出;
shape返回張量的形狀: t.shape= torch.Size([4, 6])
view改變形狀: t1.shape= torch.Size([3, 8])
view展平: t1.shape= torch.Size([24, 1])
view增加維度: t1.shape= torch.Size([1, 4, 6])
t1.shape= torch.Size([1, 4, 6])
squeeze去掉1維度: t2.shape= torch.Size([4, 6])
unsqueeze增加1維度: t2.shape= torch.Size([1, 4, 6])
7 張量的自動微分
requires_grad屬性設(shè)置為True時,Pytorch會跟蹤此張量所有計算,并可調(diào)用backward() 計算所有梯度,梯度將累加到grad屬性中。
grad_fn屬性指向運算生成此張量的方法。
t = torch.ones(2,2,requires_grad= True)
print('是否跟蹤計算梯度:', t.requires_grad)
print('輸出梯度:', t.grad)
print('生成此張量的方法:', t.grad_fn)y = t + 5
print('y= ', y)
print('y.grad_fn=',y.grad_fn)z = y * 2
out = z.mean()
print('out=',out)# 對out微分:d(out)/d(t)
out.backward()
print('t.grad=',t.grad)
輸出:
是否跟蹤計算梯度: True
輸出梯度: None
生成此張量的方法: None
y= tensor([[6., 6.],[6., 6.]], grad_fn=<AddBackward0>)
y.grad_fn= <AddBackward0 object at 0x000002A7D34E8248>
out= tensor(12., grad_fn=<MeanBackward0>)
t.grad= tensor([[0.5000, 0.5000],[0.5000, 0.5000]])
8 使用with torch.no_grad():包含上下文中使其不再跟蹤計算
print('是否跟蹤計算梯度:', t.requires_grad)
print('是否跟蹤計算梯度:', (t+2).requires_grad)with torch.no_grad():print('是否跟蹤計算梯度:', (t+2).requires_grad)
輸出:
是否跟蹤計算梯度: True
是否跟蹤計算梯度: True
是否跟蹤計算梯度: False
9 使用tensor.detach()分離出張量的值
print('是否跟蹤計算梯度:', out.requires_grad)
# s1 = out.data() #獲取值
s = out.detach()print('是否跟蹤計算梯度:',s.requires_grad)
輸出:
是否跟蹤計算梯度: True
是否跟蹤計算梯度: False
10 requirs_grad_()方法改變張量的跟蹤屬性,是否需要追蹤計算
print('是否跟蹤計算梯度:', t.requires_grad)
t.requires_grad_(False)
print('是否跟蹤計算梯度:', t.requires_grad)
輸出:
是否跟蹤計算梯度: True
是否跟蹤計算梯度: False