torch.cat() :tensor的append方法

原文:
https://clay-atlas.com/blog/2020/06/15/pytorch-cn-note-torch-cat-append/

[PyTorch] 使用 torch.cat() 在 torch tensor 中實現如 List 資料結構中的 append() 操作

在我使用 PyTorch 搭建模型的過程中,經常會在處理資料時,對於如何將資料『串接』感到不知所措。

比方說在一般 List 資料型態中用起來相當順手的 append() 函式,在 Tensor 當中居然是沒有的,這讓我相當苦惱,不得已之下甚至常常將資料轉為 List,處理完後再將其轉回 Tensor。

不過這樣子的應急措施無法維持太久,應該說,我總是要學習 PyTorch 中資料串接的方法。

查了查網路,發現在 PyTorch 中算很相當常見的 torch.cat() 是相當高效的,也確實能完成如同 List 中的 append() 功能,故決定來紀錄一下使用方法。


torch.cat() 的使用方法

torch.cat() 的使用方法非常簡單,具體看下方的程式碼。

import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])

ab = torch.cat((a, b), 0)
ba = torch.cat((b, a), 0)

print('ab:', ab)
print('ba:', ba)

Output:

ab: tensor([1, 2, 3, 4, 5, 6])
ba: tensor([4, 5, 6, 1, 2, 3])

可以看到,具體的拼接方法為『前項』接『後項』。至於 0 是什麼意思呢?以下是個比較容易看出差異的例子。

import torch

a = torch.tensor([[1, 2, 3]])
b = torch.tensor([[4, 5, 6]])

print('0:', torch.cat((a, b), 0))
print('1:', torch.cat((a, b), 1))

Output:

0: tensor([[1, 2, 3],
           [4, 5, 6]])

1: tensor([[1, 2, 3, 4, 5, 6]])

可以發現 0 和 1 是不同維度的拼接方法。


References

posted @ 2022-06-27 04:57  TR_Goldfish  阅读(5334)  评论(0编辑  收藏  举报