张量流tf.metrics.平均值返回0

2024-04-24 13:14:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用函数tf.metrics.mean_iou作为FCN的语义分段。只有在IoU之前计算混淆矩阵,否则返回0。在

以下是我的例子:

此示例返回正确的值0.66071427

import tensorflow as tf
import numpy as np

y_pred0 = np.array([   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ],   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ]    ])
y_pred1 = tf.constant(y_pred0)
y_pred2 = tf.argmax(y_pred1, axis=3)

y_label = np.array([[[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]], [[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]]])
y_label2 = tf.constant(y_label)

iou, conf_mat = tf.metrics.mean_iou(y_label2, y_pred2, num_classes=2)

sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

sess.run(conf_mat)
res = sess.run(iou)

print(res)

一。在

此示例返回0

^{pr2}$

如果有一个计算平均IoU的函数而不初始化其中的所有变量,那将是非常好的。有没有办法修正第二个例子?我认为问题在于同时计算IoU和混淆矩阵,我没有找到另一种方法,比如通过Session()分别运行它们。在

谢谢


Tags: 函数runimport示例tfasnp矩阵
1条回答
网友
1楼 · 发布于 2024-04-24 13:14:51

在从张量获取iou值之前,需要运行tf.metrics.mean_iou返回的更新操作。在

以下是固定代码:

import tensorflow as tf
import numpy as np

def intersection_over_union(prediction, labels):
    pred = tf.argmax(prediction, axis=3)
    labl = tf.constant(labels)
    iou, conf_mat = tf.metrics.mean_iou(labl, pred, num_classes=2)
    return iou, conf_mat

y_pred0 = np.array([   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ],   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ]    ])
y_pred1 = tf.constant(y_pred0)

y_label = np.array([[[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]], [[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]]])

mean__iou, conf_mat = intersection_over_union(y_pred1, y_label)

sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

sess.run([conf_mat])
res = sess.run(mean__iou)

print(res)

返回正确的值:0.66071427

相关问题 更多 >