tfx icon indicating copy to clipboard operation
tfx copied to clipboard

Constructor of a custom keras metric in evaluator called many times

Open PunyPony opened this issue 6 years ago • 6 comments

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 avatar Nov 19 '20 09:11 PunyPony

@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!

rmothukuru avatar Nov 23 '20 06:11 rmothukuru

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.

PunyPony avatar Nov 23 '20 10:11 PunyPony

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?

zhitaoli avatar Jun 17 '21 18:06 zhitaoli

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 avatar Jun 17 '21 19:06 PunyPony

@PunyPony Please create an issue in keras-team/keras as this issue is related to keras. Thanks!!

gowthamkpr avatar Sep 21 '22 22:09 gowthamkpr

Are you satisfied with the resolution of your issue? Yes No

google-ml-butler[bot] avatar Sep 21 '22 22:09 google-ml-butler[bot]