Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to import Metric from tensorflow.keras.metrics

I want to write a custom metric evaluator for which I am following this link. my dummy code is

import tensorflow as tf    
from tensorflow import keras    

class DummyMetric(keras.metrics.Metric):

    def __init__(self, name='categorical_true_positives', **kwargs):
      super(DummyMetric, self).__init__(name=name, **kwargs)
      self.true_positives = self.add_weight(name='tp', initializer='zeros')

    def update_state(self, y_true, y_pred, sample_weight=None):
      print("Evaluating tensor of shape {} against gt of shape {}".format(y_pred.shape, y_true.shape))
      self.true_positives.assign_add(1.0)

    def result(self):
      return self.true_positives

    def reset_states(self):
      # The state of the metric will be reset at the start of each epoch.
      self.true_positives.assign(0.)

my tensorflow version is 1.13.1 installed from source.

keras.metrics.Metric throws

AttributeError: module 'tensorflow._api.v1.keras.metrics' has no attribute 'Metric'.

When I do pip install tensorflow-gpu==1.14 then this error goes away.

please suggest any solution/hack if possible which will make it work without upgrading to 1.14

like image 680
Pratik Kumar Avatar asked Jun 20 '19 14:06

Pratik Kumar


1 Answers

It seems like this was probably left out of an __init__.py and they fixed that in 1.14 I guess. I was able to import it this way:

from tensorflow.python.keras.metrics import Metric

It is defined in file:

tensorflow/python/keras/metrics.py
like image 84
David Parks Avatar answered Nov 09 '22 11:11

David Parks