【问题标题】:Keras metric implementationKeras 指标实现
【发布时间】:2020-03-13 15:15:23
【问题描述】:

我正在尝试使用 Keras 构建一个模型,该模型使用一个指标:一个特殊的 f1 分数。我正在努力实现它。

到目前为止,我有:

def f1_metric(y_true,y_pred):
   y_pred = K.one_hot(indices=K.argmax(y_pred,1), num_classes=4)
   arr = np.zeros((4,4))
   for pred,true in zip(y_pred,y_true):
       c_pred = K.constant(K.argmax(pred))
       c_true = K.constant(K.argmax(true))
       arr[c_true][c_pred] += 1
   fn = 2*arr[0][0]/(np.sum(arr[0]) + np.sum(arr.T[0])) if (np.sum(arr[0]) + np.sum(arr.T[0])) != 0 else 0
   fa = 2*arr[1][1]/(np.sum(arr[1]) + np.sum(arr.T[1])) if (np.sum(arr[1]) + np.sum(arr.T[1])) != 0 else 0
   fo = 2*arr[2][2]/(np.sum(arr[2]) + np.sum(arr.T[2])) if (np.sum(arr[2]) + np.sum(arr.T[2])) != 0 else 0
   fp = 2*arr[3][3]/(np.sum(arr[3]) + np.sum(arr.T[3])) if (np.sum(arr[3]) + np.sum(arr.T[3])) != 0 else 0
   return K.constant((fn + fa + fo + fp)/4)

当我使用 f1_metric 函数时出现以下错误: OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed

我明白不能使用循环。我已经阅读了一段时间,但仍然找不到替代品。

如何正确实现我的 for 循环?

【问题讨论】:

    标签: python tensorflow keras metrics


    【解决方案1】:

    错误非常具体。 y_true 和 y_pred 是张量类型,你不能遍历它们。您可以尝试使用 to_numpy_array(y_pred) 将它们转换为 numpy 数组,执行您需要执行的操作,并像您已经在执行的那样返回一个张量值。

    因此,一旦将 y_true 和 y_pred 转换为数组,就不需要在 for 循环中使用 K.constant,但函数必须返回张量值,因此请留在那里 K.constant((fn + fa + fo + fp)/4) .

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2018-12-04
      • 1970-01-01
      • 2019-05-21
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多