Pytorch 张量 – 随机替换满足条件的值

青葱年少 pytorch 284

原文标题Pytorch tensor – randomly replace values that meet condition

我有一个 Pytorch 张量mask的维度,

torch.Size([8, 24, 24])

具有独特的价值,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2093, 1054, 1461]))

我希望将 2 的数量随机替换为 0,以便张量中的唯一值和计数变为,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2500, 1054, 1054]))

我试过用torch.where没有成功。如何做到这一点?

原文链接:https://stackoverflow.com//questions/71885228/pytorch-tensor-randomly-replace-values-that-meet-condition

回复

我来回复
  • draw的头像
    draw 评论

    一种可能的解决方案是通过viewnumpy.random.choice展平:

    from numpy.random import choice
    
    idx = torch.where(mask.view(-1) == 2)[0]  # get all indicies of 2 in flat tensor
    
    num_to_change = 2500 - 2093 # as follows from example abow
    
    idx_to_change = choice(idx, size=num_to_change, replace=False)
    
    mask.view(-1)[idx_to_change] = 0
    
    2年前 0条评论