首页 > 解决方案 > Keras 指标实现

问题描述

我正在尝试使用 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 循环?

标签: pythontensorflowkerasmetrics

解决方案


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

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


推荐阅读