Constructor of a custom keras metric in evaluator called many times
Hi !
In this exemple of code ConfusionMatrix seems to be instantiated many time replacing an object which contains a good result (self.matrix) by an other one freshly instantiated .
How can I improve this sample of code ?
class ConfusionMatrix(tf.keras.metrics.Metric):
def __init__(self, name='ConfusionMatrix', **kwargs):
print("INIT")
super(ConfusionMatrix, self).__init__(name=name, **kwargs)
self.num_classes = 6
self.matrix = None
def update_state(self, y_true, y_pred, sample_weight=None):
print("UPDATE")
y_true = np.argmax(y_true, axis=-1)
y_pred = np.argmax(y_pred, axis=-1)
self.matrix = tf.math.confusion_matrix(labels=y_true, predictions=y_pred, num_classes=self.num_classes)
def result(self):
print("RESULT")
return self.matrix
def reset_states(self):
print("RESET")
self.matrix = None
Thank you
@PunyPony,
Can you elaborate what your issue is? Also, can you please confirm why you are using np.argmax function for y_true because usually it is not required. Thanks!
What is happening is that:
celery_worker | INIT
celery_worker | RESET
celery_worker | UPDATE #Contains a good value
celery_worker | INIT
celery_worker | INIT
celery_worker | INIT
celery_worker | INIT
celery_worker | RESULT #Return None
The first object wich have the result since update is calles seems to be replaced by others freshly instantiated objects. The problem is that I can't retrieve my confusion matrix because "result" is called on an object where the self.matrix is None. Maybe It's a bug ?
y_true, y_pred have the shape (test_set_size, num_classes) but that's not which is important here since update_state do not make any error.
Sorry for the slow response. Is this issue still there?
Also, this seems to be a problem with keras.Metric rather than TFX, so maybe we should move this issue to the Keras code repo?
It's not against you but I don't care (and I can't really reproduce it since I do not have the code anymore). Obviously you can move this issue at your convenience.
Thank you for your help anyways !
@PunyPony Please create an issue in keras-team/keras as this issue is related to keras. Thanks!!