Python Forum

Full Version: F-score, Precision, and Recall values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
from tensorflow.keras import backend as K
.
.
.
def computeMetrics(true, pred): # considering sigmoid activation, threshold = 0.5
pred = K.cast(K.greater(pred, 0.5), K.floatx())

gP = K.cast( K.sum(true), K.floatx()) + K.epsilon()
cP = K.sum(true * pred) + K.epsilon()
pP = K.sum(pred) + K.epsilon()

precision = cP / pP
recall = cP / gP
f1 = (2 * precision * recall) / (precision + recall)

return f1, precision, recall

metrics =computeMetrics(y_test, y_pred)

print('metrics -----> ',metrics)


output:
metrics -----> (<tf.Tensor 'truediv_2:0' shape=() dtype=float32>, <tf.Tensor 'truediv:0' shape=() dtype=float32>, <tf.Tensor 'truediv_1:0' shape=() dtype=float32>)



Anyone can help to get the values from the metrics ?
You return three values and assign these to one variable, so that´s a tuple. Nothing you really want.

Python has an interesting function named dir() to inspect variables
Using this one can see that there is a method .numpy() to return the value of a tensor.

f1, precision, recall = computeMetrics([1.0, 2.0, 3.0, 4.0], [1.1, 1.9, 3.2, 4.1])

print('metrics: ', f1.numpy(), precision.numpy(), recall.numpy())
Output:
metrics: 1.4285715 2.5 1.0
For readability i would return the values instead of the tensors

    return f1.numpy(), precision.numpy(), recall.numpy()

f1, precision, recall = computeMetrics([1.0, 2.0, 3.0, 4.0], [1.1, 1.9, 3.2, 4.1])

print('metrics: ', f1, precision, recall)
Thanks ThomasL
Now I am getting the following error:

print('metrics: ', f1.numpy(), precision.numpy(), recall.numpy())
AttributeError: 'numpy.float32' object has no attribute 'numpy'
>>>

I am not sure if this related to casting.
Did you use .numpy() twice?

    return f1.numpy(), precision.numpy(), recall.numpy()
 
f1, precision, recall = computeMetrics([1.0, 2.0, 3.0, 4.0], [1.1, 1.9, 3.2, 4.1])
 
print('metrics: ', f1.numpy(), precision.numpy(), recall.numpy())
AttributeError: 'numpy.float32' object has no attribute 'numpy'
means that the variables are already a numerical object that you can use/print directly
so delete the .numpy() or don´t use it twice on the same object.