【发布时间】:2020-03-04 02:29:39
【问题描述】:
我需要帮助才能在 keras 中创建自定义指标。我需要计算我的错误等于零的次数(y_pred - y_true = 0)。
我试过这个:
n_train = 1147 # Number of samples on training set
c = 0 # Variable to count
def our_metric(y_true, y_pred):
if y_true-y_pred == 0:
c += 1
return c/n_train
但是我收到了这个错误:
OperatorNotAllowedInGraphError: 使用
tf.Tensor作为 Pythonbool在 Graph 执行中是不允许的。使用 Eager 执行或装饰 这个函数带有@tf.function。
编辑:使用此处提出的解决方案:
Creating custom conditional metric with Keras
我这样解决了我的问题:
c = tf.constant(0)
def our_metric(y_true, y_pred):
mask = K.equal(y_pred, y_true) # TRUE if y_pred = y_true
mask = K.cast(mask,K.floatx())
s = K.sum(mask)
return s/n_train
【问题讨论】:
-
这与准确度指标完全相同
-
我使用了这里提出的解决方案:stackoverflow.com/questions/51902088/…