我正在尝试学习如何在 Tensorflow 中创建我自己的自定义流指标。
我首先尝试编写自己的函数来计算 f1 分数。
这是我目前所拥有的:
import tensorflow as tf
import numpy as np
from sklearn.metrics import precision_recall_fscore_support, f1_score, precision_score
sess = tf.InteractiveSession()
# Custom streaming metric to compute f1 score.
# Code is from answer to https://stackoverflow.com/questions/44764688/custom-metric-based-on-tensorflows-streaming-metrics-returns-nan/44935895
def metric_fn(predictions=None, labels=None, weights=None):
P, update_op1 = tf.contrib.metrics.streaming_precision(predictions, labels)
R, update_op2 = tf.contrib.metrics.streaming_recall(predictions, labels)
eps = 1e-5;
return (2*(P*R)/(P+R+eps), tf.group(update_op1, update_op2))
# True labels
labels = np.array([1, 0, 0, 1])
# Predicted labels
preds = np.array([1, 1, 0, 1])
f1 = metric_fn(preds, labels)
init1 = tf.global_variables_initializer()
init2 = tf.local_variables_initializer()
sess.run([init1, init2])
# Check result with output from sklearn
print(f1_score(labels, preds))
# Run a custom metric a few times
print(sess.run(f1))
print(sess.run(f1))
print(sess.run(f1))
这是我得到的输出:
0.8
(0.0, None)
(0.99999624, None)
(0.79999518, None)
第一行是使用 sklearn 的 f1_score 函数计算的 f1 分数,这是正确的。其余来自 metric_fn。
我不理解 metric_fn 的输出。为什么 metric_fn 的结果总是改变,即使我给它相同的输出?此外,它的结果都不正确,即使我编码的公式是正确的。发生了什么事,我需要进行哪些更改才能获得正确的结果?
请您参考如下方法:
您可以通过这种方式将metric_fn 的输出分成两部分:
f1_value, update_op = metric_fn(preds, labels)
其中 f1_value 是您分数的当前值,update_op 是采用预测值和标签的新值并更新 f1 分数的操作。
因此,在这种情况下,您可以这样更改代码:
import tensorflow as tf
import numpy as np
from sklearn.metrics import precision_recall_fscore_support, f1_score, precision_score
sess = tf.InteractiveSession()
# Custom streaming metric to compute f1 score.
# Code is from answer to https://stackoverflow.com/questions/44764688/custom-metric-based-on-tensorflows-streaming-metrics-returns-nan/44935895
def metric_fn(predictions=None, labels=None, weights=None):
P, update_op1 = tf.contrib.metrics.streaming_precision(predictions, labels)
R, update_op2 = tf.contrib.metrics.streaming_recall(predictions, labels)
eps = 1e-5;
return (2*(P*R)/(P+R+eps), tf.group(update_op1, update_op2))
# True labels
labels = np.array([1, 0, 0, 1])
# Predicted labels
preds = np.array([1, 1, 0, 1])
f1_value, update_op = metric_fn(preds, labels)
init1 = tf.global_variables_initializer()
init2 = tf.local_variables_initializer()
sess.run([init1, init2])
# Check result with output from sklearn
print(f1_score(labels, preds))
# Run a custom metric a few times
print(sess.run(f1_value))
print(sess.run(update_op))
print(sess.run(f1_value))
如预期的那样,您会得到:
0.8 # Obtained with sklearn
0.0 # Value of f1_value before calling update_op
None # update_op does not return anything
0.799995 # Value of f1_value after calling update_op
请注意,update_op 返回 None 仅仅是因为使用 tf.group 创建的操作没有输出。每个 update_op1 和 update_op2 将分别返回 1.0 和 0.6666667。
