'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 1:[1]
If you sample from {0, 1} then a simple mapping from [0, 1] to [10, 100] will suffice
Here x -> (b-a)x + a = (100-10)x + 10 = 90x + 10 will work:
>>> rand = torch.randint(0, 2, (100,))
tensor([0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0,
0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1,
0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1,
1, 1, 0, 0])
>>> 90*rand+10
tensor([ 10, 10, 100, 100, 100, 100, 10, 100, 100, 100, 100, 10, 10, 100,
100, 10, 100, 100, 10, 100, 100, 100, 10, 10, 10, 10, 10, 100,
10, 10, 100, 10, 100, 100, 10, 10, 100, 10, 10, 10, 10, 10,
100, 10, 10, 100, 10, 10, 10, 100, 100, 100, 100, 10, 100, 100,
10, 10, 100, 10, 100, 10, 100, 10, 100, 100, 10, 10, 10, 10,
100, 100, 10, 10, 100, 100, 10, 10, 10, 100, 10, 10, 100, 10,
100, 100, 10, 10, 100, 10, 100, 10, 10, 10, 100, 100, 100, 100,
10, 10])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivan |
