Tensor.index_copy_按照index索引,将Tensor的元素复制到张量中
def index_copy_(self, dim, index, tensor): # real signature unknown; restored from __doc__
"""
index_copy_(dim, index, tensor) -> Tensor
Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting
the indices in the order given in :attr:`index`. For example, if ``dim == 0``
and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the
``j``\ th row of :attr:`self`.
The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the
length of :attr:`index` (which must be a vector), and all other dimensions must
match :attr:`self`, or an error will be raised.
.. note::
If :attr:`index` contains duplicate entries, multiple elements from
:attr:`tensor` will be copied to the same index of :attr:`self`. The result
is nondeterministic since it depends on which copy occurs last.
Args:
dim (int): dimension along which to index
index (LongTensor): indices of :attr:`tensor` to select from
tensor (Tensor): the tensor containing values to copy
Example::
>>> 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.]])
"""
return _te.Tensor(*(), **{})
官方注释例子讲解
这里x
是指被复制的张量 ,如例子中是一个 5×3
的矩阵
t
里面包含了需要被插入的值, 如
t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我们希望把t[0]
、t[1]
、t[2]
分别复制到 x
的 第0、第4、第2
维度
将index设置为 index = torch.tensor([0, 4, 2])
即可
官方例子如下:
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.]])