D. Thomas
D. Thomas

Reputation: 23

Getting range of values from Pytorch Tensor

I am trying to get a specific range of values from my pytorch tensor.

tensor=torch.tensor([0,1,2,3,4,5,6,7,8,9])
new_tensor=tensor[tensor>2]
print(new_tensor)

This will give me a tensor with scalars of 3-9

new_tensor2=tensor[tensor<8]
print(new_tensor2)

This will give me a tensor with scalars of 0-7

new_tensor3=tensor[tensor>2 and tensor<8]
print(new_tensor3)

However this raises an error. Would I be able to get a tensor with the values of 3-7 using something like this? I am trying to edit the tensor directly, and do not wish to change the order of the tensor itself.

grad[x<-3]=0.1
grad[x>2]=1
grad[(x>=-3 and x<=2)]=siglrelu(grad[(x>=-3 and x<=2)])*(1.0-siglrelu(grad[(x>=-3 and x<=2)]))

This is what I am really going for, and I am not exactly sure of how to go about this. Any help is appreciated, thank you!

Upvotes: 0

Views: 5720

Answers (1)

Melike
Melike

Reputation: 468

You can use & operation,

t = torch.arange(0., 10)
print(t)
print(t[(t > 2) & (t < 8)])

Output is,

tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
tensor([3., 4., 5., 6., 7.])

Upvotes: 1

Related Questions