python中的torch常用tensor處理函數(shù)示例詳解
note
一、tensor的創(chuàng)建
torch.tensor
會復制data,不想復制可以使用torch.Tensor.detach()
。- 如果是獲得numpy數(shù)組數(shù)據(jù),可以使用
torch.from_numpy()
,共享內(nèi)存
# 1. tensor torch.tensor(data, dtype=None, device=None,requires_grad=False) data - 可以是list, tuple, numpy array, scalar或其他類型 dtype - 可以返回想要的tensor類型 device - 可以指定返回的設備 requires_grad - 可以指定是否進行記錄圖的操作,默認為False # example 1 torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) tensor([[ 0.1000, 1.2000], [ 2.2000, 3.1000], [ 4.9000, 5.2000]]) # example 2 torch.tensor([0, 1]) # Type inference on data tensor([ 0, 1]) # example 3 torch.tensor([[0.11111, 0.222222, 0.3333333]], dtype=torch.float64, device=torch.device(‘cuda:0')) # creates a torch.cuda.DoubleTensor tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device=‘cuda:0') torch.tensor(3.14159) # Create a scalar (zero-dimensional tensor) tensor(3.1416) torch.tensor([]) # Create an empty tensor (of size (0,)) tensor([]) # 2. 從numpy中獲得數(shù)據(jù) torch.from_numpy(ndarry) # 3. 創(chuàng)建特定數(shù)值的tensor torch.zeros(*sizes, out=None, …)# 返回大小為sizes的零矩陣 1 torch.zeros_like(input, …) # 返回與input相同size的零矩陣 torch.ones(*sizes, out=None, …) #f返回大小為sizes的單位矩陣 torch.ones_like(input, …) #返回與input相同size的單位矩陣 torch.full(size, fill_value, …) #返回大小為sizes,單位值為fill_value的矩陣 torch.full_like(input, fill_value, …) 返回與input相同size,單位值為fill_value的矩陣 torch.arange(start=0, end, step=1, …) #返回從start到end, 單位步長為step的1-d tensor. torch.linspace(start, end, steps=100, …) #返回從start到end, 間隔中的插值數(shù)目為steps的1-d tensor torch.logspace(start, end, steps=100, …) #返回1-d tensor ,從10start到10end的steps個對數(shù)間隔 # 4. 隨機生成 torch.normal(mean, std, out=None) torch.rand(*size, out=None, dtype=None, …) #返回[0,1]之間均勻分布的隨機數(shù)值 torch.rand_like(input, dtype=None, …) #返回與input相同size的tensor, 填充均勻分布的隨機數(shù)值 torch.randint(low=0, high, size,…) #返回均勻分布的[low,high]之間的整數(shù)隨機值 torch.randint_like(input, low=0, high, dtype=None, …) # torch.randn(*sizes, out=None, …) #返回大小為size,由均值為0,方差為1的正態(tài)分布的隨機數(shù)值 torch.randn_like(input, dtype=None, …) torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的數(shù)列的隨機排列
二、tensor的加減乘除
torch.mm
: 用于兩個矩陣(不包括向量)的乘法。如維度為(l,m)和(m,n)相乘torch.bmm
: 用于帶batch的三維向量的乘法。如維度為(b,l,m)和(b,m,n)相乘torch.mul
: 用于兩個同維度矩陣的逐像素點相乘(點乘)。如維度為(l,m)和(l,m)相乘torch.mv
: 用于矩陣和向量之間的乘法(矩陣在前,向量在后)。如維度為(l,m)和(m)相乘,結果的維度為(l)。torch.matmul
: 用于兩個張量(后兩維滿足矩陣乘法的維度)相乘或者是矩陣與向量間的乘法,因為其具有廣播機制(broadcasting,自動補充維度)。如維度為(b,l,m)和(b,m,n);(l,m)和(b,m,n);(b,c,l,m)和(b,c,m,n);(l,m)和(m)相乘等?!酒渥饔冒瑃orch.mm、torch.bmm和torch.mv】@
運算符 : 其作用類似于torch.matmul
*
運算符 : 其作用類似于torch.mul
einsum
(Einstein summation convention,即愛因斯坦求和約定)的用法:- c i k = ∑ j a i j b j k c_{i k}=\sum_j a_{i j} b_{j k} cik?=∑j?aij?bjk? 的寫法如下:
c = np.dot(a, b) # 常規(guī) c = np.einsum('ij,jk->ik', a, b) # einsum
- 再比如 c k l = ∑ i ∑ j a i j k b i j l c_{\mathrm{kl}}=\sum_{\mathrm{i}} \sum_{\mathrm{j}} \mathrm{a}_{\mathrm{ijk}} \mathrm_{\mathrm{ijl}} ckl?=∑i?∑j?aijk?bijl? :
c = np.einsum('ijk,jkl->kl', a, b)
# 對數(shù)運算 torch.log(input, out=None) # y_i=log_e(x_i) torch.log1p(input, out=None) #y_i=log_e(x_i+1) torch.log2(input, out=None) #y_i=log_2(x_i) torch.log10(input,out=None) #y_i=log_10(x_i) # 冪函數(shù) torch.pow(input, exponent, out=None) # y_i=input^(exponent) # 指數(shù)運算 torch.exp(tensor, out=None) #y_i=e^(x_i) torch.expm1(tensor, out=None) #y_i=e^(x_i) -1
三、torch.argmax()函數(shù)
- (1)
torch.argmax(input, dim=None, keepdim=False)
返回指定維度最大值的序號; - (2)
dim
給定的定義是:the demention to reduce.也就是把dim
這個維度的,變成這個維度的最大值的index。
import torch a=torch.tensor([ [ [1, 5, 5, 2], [9, -6, 2, 8], [-3, 7, -9, 1] ], [ [-1, 7, -5, 2], [9, 6, 2, 8], [3, 7, 9, 1] ]]) b=torch.argmax(a,dim=1) print(a) print(a.shape) print(b)
(1)這個例子,tensor(2, 3, 4)
,因為是dim=1
,即將第二維度去掉,變成tensor(2, 4)
,將每一個3x4數(shù)組,變成1x4數(shù)組。
[1, 5, 5, 2], [9, -6, 2, 8], [-3, 7, -9, 1]
如上所示的3×4矩陣,取每一列的最大值對應的下標,a[0]中第一列的最大值的行標為1, 第二列的最大值的行標為2,第三列的最大值行標為0,第4列的最大值行標為1,所以最后輸出[1, 2, 0, 1],取每一列的最大值,結果為:
tensor([[[ 1, 5, 5, 2],
[ 9, -6, 2, 8],
[-3, 7, -9, 1]],
[[-1, 7, -5, 2],
[ 9, 6, 2, 8],
[ 3, 7, 9, 1]]])
torch.Size([2, 3, 4])
tensor([[1, 2, 0, 1],
[1, 0, 2, 1]])
(1)如果改成dim=2
,即將第三維去掉,即取每一行的最大值對應的下標,結果為tensor(2, 3)
。
import torch a=torch.tensor([ [ [1, 5, 5, 2], [9, -6, 2, 8], [-3, 7, -9, 1] ], [ [-1, 7, -5, 2], [9, 6, 2, 8], [3, 7, 9, 1] ]]) b=torch.argmax(a,dim=2) print(b) print(a.shape) """ tensor([[2, 0, 1], [1, 0, 2]]) torch.Size([2, 3, 4]) """
四、gathter函數(shù)
torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor
torch.gather()
函數(shù):利用index來索引input特定位置的數(shù)值dim = 1
表示橫向。
對于三維張量,其output是:
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
小栗子1
比如現(xiàn)在有4個句子(句子長度不一),現(xiàn)在的序列標注問題需要給每個單詞都標上一個標簽,標簽如下:
input = [ [2, 3, 4, 5], [1, 4, 3], [4, 2, 2, 5, 7], [1] ]
長度分別為4,3,5,1,其中第一個句子的標簽為2,3,4,5。在NLP中,一般需要對不同長度的句子進行padding到相同長度(用0進行padding),所以padding后的結果:
input = [
[2, 3, 4, 5, 0, 0],
[1, 4, 3, 0, 0, 0],
[4, 2, 2, 5, 7, 0],
[1, 0, 0, 0, 0, 0]
]
import torch input = [ [2, 3, 4, 5, 0, 0], [1, 4, 3, 0, 0, 0], [4, 2, 2, 5, 7, 0], [1, 0, 0, 0, 0, 0] ] input = torch.tensor(input) length = torch.LongTensor([[4], [3], [5], [1]]) # index之所以減1,是因為序列維度從0開始計算的 out = torch.gather(input, 1, length - 1) print(out)
out的結果為如下,比如length的第一行是[4]
,即找出input的第一行的第4個元素為5(這里length-1
后就是下標從1開始計算了)。
tensor([[5], [3], [7], [1]])
小栗子2:如果每行需要索引多個元素:
>>> t = torch.Tensor([[1,2],[3,4]]) 1 2 3 4 >>> torch.gather(t,1,torch.LongTensor([[0,0],[1,0]]) 1 1 4 3 [torch.FloatTensor of size 2x2]
五、針對某一維度的操作
- mean
- softmax
- BN
- LN
六、改變維度、拼接、堆疊等操作
import torch x = torch.arange(12) # tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) x1 = x.reshape(3, 4) # 改變維度 x2 = x.reshape(-1, 4) x3 = torch.zeros((2, 3, 4)) x4 = torch.ones((2, 3, 4)) # 所有元素都為1 # 正態(tài)分布 x5 = torch.randn(3, 4) x6 = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) x = torch.tensor([1.0, 2, 4, 8]) y = torch.tensor([2, 2, 2, 2]) # 都是按元素操作,注意**是求冪運算 print(x + y, x - y, x * y, x / y, x ** y) X = torch.arange(12, dtype=torch.float32).reshape((3,4)) Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) # 每行(上下)拼接, dim=1為左右拼接 print(torch.cat((X, Y), dim=0), "\n", torch.cat((X, Y), dim=1)) # 判斷每個位置是否相同 X == Y # 廣播機制, 兩個矩陣維度不同(數(shù)學上不能按元素相加),通過廣播(a賦值列,b賦值行)后相加 a = torch.arange(3).reshape((3, 1)) b = torch.arange(2).reshape((1, 2)) print(a + b) # 切片和索引, 和numpy差不多 X[-1], X[1:3] X[1, 2] X[0:2, :] = 12 # 賦值
view
改變維度,可以在其中一個維度傳參為-1,會自動計算。
import torch a = torch.arange(1, 7) print(a) b = a.view(2, 3) print(b) c = a.view(3, -1) print(c)
flatten
壓平操作
input1 = torch.tensor(range(2*3*4*5)).view(2, 3, 4, 5) # input1.shape torch.flatten(input1, start_dim = 1, end_dim=2).shape # torch.Size([2, 12, 5])
repeat_interleave
是將張量中的元素沿某一維度復制n次
import torch x = torch.tensor([[1, 2, 3],[4,5,6]]) x1 = x.repeat_interleave(3,0) print("x1:\n", x1) x2 = x.repeat_interleave(3,1) print("x2:\n",x2) x1: tensor([[1, 2, 3], [1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6]]) x2: tensor([[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 5, 5, 5, 6, 6, 6]]) Process finished with exit code 0
其他函數(shù):
torch.lerp(star, end, weight) : 返回結果是out= star t+ (end-start) * weight torch.rsqrt(input) : 返回平方根的倒數(shù) torch.mean(input) : 返回平均值 torch.std(input) : 返回標準偏差 torch.prod(input) : 返回所有元素的乘積 torch.sum(input) : 返回所有元素的之和 torch.var(input) : 返回所有元素的方差 torch.tanh(input) :返回元素雙正切的結果 torch.equal(torch.Tensor(a), torch.Tensor(b)) :兩個張量進行比較,如果相等返回true torch.max(input): 返回輸入元素的最大值 torch.min(input) : 返回輸入元素的最小值 element_size() :返回單個元素的字節(jié) torch.from_numpy(obj),利用一個numpy的array創(chuàng)建Tensor。注意,若obj原來是1列或者1行,無論obj是否為2維,所生成的Tensor都是一階的,若需要2階的Tensor,需要利用view()函數(shù)進行轉換。 torch.numel(obj),返回Tensor對象中的元素總數(shù)。 torch.ones_like(input),返回一個全1的Tensor,其維度與input相一致 torch.cat(seq, dim),在給定維度上對輸入的張量序列進行連接操作 torch.chunk(input, chunks, dim)在給定維度(軸)上將輸入張量進行分塊 torch.squeeze(input),將input中維度數(shù)值為1的維度去除??梢灾付骋痪S度。共享input的內(nèi)存 torch.unsqeeze(input, dim),在input目前的dim維度上增加一維 torch.clamp(input, min, max),將input的值約束在min和max之間 torch.trunc(input),將input的小數(shù)部分舍去
Reference
[1] 透徹理解torch.tensor中對某一維度的操作們(mean,Softmax,batch norm, layer norm)
到此這篇關于python中的torch常用tensor處理函數(shù)的文章就介紹到這了,更多相關torch常用tensor處理函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python判斷文件是否存在,不存在就創(chuàng)建一個的實例
今天小編就為大家分享一篇python判斷文件是否存在,不存在就創(chuàng)建一個的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python實現(xiàn)Word文檔轉換為圖片(JPG、PNG、SVG等常見格式)
將Word文檔以圖片形式導出,既能方便信息的分享,也能保護數(shù)據(jù)安全,避免被二次編輯,文本將介紹如何使用 Spire.Doc for Python 庫在Python程序中實現(xiàn)Word到圖片的批量轉換,需要的朋友可以參考下2024-06-06python生成器generator:深度學習讀取batch圖片的操作
這篇文章主要介紹了python生成器generator:深度學習讀取batch圖片的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05