0
votes

I'm using the following helper functions to compute Precision, Recall and F1-Score:

def recall_m(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

def precision_m(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

def f1_m(y_true, y_pred):
    precision = precision_m(y_true, y_pred)
    recall = recall_m(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))

I have tried the following imports for Keras:

import keras as K
import keras

But I get the error:

in f1_m(y_true, y_pred) 12 13 def f1_m(y_true, y_pred): ---> 14 precision = precision_m(y_true, y_pred) 15 recall = recall_m(y_true, y_pred) 16 return 2*((precision*recall)/(precision+recall+K.epsilon()))

in precision_m(y_true, y_pred) 6 7 def precision_m(y_true, y_pred): ----> 8 true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) 9 predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) 10 precision = true_positives / (predicted_positives + K.epsilon())

AttributeError: module 'keras' has no attribute 'sum'

How can I solve this ?

2

2 Answers

0
votes

I found a possible method to solve this:

Import the following:

import tensorflow.keras.backend as K

Instead of these:

import keras as K
import keras
0
votes

Either use

Import keras.backend as K

or

Import tensorflow.keras.backend as K

instead of

import keras as K # keras has no direct attribute sum

reference: https://www.tensorflow.org/api_docs/python/tf/keras/backend