Search code examples
pytorchtensortorch

Create a torch tensor with desired values


I want to create a torch tensor of size 100 with values 10 and 100. For example: The following gives a tensor of values between 5 and 6.

torch.randint(5,7,(100,))

tensor([6, 6, 6, 5, 5, 6, 6, 6, 6, 5, 6, 6, 6, 6, 6, 5, 6, 5, 5, 6, 5, 5, 5, 5,
        6, 5, 5, 5, 5, 5, 6, 6, 6, 5, 6, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 5, 6, 5,
        5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 5, 6,
        5, 5, 5, 5, 6, 6, 5, 6, 6, 6, 5, 5, 6, 6, 5, 6, 6, 6, 5, 5, 5, 5, 5, 6,
        6, 6, 5, 6])

Instead of this, I want a tensor with values 10 and 100 and I do not want the values between the integers 10 and 100. Tensor should just contain 10 and 100. How do I do that?

Thanks in advance.


Solution

  • You can achieve that by using the python function random.choice() to create a list of random numbers then convert it to a tensor:

    import random 
    import torch
    list_numbers = random.choices([100,10], k=100) 
    
    random_numbers = torch.Tensor(list_numbers)
    
    print(random_numbers)