构建或者生成的bool tensor作为index,可以方便的访问满足特定条件的相关的tensor值。
import torch
import numpy as np
if __name__ == '__main__':
a = torch.range(0,5)
print(a)
b = range(0,6)
print(b)
for i in b:
print(i)
c = torch.tensor([False,True,False,True,False,True])
index = a[c]
print(index)
d = np.random.permutation(5)
print(d)
# numpy 可以直接作为tensor的index去使用
print(a[d])
# index = b[c]
# print(index)
UserWarning: torch.range is deprecated and will be removed in a future release because its behavior is inconsistent with Python's range builtin. Instead, use torch.arange, which produces values in [start, end).
a = torch.range(0,5)
tensor([0., 1., 2., 3., 4., 5.])
range(0, 6)
0
1
2
3
4
5
tensor([1., 3., 5.])
[4 3 0 1 2]
tensor([4., 3., 0., 1., 2.])
但torch.range现在不建议使用了,和Python的range不太一样。
numpy 可以直接作为tensor的index去使用,