无法从 tensorflow.keras.metrics 导入指标

Pra*_*mar 4 python keras tensorflow

我想编写一个自定义指标评估器,我正在关注此链接。我的虚拟代码是

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.)
Run Code Online (Sandbox Code Playgroud)

我的 tensorflow 版本是从源安装的 1.13.1

keras.metrics.Metric 投掷

AttributeError:模块“tensorflow._api.v1.keras.metrics”没有属性“Metric”。

当我这样做时,pip install tensorflow-gpu==1.14这个错误就会消失。

如果可能,请提出任何解决方案/黑客,这将使其在不升级到 1.14 的情况下工作

Dav*_*rks 6

似乎这可能被排除在外,__init__.py他们在 1.14 中修复了我猜。我能够以这种方式导入它:

from tensorflow.python.keras.metrics import Metric
Run Code Online (Sandbox Code Playgroud)

它在文件中定义:

tensorflow/python/keras/metrics.py
Run Code Online (Sandbox Code Playgroud)