python - 训练 tf.estimator 时记录准确度指标

标签 python tensorflow tensorboard tensorflow-estimator

在训练预先设定的估算器时,打印精度指标以及损失的最简单方法是什么?

大多数教程和文档似乎都在解决您何时创建自定义估算器的问题——如果打算使用其中一个可用的估算器,这似乎有点过分了。

tf.contrib.learn 有一些(现已弃用)监视器 Hook 。 TF 现在建议使用 hook API,但它似乎实际上并没有附带任何可以利用标签和预测来生成准确度数字的东西。

最佳答案

您是否尝试过 tf.contrib.estimator.add_metrics(estimator, metric_fn) ( doc )?它需要一个初始化的估计器(可以预先封装)并向其添加 metric_fn 定义的指标。

使用示例:

def custom_metric(labels, predictions):
    # This function will be called by the Estimator, passing its predictions.
    # Let's suppose you want to add the "mean" metric...

    # Accessing the class predictions (careful, the key name may change from one canned Estimator to another)
    predicted_classes = predictions["class_ids"]  

    # Defining the metric (value and update tensors):
    custom_metric = tf.metrics.mean(labels, predicted_classes, name="custom_metric")

    # Returning as a dict:
    return {"custom_metric": custom_metric}

# Initializing your canned Estimator:
classifier = tf.estimator.DNNClassifier(feature_columns=columns_feat, hidden_units=[10, 10], n_classes=NUM_CLASSES)

# Adding your custom metrics:
classifier = tf.contrib.estimator.add_metrics(classifier, custom_metric)

# Training/Evaluating:
tf.logging.set_verbosity(tf.logging.INFO) # Just to have some logs to display for demonstration

train_spec = tf.estimator.TrainSpec(input_fn=lambda:your_train_dataset_function(),
                                    max_steps=TRAIN_STEPS)
eval_spec=tf.estimator.EvalSpec(input_fn=lambda:your_test_dataset_function(),
                                steps=EVAL_STEPS,
                                start_delay_secs=EVAL_DELAY,
                                throttle_secs=EVAL_INTERVAL)
tf.estimator.train_and_evaluate(classifier, train_spec, eval_spec)

日志:

...
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Evaluation [20/200]
INFO:tensorflow:Evaluation [40/200]
...
INFO:tensorflow:Evaluation [200/200]
INFO:tensorflow:Finished evaluation at 2018-04-19-09:23:03
INFO:tensorflow:Saving dict for global step 1: accuracy = 0.5668, average_loss = 0.951766, custom_metric = 1.2442, global_step = 1, loss = 95.1766
...

如您所见,custom_metric 随默认指标和损失一起返回。

关于python - 训练 tf.estimator 时记录准确度指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890477/

相关文章:

python - InaccessibleTensorError - 在另一层的循环条件中使用 `tf.keras.layers.Layer` 输出时

python - 如何跳过数组中的特定索引?

python - 打印输出()类型错误 bool

python - 如何迭代 Tensorflow 中的张量?

python - @tf.function 中的 if-else

tensorflow - 如何在张量板中显示我的所有图像?

tensorboard - TensorFlow 2.0 - 图表未显示在 TensorBoard 中

tensorflow - Tensorboard 标量和图形重复

python - pandas 扩展(累积)value_counts

python - 尝试在 Flask View 中实例化 WTForms 对象时出现 "Runtime Error: working outside of application context"