user14924
user14924

Reputation: 157

Numpy arrays comparison

I have 2 pytorch tensors (single column) of 40 elements To compare them element by element I converted them to numpy arrays with a single column of 40 elements. I want to compare both arrays element by element and if the value is greater than 0.5 in one array make it 1 else 0 and convert the result again to pytorch tensor. How do I do that.

Upvotes: 0

Views: 369

Answers (2)

erip
erip

Reputation: 16935

If you only care about the absolute difference, you can use torch.isclose with atol=0.5:

>>> A = torch.arange(10).float()
>>> B = A + torch.randn_like(A) # Add some Gaussian noise to `A`
>>> A
tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> B
tensor([0.3109, 1.6514, 1.7576, 3.2930, 2.7340, 5.5602, 6.9321, 6.4786, 6.7976,
        9.2342])
>>> torch.isclose(A, B, atol=0.5)
tensor([ True, False,  True,  True, False, False, False, False, False,  True])

If you need an asymmetric check, use a normal subtraction check:

>>> (B - A) > 0.5
tensor([False,  True, False, False, False,  True,  True, False, False, False])

You can use these functions in numpy easily, as well.

Upvotes: 1

3dSpatialUser
3dSpatialUser

Reputation: 2406

Maybe this helps:

import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([1.1, 2.6, 3.3, 4.6, 5.5])
(np.abs(a-b)>0.5).astype(int)
>>> array([0, 1, 0, 1, 0])

Upvotes: 0

Related Questions