Python 带有自定义估计器的Tensorflow度量
我最近重构了一个卷积神经网络,使用Tensorflow的估计器API,主要如下。但是,在培训期间,我添加到Estimator Spec中的度量没有显示在Tensorboard上,并且似乎没有在tfdbg中进行评估,尽管名称范围和度量存在于写入Tensorboard的图形中Python 带有自定义估计器的Tensorflow度量,python,tensorflow,Python,Tensorflow,我最近重构了一个卷积神经网络,使用Tensorflow的估计器API,主要如下。但是,在培训期间,我添加到Estimator Spec中的度量没有显示在Tensorboard上,并且似乎没有在tfdbg中进行评估,尽管名称范围和度量存在于写入Tensorboard的图形中 型号fn的相关位如下所示: ... predictions = tf.placeholder(tf.float32, [num_classes], name="predictions") ... with tf.
型号fn的相关位如下所示:
...
predictions = tf.placeholder(tf.float32, [num_classes], name="predictions")
...
with tf.name_scope("metrics"):
predictions_rounded = tf.round(predictions)
accuracy = tf.metrics.accuracy(input_y, predictions_rounded, name='accuracy')
precision = tf.metrics.precision(input_y, predictions_rounded, name='precision')
recall = tf.metrics.recall(input_y, predictions_rounded, name='recall')
if mode == tf.estimator.ModeKeys.PREDICT:
spec = tf.estimator.EstimatorSpec(mode=mode,
predictions=predictions)
elif mode == tf.estimator.ModeKeys.TRAIN:
...
# if we're doing softmax vs sigmoid, we have different metrics
if cross_entropy == CrossEntropyType.SOFTMAX:
metrics = {
'accuracy': accuracy,
'precision': precision,
'recall': recall
}
elif cross_entropy == CrossEntropyType.SIGMOID:
metrics = {
'precision': precision,
'recall': recall
}
else:
raise NotImplementedError("Unrecognized cross entropy function: {}\t Available types are: SOFTMAX, SIGMOID".format(cross_entropy))
spec = tf.estimator.EstimatorSpec(mode=mode,
loss=loss,
train_op=train_op,
eval_metric_ops=metrics)
else:
raise NotImplementedError('ModeKey provided is not supported: {}'.format(mode))
return spec
有人有没有想过为什么这些没有被写下来?我使用的是Tensorflow 1.7和Python 3.5。我曾尝试通过tf.summary.scalar
显式添加它们,虽然它们确实以这种方式进入了Tensorboard,但在第一次通过图形之后,它们永远不会更新 metrics API有一个转折点,让我们以tf.metrics.accurity
为例(所有tf.metrics.*
的工作原理都是一样的)。这将返回两个值,精度
度量和一个upate_op
,这似乎是您的第一个错误。你应该有这样的东西:
accuracy, update_op = tf.metrics.accuracy(input_y, predictions_rounded, name='accuracy')
accurity
只是您希望计算的值,但是请注意,您可能希望跨多个调用sess.run
计算精度,例如,当您计算不完全适合内存的大型测试集的精度时。这就是update\u op
的作用,它会累积结果,这样当你要求准确性时,它会给你一个连续的计数
update\u op
没有依赖项,因此您需要在sess.run中显式运行它,或者添加依赖项。例如,您可以将其设置为依赖于成本函数,以便在计算成本函数时计算update_op
(导致更新精度的运行计数):
可以使用局部变量初始值设定项重置度量值:
sess.run(tf.local_variables_initializer())
您将需要使用tf.summary.scalar(精度)
为tensorboard添加精度,正如您所提到的,您已经尝试过(尽管看起来您添加了错误的内容)。啊。。。。在每一个教程中,他们要么使用一个固定的估计器,要么按照我在那里写的那样做,不再提及。使用tf.summary.scalar手动执行--我知道元组的事情,但我很高兴您为子孙后代提到了它--并且控制依赖项工作正常,非常感谢!
sess.run(tf.local_variables_initializer())