代码之家  ›  专栏  ›  技术社区  ›  viksit

训练tf时记录精度指标。估计员

  •  12
  • viksit  · 技术社区  · 6 年前

    在培训预先确定的估计员时,打印精度指标和损失的最简单方法是什么?

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

    tf。承包商。learn有几个(现已弃用)监视器挂钩。TF现在建议使用钩子API,但似乎它实际上没有提供任何可以利用标签和预测来生成准确数字的东西。

    2 回复  |  直到 6 年前
        1
  •  10
  •   benjaminplanche    6 年前

    你试过了吗 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 随默认指标和损失一起返回。

        2
  •  4
  •   tsveti_iko    6 年前

    除了@Aldream的答案外,您还可以使用 TensorBoard 查看 custom_metric 。为此,请将其添加到TensorFlow摘要中,如下所示:

    tf.summary.scalar('custom_metric', custom_metric)
    

    使用 tf.estimator.Estimator 您不需要将摘要添加到 FileWriter ,因为它是自动完成的(默认情况下每100步合并并保存一次)。

    要查看张力板,需要打开一个新的端子并键入:

    tensorboard --logdir={$MODEL_DIR}
    

    之后,您将能够在以下位置在浏览器中查看图形: localhost:6006

    推荐文章