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

在每个历元后重置度量的局部变量

  •  0
  • Natjo  · 技术社区  · 7 年前

    我使用内置的方法 tf.metrics.precision definition ,但局部变量永远不会重置。

    是否应该在每个历元之后重置它们,以便从最后一个历元中删除计数?这是自动完成的,而我只是在源代码中忽略了它,还是我应该这样做?如果后者为真,如何重置局部变量?我没有在文档中读到任何关于它的内容。

    2 回复  |  直到 7 年前
        1
  •  1
  •   javidcf    7 年前

    用于跟踪度量的变量是使用 metric_variable 函数,从而使用键添加到集合中 tf.GraphKeys.METRIC_VARIABLES . 定义所有指标后,可以执行如下重置操作:

    reset_metrics_op = tf.variables_initializer(tf.get_collection(tf.GraphKeys.METRIC_VARIABLES))
    

        2
  •  0
  •   ARAT    7 年前

    对在批量处理数据时,必须小心如何重置变量。在计算总体指标(即精度、准确度或auc)和批次指标时安排操作是不同的。在计算每批新数据的精度值之前,需要将运行变量重置为零。

    tf.metrics.precision ,将创建两个运行变量并将其放入计算图中: true_positives false_positives . 因此,您可以选择使用重置哪些变量 scope 论据 tf.get_collection()

    import tensorflow as tf
    import numpy as np
    
    import numpy as np
    import tensorflow as tf
    
    labels = np.array([[1,1,1,0],
                       [1,1,1,0],
                       [1,1,1,0],
                       [1,1,1,0]], dtype=np.uint8)
    
    predictions = np.array([[1,0,0,0],
                            [1,1,0,0],
                            [1,1,1,0],
                            [0,1,1,1]], dtype=np.uint8)
    
    precision, update_op = tf.metrics.precision(labels, predictions, name = 'precision')
    
    print(precision)
    #Tensor("precision/value:0", shape=(), dtype=float32)
    print(update_op)
    #Tensor("precision/update_op:0", shape=(), dtype=float32)
    
    tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES)
    #[<tf.Variable 'precision/true_positives/count:0' shape=() dtype=float32_ref>,
    # <tf.Variable 'precision/false_positives/count:0' shape=() dtype=float32_ref>,
    
    running_vars_precision = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='precision')
    running_vars_auc_initializer = tf.variables_initializer(var_list=running_vars_precision )
    
    with tf.Session() as sess:
        sess.run(running_vars_auc_initializer)
        print("tf precision/update_op: {}".format(sess.run([precision, update_op])))
        #tf precision/update_op: [0.8888889, 0.8888889]
        print("tf precision: {}".format(sess.run(precision)))
        #tf precision: 0.8888888955116272