“PyTorchのテンソルの連結をどのように実装すればいいですか?”

PyTorchでは、torch.cat()関数を使用してテンソルの連結を実現できます。

torch.cat()関数の構文は次のようになります:

torch.cat(tensors, dim=0, out=None)

– tensorsとは、連結するテンソルを表すテンソルのシーケンスであり、dimは結合する次元を指定するもので、デフォルトは0(行の方向に結合)です。outは結合結果を示すオプションの出力テンソルです。

torch.cat()関数を使用してテンソルを連結する例を以下に示します:

import torch

# 创建两个张量
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])

# 沿着行的方向拼接张量
result = torch.cat((tensor1, tensor2), dim=0)

print(result)

実行結果は:

tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

上記の例では、まず、テンソルtensor1とtensor2を作成しました。そして、torch.cat()関数を使用してこれらのテンソルを行方向に結合し、新しいテンソルresultを得ました。最後に、結合結果を出力しました。

bannerAds