0

I am trying to calculate F1_Score using numpy array using the code below

ypred = np.squeeze(imgs_mask_predict[jj,:,:,:])
ytrue = np.squeeze(imgs_test_mask[jj,:,:,:])

def f1_score_single(y_true, y_pred):
    y_true = y_true.flatten('F')
    y_pred = y_pred.flatten('F')
    cross_size = len(y_true & y_pred)
    if cross_size == 0: return 0.
    p = 1. * cross_size / len(y_pred)
    r = 1. * cross_size / len(y_true)
    return (2. * (p * r) / (p + r))

I get an error

"ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' " at this line of code

    cross_size = len(y_true & y_pred)

I tried to search for this error but did not get the reason and solution for this. How should I resolve this?

7
  • What are y_true.dtype and y_pred.dtype? Commented Feb 14, 2018 at 14:13
  • y_true type <class 'numpy.ndarray'> y_pred type <class 'numpy.ndarray'> y_true shape (256, 160) y_pred shape (256, 160) Commented Feb 14, 2018 at 14:20
  • 1
    That looks like type(y_true) and y_true.shape. Now show us y_true.dtype and y_pred.dtype. The dtype attribute tells you the data type of the data in the numpy array. Commented Feb 14, 2018 at 14:21
  • dtype is float32 Commented Feb 14, 2018 at 14:23
  • 1
    Ah. Why are you trying to use the & operator (which for numpy arrays is bitwise-and) with floating point values? That operator only makes sense (for some definition of "sense") with integer values. Commented Feb 14, 2018 at 14:25

2 Answers 2

2

You should use isclose for floating point numbers.

cross_size = np.isclose(y_true, y_pred).sum()

You can also set a threshold for similarity by atol and rtol keyword arguments, you can see the documentation here.

Sign up to request clarification or add additional context in comments.

Comments

0

you can try intersect1d instead of &, for example, the use of np.intersect1d will do the same as you intend to do with &

import numpy as np
y_true=np.array([1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0])
y_score=np.array([1.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0])
x=np.intersect1d(y_true, y_score)
print(x)

the result will be [1. 2. 4.]

you can test the program here https://www.programiz.com/python-programming/online-compiler/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.