python - 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 循环?
解决方案
该错误非常具体。y_true 和 y_pred 是张量类型,你不能遍历它们。您可以尝试使用 to_numpy_array(y_pred) 将它们转换为 numpy 数组,执行您需要执行的操作,并像您已经在执行的那样返回一个张量值。
因此,一旦将 y_true 和 y_pred 转换为数组,就不需要在 for 循环中使用 K.constant,但函数必须返回张量值,因此请保留 K.constant((fn + fa + fo + fp)/4)。
推荐阅读
- firebase - 我可以使用此快照调用访问文档 ID 吗?
- javascript - jQuery 背景随 id 变化
- swift - 什么是suppressesIncrementalRendering?
- android - 与许多设备的蓝牙连接
- intellij-idea - Intellij 本地历史“贴标签”有什么意义?
- django - Nginx 502 网关错误 - gcp
- typescript - 如何查看来自 TypeScript 插件的日志?
- sql - SQL连接两个表并从两个表中删除重复项,但不会丢失表本身的任何重复项
- javascript - 部署到 Heroku 时如何使 api 端点以用户的本地主机为目标
- android - 如何添加重新发送otp firebase android的代码