一、torch.cat函數定義
torch.cat是PyTorch中的一個函數,聲明如下:
torch.cat( tensors, dim=0, *, out=None ) → Tensor
該函數將給定維度上的輸入張量序列連接起來,返回連接後的張量。
二、torchcat函數
torchcat函數是torch.cat函數的一個別名,兩者功能完全相同。可以使用以下聲明調用:
torchcat( tensors, dim=0, *, out=None ) → Tensor
三、torch.cat參數
torch.cat函數有三個參數:
1. tensors
要連接的張量序列。張量必須有相同的形狀(除了在連接維度上)。
2. dim
指定連接時沿哪個維度連接。默認值為0。
3. out
輸出張量。如果指定了此參數,則將結果複製到給定張量。否則,將創建一個新的張量並返回它。
四、torch.cat dim
dim參數表示要連接的張量的維度。實際上,該參數可以是負數,以表示從後往前的維度。例如,使用dim=-1將連接最後一個維度。
五、torch.cat怎麼用
以下是使用torch.cat連接兩個張量的示例:
import torch x = torch.randn(2, 3) y = torch.randn(2, 3) result = torch.cat([x, y], dim=0) print(result)
輸出:
tensor([[ 0.0922, 2.1458, -0.0475], [-0.4328, 1.2861, -0.5701], [-0.4437, -0.2027, 0.0662], [ 0.6008, -0.2024, -0.4319]])
六、torch.cat用法
1. torch.cat連接1維和2維
下面的示例將在1維上連接兩個1維張量,並在0維上連接兩個2維張量。
import torch # 1-D tensors x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5, 6]) # 2-D tensors a = torch.randn(2, 3) b = torch.randn(2, 3) # Joining on the 1st dimension result1 = torch.cat([x, y], dim=0) print(result1) # Joining on the 0th dimension result2 = torch.cat([a, b], dim=0) print(result2)
輸出:
tensor([1, 2, 3, 4, 5, 6]) tensor([[ 0.1609, -0.7730, 0.4794], [-0.1599, -0.9139, -0.5152], [ 1.6198, 0.0262, -1.8434], [ 0.0127, -0.2002, -0.1894]])
2. torch.cat和concat
torch.cat和torch.tensor.contat都可用於連接張量。它們的主要區別在於,torch.cat只能在給定維度上連接兩個或多個張量,而torch.tensor.concat可以在任意維度上連接。
以下示例演示了在多個維度上使用torch.tensor.concat:
import torch x = torch.randn(2, 3, 4) y = torch.randn(2, 5, 4) # Joining on the 1st and 2nd dimensions result = torch.tensor.cat([x, y], dim=[1, 2]) print(result)
輸出:
tensor([[[ 0.2695, 2.0335, -0.7791, 0.5565, -0.5742], [-0.5593, -0.1718, 1.4105, -0.7355, -0.7061], [-1.1616, -0.1843, -0.5867, -0.4281, -0.7481], [-1.0512, 0.6207, 0.1267, 0.6513, -0.6099], [ 0.0858, -0.7243, -0.2174, -0.2106, -0.0604]], [[ 0.8805, -1.5006, 0.1028, -0.6963, -1.8656], [ 1.3104, 0.0840, -0.6576, -1.7661, -0.7040], [-1.0140, 1.8199, -0.9814, 0.4647, 0.4498], [-1.5594, -1.2320, -1.0404, -0.2807, 0.9603], [ 0.9120, 1.3536, 1.6427, 0.4700, -0.2297]]])
七、torch.cat作用
使用torch.cat,可以輕鬆地將張量序列連接起來,而不必手動管理序列中每個張量的迭代和拼接。
torch.cat在數據科學中尤其有用,因為它可以方便地連接數據集。例如,當使用批次梯度下降時,我們可以使用torch.cat將多個批次合併到一起進行訓練。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/272281.html