Reputation: 504
Given the following code:
def to_l(pos_probs, threshold):
return (pos_probs >= threshold).astype('int')
thresh = np.arange(0, 0.2, 0.1)
print(thresh)
This works:
print([to_l([0.2,0.3], w) for w in thresh])
Result:
[0. 0.1]
[array([1, 1]), array([1, 1])]
But this doesn't:
[to_l([0.2,0.3], w) for w in [0.,0.1]]
And this doesn't:
to_l([0.2,0.3], 0.1)
Giving the error:
TypeError: '>=' not supported between instances of 'list' and 'float'
The type error is clear in the second and third situation. We are comparing a list [0.2,0.3] to a float 0.1.
But would someone explain why it DOES work in the first situation?
Upvotes: 0
Views: 216
Reputation: 16906
This is called broadcasting which is supported by numpy. So when two operands in the operation are of different shapes, numpy will try to broadcast it and do the operation.
[0.2,0.3] >= 0
will not work because numpy is not involved here. You will get the error:TypeError: '>=' not supported between instances of 'list' and 'float'
np.array([1, 2, 3]) > 2
will work as numpy broadcasting will come into picture.[1, 2, 3] > np.float32(2)
will also workHowever,
[1, 2, 3] > np.float(2)
will not work because np.float
is just an alias to python float
. But np.float32
and np.float64
are np implementations of single and double precision number respectively.Upvotes: 2