Pytorch:如何创建一个随机整数张量,其中特定百分比具有特定值?例如25%为1,其余为0

问题描述 投票:0回答:3

在 pytorch 中,我可以创建一个随机的零和一个张量,每个张量的分布约为 %50

import torch 
torch.randint(low=0, high=2, size=(2, 5))

我想知道如何制作一个张量,其中只有 25% 的值为 1,其余均为 0?

pytorch
3个回答
5
投票

您可以使用

rand
生成
0,1
之间的随机张量,并将其与
0.25
进行比较:

(torch.rand(size=(2,5)) < 0.25).int()

输出:

tensor([[0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0]], dtype=torch.int32)

2
投票

以下是我的回答:如何在 PyTorch 中的张量的每一行中随机设置固定数量的元素

假设您想要一个维度为

n X d
的矩阵,其中恰好每行中 25% 的值为 1,其余为 0,
desired_tensor
将得到您想要的结果:

n = 2
d = 5
rand_mat = torch.rand(n, d)
k = round(0.25 * d) # For the general case change 0.25 to the percentage you need
k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:]
bool_tensor = rand_mat <= k_th_quant
desired_tensor = torch.where(bool_tensor,torch.tensor(1),torch.tensor(0))

0
投票
n = 1024
k = int(0.75 * n)
tensor = torch.ones(n)
indexes = torch.randperm(n)[:k] # Generates random permutation of integers from 0 to n-1, select first 256 in order to get 256 random unique integers
tensor[indexes] = 0
© www.soinside.com 2019 - 2024. All rights reserved.