Shortcuts

torch.tensor_split

torch.tensor_split(input, indices_or_sections, dim=0) List of Tensors

将一个张量分割成多个子张量,所有子张量都是 input 的视图, 沿着维度 dim 根据由 indices_or_sections 指定的索引或段数进行分割。此函数基于 NumPy 的 numpy.array_split()

Parameters
  • 输入 (Tensor) – 要分割的张量

  • indices_or_sections (Tensor, int or list or tuple of ints) –

    如果 indices_or_sections 是一个整数 n 或一个值为 n 的零维长张量,input 将沿维度 dim 被分割成 n 个部分。 如果 input 在维度 dim 上可以被 n 整除,每个部分的大小将相等,input.size(dim) / n。如果 input 不能被 n 整除,前 int(input.size(dim) % n) 部分的大小将为 int(input.size(dim) / n) + 1,其余部分的大小将为 int(input.size(dim) / n)

    如果 indices_or_sections 是一个整数列表或元组,或一个一维长张量,则 input 将沿维度 dim 在列表、元组或张量中的每个索引处进行分割。例如,indices_or_sections=[2, 3]dim=0 将导致张量 input[:2]input[2:3]input[3:]

    如果 indices_or_sections 是一个张量,它必须是 CPU 上的零维或一维长张量。

  • dim (int, 可选) – 沿此维度分割张量。默认值: 0

示例:

>>> x = torch.arange(8)
>>> torch.tensor_split(x, 3)
(tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7]))

>>> x = torch.arange(7)
>>> torch.tensor_split(x, 3)
(tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6]))
>>> torch.tensor_split(x, (1, 6))
(tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6]))

>>> x = torch.arange(14).reshape(2, 7)
>>> x
tensor([[ 0,  1,  2,  3,  4,  5,  6],
        [ 7,  8,  9, 10, 11, 12, 13]])
>>> torch.tensor_split(x, 3, dim=1)
(tensor([[0, 1, 2],
        [7, 8, 9]]),
 tensor([[ 3,  4],
        [10, 11]]),
 tensor([[ 5,  6],
        [12, 13]]))
>>> torch.tensor_split(x, (1, 6), dim=1)
(tensor([[0],
        [7]]),
 tensor([[ 1,  2,  3,  4,  5],
        [ 8,  9, 10, 11, 12]]),
 tensor([[ 6],
        [13]]))