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

Pytorch:如何创建一个随机整数张量,其中某个百分比具有某个值?例如,25%为1,其余为0,pytorch,Pytorch,在pytorch中,我可以创建一个随机的零张量和一张量,每个张量的分布约为%50 import torch torch.randint(low=0, high=2, size=(2, 5)) 我想知道我怎么能做一个张量,其中只有25%的值是1,其余的是0?下面是我的答案: 假设您想要一个维度为nxd的矩阵,其中每行中25%的值为1,其余为0,所需的张量将得到您想要的结果: n = 2 d = 5 rand_mat = torch.rand(n, d) k = round(0.25 * d)

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

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

我想知道我怎么能做一个张量,其中只有25%的值是1,其余的是0?

下面是我的答案:

假设您想要一个维度为
nxd
的矩阵,其中每行中25%的值为1,其余为0,
所需的张量将得到您想要的结果:

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))
n=2
d=5
rand_mat=火炬。rand(n,d)
k=四舍五入(0.25*d)#对于一般情况,将0.25更改为您需要的百分比
k_th_quant=torch.topk(rand_mat,k,max=False)[0][:,-1:]

bool_tensor=rand_mat您可以使用
rand
0,1
之间生成一个随机张量,并将其与
0.25
进行比较:

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

这并不能保证25%的值是1!特别是对于较小的母校,这是否回答了你的问题?
tensor([[0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0]], dtype=torch.int32)