评价此页

torch.Tensor.index_copy_#

Tensor.index_copy_(dim, index, tensor) Tensor#

通过按照 index 中给出的顺序选择索引,将 tensor 中的元素复制到 self 张量中。例如,如果 dim == 0index[i] == j,那么 tensor 的第 i 行将被复制到 self 的第 j 行。

tensor 的第 dim 个维度的尺寸必须与 index(必须为向量)的长度相同,且所有其他维度必须与 self 匹配,否则将报错。

注意

如果 index 包含重复条目,则 tensor 中的多个元素将被复制到 self 的相同索引位置。结果是不确定的,因为它取决于哪次复制最后执行。

参数:
  • dim (int) – 沿哪个维度进行索引

  • index (LongTensor) – 要从中选择的 tensor 的索引

  • tensor (Tensor) – 包含要复制数值的张量

示例

>>> x = torch.zeros(5, 3)
>>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
>>> index = torch.tensor([0, 4, 2])
>>> x.index_copy_(0, index, t)
tensor([[ 1.,  2.,  3.],
        [ 0.,  0.,  0.],
        [ 7.,  8.,  9.],
        [ 0.,  0.,  0.],
        [ 4.,  5.,  6.]])