一祠锣、張量
本文是個人的學(xué)習(xí)筆記酷窥,內(nèi)容主要參考了圖書《python深度學(xué)習(xí)——基于pyTorch》、極客時間的課程《pyTorch深度學(xué)習(xí)實戰(zhàn)》以及B站上“深度之眼”的課程《pyTorch框架基礎(chǔ)》等伴网。
1.1 概述
張量(Tensor)是一個多維數(shù)組蓬推,它是標(biāo)量(0維張量)、向量(1維張量)澡腾、矩陣(2維張量)的高維擴(kuò)展沸伏。
Tensor在torch.Tensor
中糕珊,有以下幾個基本屬性:
- data: 存儲了主要的數(shù)據(jù)
- grad: data的梯度
- grad_fn: 創(chuàng)建Tensor的Function,自動求導(dǎo)計算的依據(jù)
- requires_grad: 是否需要計算梯度
- is_leaf: 當(dāng)前Tensor是否為計算圖中的葉子節(jié)點
- dtype: 張量的數(shù)據(jù)類型毅糟,如
torch.FloatTensor
红选,torch.cuda.FloatTensor
等 - shape: 張量的形狀
- device: 張量的位置,如GPU/CPU
非葉子節(jié)點的梯度會在計算梯度后被釋放
1.2 張量的創(chuàng)建
1.2.1 直接創(chuàng)建
直接使用torch.tensor
創(chuàng)建張量姆另,默認(rèn)在CPU上創(chuàng)建喇肋,定義為:
torch.tensor(data,
dtype=None,
device=None,
requires_grad=False,
pin_memory=False)
-
data
: 數(shù)據(jù),可以是ndarray
迹辐、list
苟蹈、tuple
寝姿、scalar
等 -
dtype
: 張量的數(shù)據(jù)類型簸淀,默認(rèn)為torch.float32
-
device
: 張量的位置役电,默認(rèn)為torch.device('cpu')
-
requires_grad
: 是否需要計算梯度幻妓,默認(rèn)為False
-
pin_memory
: 是否使用pinned memory
壶栋,默認(rèn)為False
除此以外跑杭,還可以使用
torch.Tensor
進(jìn)行張量的創(chuàng)建盯串,torch.Tensor
的創(chuàng)建和torch.tensor
的創(chuàng)建基本相同抚垄,只是torch.Tensor
是類躏鱼,是默認(rèn)張量類型torch.FloatTensor
的別名氮采;而torch.tensor()
則是Python的函數(shù)。
import torch
t = torch.tensor([1,2,3])
print(t)
import numpy as np
arr = np.ones((3,3))
t = torch.tensor(arr, device='cuda', dtype=torch.int16)
print(t)
tensor([1, 2, 3], device='cuda:0')
tensor([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], device='cuda:0', dtype=torch.int16)
除此以外染苛,還可以使用torch.Tensor
的from_numpy
方法創(chuàng)建張量鹊漠,需要注意的是,使用from_numpy
創(chuàng)建的Tensor
和numpy
的ndarray
共享內(nèi)存茶行,修改一個躯概,另一個也會改變:
import numpy as np
import torch
arr = np.array([[1,2,3],[4,5,6]])
t = torch.from_numpy(arr)
print('ndarray arr is {}'.format(arr))
print('Tensor t is {}'.format(t))
arr[1,2] = 10
print(t)
print('after modification arr is:\n {}'.format(arr))
print('After modify arr, t is:\n {}'.format(t))
ndarray arr is [[1 2 3]
[4 5 6]]
Tensor t is tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
tensor([[ 1, 2, 3],
[ 4, 5, 10]], dtype=torch.int32)
after modification arr is:
[[ 1 2 3]
[ 4 5 10]]
After modify arr, t is:
tensor([[ 1, 2, 3],
[ 4, 5, 10]], dtype=torch.int32)
1.2.2 依據(jù)數(shù)值創(chuàng)建
torch.zeros()
創(chuàng)建一個指定形狀的張量,并初始化為0畔师,其定義為:
torch.zeros(size,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
-
size
: 指定形狀 -
out
: 輸出張量 -
dtype
: 張量的數(shù)據(jù)類型娶靡,默認(rèn)為torch.float32
-
layout
: 張量的存儲方式,默認(rèn)為torch.strided
-
device
: 張量的位置看锉,默認(rèn)為torch.device('cpu')
import torch
Y = torch.ones([1])
X = torch.zeros((3, 3), out=Y)
print(X, Y, id(X), id(Y), id(X) == id(Y))
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]) tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]) 2374969795552 2374969795552 True
可以看到X和Y是同一個內(nèi)容
torch.ones_like()
依據(jù)內(nèi)容形狀創(chuàng)建全0張量姿锭,其定義為:
torch.ones_like(input,
out=None,
dtype=None,
layout=None,
device=None,
requires_grad=False)
torch.full()
依據(jù)內(nèi)容創(chuàng)建全為特定值的張量,其定義為:
torch.full(size,
fill_value,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
torch.arange()
創(chuàng)建一個等差數(shù)列的張量(半開半閉區(qū)間伯铣,即[start, end))呻此,其定義為:
torch.arange(start=0,
end,
step=1,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
torch.linspace()
創(chuàng)建一個等差張量,與arange
的區(qū)別在于腔寡,該函數(shù)在一定數(shù)值范圍內(nèi)(閉區(qū)間)構(gòu)建一個等差的張量焚鲜,而不需要指定間隔的大小,其定義為:
torch.linspace(start,
end,
steps=100,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
此處需要注意的是第三個參數(shù)step
,該參數(shù)表示的是最后生成的張量的長度恃泪,而不是數(shù)列的間隔郑兴,因此實際的間隔為
import torch
torch.linspace(0, 10, 5)
tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
torch.logspace()
創(chuàng)建一個對數(shù)等比數(shù)列的張量犀斋,其定義為:
torch.logspace(start,
end,
steps=100,
base=10.0,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
其中贝乎,
-
base
: 表示對數(shù)數(shù)列的底數(shù),默認(rèn)為10 -
step
: 表示最后生成的張量的長度叽粹,而不是數(shù)列的間隔览效,因此實際的間隔為
1.2.3 創(chuàng)建隨機(jī)張量
torch.normal()
創(chuàng)建一個正態(tài)分布的張量,其定義為:
torch.normal(mean, std, out=None)
torch.normal(mean, std, size, out=None)
需要注意的是對于
normal()
函數(shù)而言虫几,當(dāng)mean和std均為標(biāo)量時锤灿,必須指定size
參數(shù),否則會報錯
import torch
# mean為張量辆脸,std為張量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print('mean is {}\nstd is {}'.format(mean, std))
print('t_normal is {}'.format(t_normal))
# mean為標(biāo)量但校,std為標(biāo)量
t_normal = torch.normal(0.0, 1.0, size=(1,))
print('t_normal is {}'.format(t_normal))
# mean為張量,std為標(biāo)量
mean = torch.arange(1, 5, dtype=torch.float)
std = 1
t_normal = torch.normal(mean, std)
print("mean is {}\nstd is {}".format(mean, std))
print('t_normal is {}'.format(t_normal))
mean is tensor([1., 2., 3., 4.])
std is tensor([1., 2., 3., 4.])
t_normal is tensor([0.1857, 1.8819, 5.5086, 6.1349])
t_normal is tensor([1.3543])
mean is tensor([1., 2., 3., 4.])
std is 1
t_normal is tensor([2.2058, 0.9800, 3.6500, 3.6093])
torch.randn()
創(chuàng)建一個標(biāo)準(zhǔn)正態(tài)分布的張量啡氢,其定義為:
torch.randn(size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
-
size
: 指定張量的形狀
torch.rand()和torch.rand_like()
在區(qū)間創(chuàng)建一個均勻分布的張量状囱,其定義為:
torch.rand(size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
torch.rand_like(input, dtype=None, layout=None, device=None, requires_grad=False, memory_format=None)
torch.randint()和torch.randint_like()
在一個區(qū)間上,創(chuàng)建一個均勻分布的整數(shù)張量倘是,其定義為:
torch.randint(low=0,
high,
size,
out=None,
dtype=None,
layout=torch.strided,
device=None,
requires_grad=False)
參考官方文檔:https://pytorch.org/docs/stable/generated/torch.randint.html#torch-randint
torch.randint_like(input,
low=0,
high=None,
size=None,
out=None,
dtype=None,
layout=None,
device=None,
requires_grad=False,
memory_format=torch.preserve_format)
參考官方文檔:https://pytorch.org/docs/stable/generated/torch.randint_like.html#torch-randint-like
torch.randperm()
創(chuàng)建一個隨機(jī)排列的整數(shù)張量亭枷,常常用來生成一個隨機(jī)索引,其定義為:
torch.randperm(n,
out=None,
dtype=torch.int64,
layout=torch.strided,
device=None,
requires_grad=False)
torch.bernoulli()
以input
的值作為概率搀崭,生成一個服從伯努利分布的張量叨粘,其定義為:
torch.bernoulli(input,
*
generator=None,
out=None)
import torch
t = torch.bernoulli(torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5]))
t
tensor([0., 1., 0., 1., 1.])
1.3 張量的操作
1.3.1 張量的拼接
torch.cat()
將輸入的張量按維度dim
拼接起來,其定義為:
torch.cat(tensors, dim=0, out=None)
- tensors:輸入的張量列表
- dim:在哪個維度上拼接瘤睹,默認(rèn)為0
dim
可以理解為:操作后會發(fā)生變化的維度
torch.stack()
將輸入的張量在新創(chuàng)建的維度dim
拼接起來升敲,其定義為:
torch.stack(tensors, dim=0, out=None)
- tensors:輸入的張量列表
- dim:在哪個維度上增加,默認(rèn)為0
# cat的操作
import torch
t = torch.arange(1,7)
t = torch.reshape(t, (2,3))
t_0 = torch.cat([t, t], dim=0)
t_1 = torch.cat([t, t], dim=1)
print('tensor t is {}'.format(t))
print(t.shape)
print('在dim=0上執(zhí)行操作cat的結(jié)果為{}'.format(t_0))
print(t_0.shape)
print('在dim=1上執(zhí)行操作cat的結(jié)果為{}'.format(t_1))
print(t_1.shape)
tensor t is tensor([[1, 2, 3],
[4, 5, 6]])
torch.Size([2, 3])
在dim=0上執(zhí)行操作cat的結(jié)果為tensor([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
torch.Size([4, 3])
在dim=1上執(zhí)行操作cat的結(jié)果為tensor([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
torch.Size([2, 6])
# stack的操作
t_stack_0 = torch.stack([t, t], dim=0)
t_stack_1 = torch.stack([t, t], dim=2)
print(t_stack_0)
print(t_stack_0.shape)
print(t_stack_1)
print(t_stack_1.shape)
tensor([[[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3],
[4, 5, 6]]])
torch.Size([2, 2, 3])
tensor([[[1, 1],
[2, 2],
[3, 3]],
[[4, 4],
[5, 5],
[6, 6]]])
torch.Size([2, 3, 2])
1.3.2 張量的切分
torch.chunk()
將輸入的張量在dim
維度上按照chunks
個大小切分轰传,其定義為:
torch.chunk(input, chunks, dim=0)
-
input
:輸入的張量 -
chunks
:切分的份數(shù)冻晤,必須為整數(shù) -
dim
:在哪個維度上切分,默認(rèn)為0
若不能整除绸吸,
chunk
函數(shù)是先做除法鼻弧,然后再向上取整得到每組的數(shù)量。例如原始tensor中有10個元素時锦茁,當(dāng)chunks=3時, 10/3=3.3333, 向上取整為4攘轩,所以最后得到每組張量有4個元素,最后剩下的兩個元素自動歸為1組码俩。
import torch
A=torch.arange(1,11)
B = torch.chunk(A, 2, 0)
print(B)
# 不能整除的情況
B = torch.chunk(A, 3, 0)
print(B)
(tensor([1, 2, 3, 4, 5]), tensor([ 6, 7, 8, 9, 10]))
(tensor([1, 2, 3, 4]), tensor([5, 6, 7, 8]), tensor([ 9, 10]))
torch.split()
將輸入的張量在dim
維度上按照split_size
的大小切分度帮,其定義為:
torch.split(tensor, split_size_or_sections, dim=0)
-
tensor
:輸入的張量 -
split_size_or_sections
:切分的份數(shù),若為整數(shù),則會在指定維度上將整個張量切分為split_size_or_sections
大斜颗瘛(不能整除時瞳秽,最后剩下的為1組);若為list率翅,則按照list中元素的數(shù)量來切分 -
dim
:在哪個維度上切分练俐,默認(rèn)為0
import torch
A = torch.rand(4, 4)
print('原始tensor為\n{}'.format(A))
print('1.split_size_or_sections為整數(shù),且可以整除時:')
B = torch.split(A, 2, 0)
print(B)
print('2.split_size_or_sections為整數(shù)冕臭,且不可以整除時:')
B = torch.split(A, 3, 0)
print(B)
print('3.split_size_or_sections為列表時:')
B = torch.split(A, [1, 3], 0)
print(B)
原始tensor為
tensor([[0.3747, 0.0479, 0.1082, 0.7263],
[0.8332, 0.2020, 0.7699, 0.0615],
[0.8753, 0.0584, 0.9294, 0.3031],
[0.6463, 0.2581, 0.3250, 0.5398]])
1.split_size_or_sections為整數(shù)腺晾,且可以整除時:
(tensor([[0.3747, 0.0479, 0.1082, 0.7263],
[0.8332, 0.2020, 0.7699, 0.0615]]), tensor([[0.8753, 0.0584, 0.9294, 0.3031],
[0.6463, 0.2581, 0.3250, 0.5398]]))
2.split_size_or_sections為整數(shù),且不可以整除時:
(tensor([[0.3747, 0.0479, 0.1082, 0.7263],
[0.8332, 0.2020, 0.7699, 0.0615],
[0.8753, 0.0584, 0.9294, 0.3031]]), tensor([[0.6463, 0.2581, 0.3250, 0.5398]]))
3.split_size_or_sections為列表時:
(tensor([[0.3747, 0.0479, 0.1082, 0.7263]]), tensor([[0.8332, 0.2020, 0.7699, 0.0615],
[0.8753, 0.0584, 0.9294, 0.3031],
[0.6463, 0.2581, 0.3250, 0.5398]]))
1.3.3 張量的索引
torch.index_select()
將輸入的張量在dim
維度上按照index
索引進(jìn)行選擇辜贵,其定義為:
torch.index_select(
input,
dim,
index,
out)
-
input
:輸入的張量 -
dim
:在哪個維度上選擇悯蝉,默認(rèn)為0 -
index
:索引,數(shù)據(jù)類型為tensor.long
import torch
t = torch.arange(1, 10).view((3, 3 ))
print(t)
idx = torch.tensor([0, 2], dtype=torch.long)
t_select = torch.index_select(t, dim=0, index=idx)
print(t_select)
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tensor([[1, 2, 3],
[7, 8, 9]])
tensor.masked_select()
將輸入的張量在dim
維度上按照mask
索引進(jìn)行選擇托慨,其定義為:
torch.masked_select(
input,
mask,
out=None)
-
input
:輸入的張量 -
mask
:索引鼻由,數(shù)據(jù)類型為tensor.bool
的列表,大小與input
相同
返回值為滿足條件的1維張量
import torch
t = torch.arange(1, 10).view((3, 3 ))
mask = t.ge(5)
t_select = t.masked_select(mask)
print('mask is: \n{}'.format(mask))
print(t_select)
# 也可以簡化為如下形式:
t_select = torch.masked_select(t, t>=5)
print(t_select)
mask is:
tensor([[False, False, False],
[False, True, True],
[ True, True, True]])
tensor([5, 6, 7, 8, 9])
tensor([5, 6, 7, 8, 9])
1.3.4 張量變換
torch.reshape()
將輸入的張量按照shape
重新排列厚棵,其定義為:
torch.reshape(input, shape)
-
input
要變換的張量 -
shape
新的形狀蕉世,如果一個維度為-1
,則這個維度會自動計算
注意:當(dāng)張量在內(nèi)存中是連續(xù)的時候窟感,新得到的張量與
input
共享內(nèi)存讨彼。
import torch
t = torch.randperm(8)
print('原始數(shù)據(jù)t為:\n{}'.format(t))
t_reshape = torch.reshape(t, (-1, 4))
print('reshape得到的數(shù)據(jù)為:\n{}'.format(t_reshape))
# 共享內(nèi)存驗證
t[0] = 1024
print('修改了t的第一個元素為1024后,t的值變?yōu)椋篭n{}'.format(t))
print('reshape得到的數(shù)據(jù)變?yōu)椋篭n{}'.format(t_reshape))
原始數(shù)據(jù)t為:
tensor([4, 5, 0, 2, 7, 3, 1, 6])
reshape得到的數(shù)據(jù)為:
tensor([[4, 5, 0, 2],
[7, 3, 1, 6]])
修改了t的第一個元素為1024后柿祈,t的值變?yōu)椋?tensor([1024, 5, 0, 2, 7, 3, 1, 6])
reshape得到的數(shù)據(jù)變?yōu)椋?tensor([[1024, 5, 0, 2],
[ 7, 3, 1, 6]])
torch.transpose()
將輸入的張量按照dim0
和dim1
進(jìn)行轉(zhuǎn)置哈误,其定義為:
torch.transpose(input, dim0, dim1)
t.transpose(dim0, dim1)
torch.t()
2維張量的轉(zhuǎn)置,相當(dāng)于torch.transpose(input, 0, 1)
import torch
t = torch.rand((2,3,4))
# 也可以寫成t_tranpose = torch.transpose(t, 0, 1)
t_transpose = t.transpose(dim0=0, dim1=1)
print('t的轉(zhuǎn)置為:\n{}'.format(t_transpose.shape))
t的轉(zhuǎn)置為:
torch.Size([3, 2, 4])
torch.squeeze()
若dim
為None
躏嚎,則將輸入的張量中所有維度為1
的維度刪除蜜自;若指定了dim
,且指定維度的長度為1卢佣,則移除該維度重荠,其定義為:
torch.squeeze(input,
dim=None,
out=None)
torch.unsqueeze()
將輸入的張量中指定維度增加一個維度,其定義為:
torch.unsqueeze(input,
dim,
out=None)
依據(jù)dim
擴(kuò)展維度
import torch
t = torch.rand((2,1,4))
t_squeeze = torch.squeeze(t)
print('t的形狀為:\n{}'.format(t.shape))
print('squeeze后t的形狀為:\n{}'.format(t_squeeze.shape))
t_unsqueeze = torch.unsqueeze(t, 3)
print('unsqueeze后的形狀為:\n{}'.format(t_unsqueeze.shape))
t的形狀為:
torch.Size([2, 1, 4])
squeeze后t的形狀為:
torch.Size([2, 4])
unsqueeze后的形狀為:
torch.Size([2, 1, 4, 1])
1.4 張量的計算
1.4.1 加法
torch.add()
對輸入的張量進(jìn)行加法操作(先乘后加)虚茶,其定義為:
torch.add(input,
other,
*,
alpha=1,
out=None)
-
input
:第一個的張量 -
alpha
:加法操作的系數(shù)戈鲁,默認(rèn)為1
-
other
:第二個的張量
整個運(yùn)算完成的操作公式為:
import torch
t1 = torch.ones((3,3)) * 2
t2 = torch.ones((3,3))
print(torch.add(t1, t2, alpha=10))
tensor([[12., 12., 12.],
[12., 12., 12.],
[12., 12., 12.]])