PyTorch torch.tensor_split 関数


Pytorch torch 参考手册PyTorch torch リファレンスマニュアル

torch.tensor_splitPyTorch において、インデックスまたはセグメント数でテンソルを分割する関数です。

関数定義

torch.tensor_split(input, indices_or_sections, dim=0)

使用例

実例

import torch

x = torch.arange(12)
print("元のテンソル:")
print(x)

# インデックスで分割
result = torch.tensor_split(x, [2, 5, 8])
print("インデックス [2, 5, 8] で分割:")
for i, t in enumerate(result):
    print(f" チャンク {i}: {t}")

# セグメント数で分割(3等分)
y = torch.arange(9)
result = torch.tensor_split(y, 3)
print("n3等分:")
for i, t in enumerate(result):
    print(f" チャンク {i}: {t}")

# 2次元テンソルを列方向に分割
z = torch.arange(12).reshape(3, 4)
print("n2次元テンソル:")
print(z)

result = torch.tensor_split(z, 2, dim=1)
print("列ごとに2分割:")
for i, t in enumerate(result):
    print(f" チャンク {i}:n{t}")

出力結果は次のとおりです:

原始张量:
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
按索引 [2, 5, 8] 分割:
  块 0: tensor([0, 1])
  チャンク1: tensor([2, 3, 4])
  チャンク2: tensor([5, 6, 7])
  チャンク3: tensor([ 8,  9, 10, 11])

平均分为 3 份:
  块 0: tensor([0, 1, 2])
  チャンク1: tensor([3, 4, 5])
  チャンク2: tensor([6, 7, 8])

二维张量:
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
按列分为 2 份:
  块 0:
tensor([[0, 1],
        [4, 5],
        [8, 9]])
  チャンク1:
tensor([[ 2,  3],
        [ 6,  7],
        [10, 11]])

Pytorch torch 参考手册PyTorch torch リファレンスマニュアル

その他の拡張