如何替换Pytorch张量中多行多个单元格的值?

How to replace the value of multiple cells in multiple rows in a Pytorch tensor?

我有张量

import torch
torch.zeros((5,10))

>>> tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

如何用随机输入 (torch.rand()) 替换每行中 X 个随机单元格的值?

也就是说,如果X = 2,在每一行中,2个随机单元格应该被替换为torch.rand()。 因为我需要它不破坏反向传播,所以我发现 替换单元格的 .data 属性应该有效。

我唯一熟悉的是使用 for 循环,但它对于大张量来说效率不高

你可以试试tensor.scatter_().

x = torch.zeros(3,4)
n_replace = 3 # number of cells to be replaced with random number
src = torch.randn(x.size())
index = torch.stack([torch.randperm(x.size()[1]) for _ in range(x.size()[0])])[:,:n_replace]

x.scatter_(1, index, src)
Out[22]: 
tensor([[ 0.0000,  0.5769,  0.7432, -0.1776],
        [-2.1673, -1.0802,  0.0000,  0.6241],
        [-0.6421,  0.1315,  0.0000, -2.7224]])

为避免重复,

perm = torch.randperm(tensor.size(0))
idx = perm[:k]
samples = tensor[idx]