Search code examples
pythonrandompytorch

pytorch How does pytorch randomly generate two data, one of which is an upper bound on the other


I want to make two tensor random data up and down 。They all have sizes of (batch_size,problem_size,problem_size), where each element in down won't exceed its counterpart in up。

the example of up and down is(batch_size=2,problem_size=3):

up=[[4,3,5],
    [6,3,1],
    [9,2,7],
    
    [7,8,5],
    [4,5,4],
    [10,4,7]]

down=[[2,1,4],
      [4,1,0],
      [7,0,3],
    
      [6,2,2],
      [1,3,3],
      [8,2,5]]

How do I do this with pytorch?

I used

dis_up = torch.randint(low=0, high=100, size=(batch_size, problem_size, problem_size)) t

to generate up,but i don't know how to generate the down.How can we ensure that the high value generated by the random number down corresponds to the value in up


Solution

  • Not really elegant, but once defined dis_up, I would do

    # initialize dis_down array with all zeros
    dis_down = torch.zeros_like(dis_up)
    
    # iterate through each cell and generate a random number
    for i in range(dis_up.shape[0]):
        for j in range(dis_up.shape[1]):
            for k in range(dis_up.shape[2]):
                dis_down[i, j, k] = torch.randint(0, dis_up[i,j,k]+1, size=(1,))
    

    This gives:

    In [ ]: dis_up
    Out[ ]:
    tensor([[[24, 67, 95],
             [34, 22,  6],
             [38, 54, 36]],
    
            [[79, 18, 30],
             [81, 34,  0],
             [47, 57, 46]]])
    
    In [ ]: dis_down
    Out[ ]:
    tensor([[[24, 52, 24],
             [26, 20,  2],
             [19, 14,  8]],
    
            [[56,  4, 28],
             [39, 13,  0],
             [16, 48, 21]]])