PyTorch框架学习三——张量操作
生活随笔
收集整理的這篇文章主要介紹了
PyTorch框架学习三——张量操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PyTorch框架學習三——張量操作
- 一、拼接
- 1.torch.cat()
- 2.torch.stack()
- 二、切分
- 1.torch.chunk()
- 2.torch.split()
- 三、索引
- 1.torch.index_select()
- 2.torch.masked_select()
- 四、變換
- 1.torch.reshape()
- 2.torch.transpace()
- 3.torch.t()
- 4.torch.squeeze()
- 5.torch.unsqueeze()
一、拼接
1.torch.cat()
功能:將tensor按照維度dim進行拼接,除了需要拼接的維度外,其余維度尺寸得是相同的。
torch.cat(tensors, dim=0, out=None)看一下所有的參數:
2.torch.stack()
功能:在新創建的維度dim上進行拼接,所有的張量必須是相同的維度。
torch.stack(tensors, dim=0, out=None)
注意:stack()會創建一個新的維度。
原來t的維度是(2, 3),本來是沒有第三維的,但是stack()會構建新的dim=2,就是先構建第三維dim=2,然后在該維度上進行拼接。
二、切分
1.torch.chunk()
功能:將tensor按維度dim進行平均切分。如果不能整除,最后一份tensor在該維度上的長度小于其他tensor。
torch.chunk(input, chunks, dim=0)2.torch.split()
功能:將tensor按dim進行切分。
torch.split(tensor, split_size_or_sections, dim=0)三、索引
1.torch.index_select()
功能:在dim上,按照index索引數據,返回一個依據index索引數據拼接的張量。
torch.index_select(input, dim, index, out=None)2.torch.masked_select()
功能:按照mask中的True進行索引,返回一個一維張量。
torch.masked_select(input, mask, out=None) >>> x = torch.randn(3, 4) >>> x tensor([[ 0.3552, -2.3825, -0.8297, 0.3477],[-1.2035, 1.2252, 0.5002, 0.6248],[ 0.1307, -2.0608, 0.1244, 2.0139]]) >>> mask = x.ge(0.5) >>> mask tensor([[False, False, False, False],[False, True, True, True],[False, False, False, True]]) >>> torch.masked_select(x, mask) tensor([ 1.2252, 0.5002, 0.6248, 2.0139])四、變換
1.torch.reshape()
功能:變換張量的形狀。
torch.reshape(input, shape)2.torch.transpace()
功能:交換tensor的兩個維度。
torch.transpose(input, dim0, dim1)3.torch.t()
功能:2維tensor轉置,對矩陣而言。等價于torch.transpose(input, 0, 1)。
torch.t(input) >>> x = torch.randn(()) >>> x tensor(0.1995) >>> torch.t(x) tensor(0.1995) >>> x = torch.randn(3) >>> x tensor([ 2.4320, -0.4608, 0.7702]) >>> torch.t(x) tensor([ 2.4320, -0.4608, 0.7702]) >>> x = torch.randn(2, 3) >>> x tensor([[ 0.4875, 0.9158, -0.5872],[ 0.3938, -0.6929, 0.6932]]) >>> torch.t(x) tensor([[ 0.4875, 0.3938],[ 0.9158, -0.6929],[-0.5872, 0.6932]])注意:只對矩陣會轉置,對標量和向量都不會。
4.torch.squeeze()
功能:壓縮長度為1的維度(軸)。
torch.squeeze(input, dim=None, out=None)5.torch.unsqueeze()
功能:返回一個新的張量,對輸入的指定位置插入維度 1。
torch.unsqueeze(input, dim) >>> x = torch.tensor([1, 2, 3, 4]) >>> torch.unsqueeze(x, 0) tensor([[ 1, 2, 3, 4]]) >>> torch.unsqueeze(x, 1) tensor([[ 1],[ 2],[ 3],[ 4]])總結
以上是生活随笔為你收集整理的PyTorch框架学习三——张量操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MFC图像点运算之灰度线性变化、灰度非线
- 下一篇: Qt中修改应用程序和标题栏的图标