【问题标题】:finding accuracy of tensorflow model找到张量流模型的准确性
【发布时间】:2018-01-23 01:19:52
【问题描述】:

在用 sigmoid 函数训练这个简单的线性模型后,我试图找到准确度:

import numpy as np
import tensorflow as tf
import _pickle as cPickle

with open("var_x.txt", "rb") as fp:   # Unpickling
    var_x = cPickle.load(fp)

with open("var_y.txt", "rb") as fp:   # Unpickling
    var_y = cPickle.load(fp)

with open("var_x_test.txt", "rb") as fp:   # Unpickling
    var_x_test = cPickle.load(fp)

with open("var_y_test.txt", "rb") as fp:   # Unpickling
    var_y_test = cPickle.load(fp)

def model_fn(features, labels, mode):
  # Build a linear model and predict values
  W = tf.get_variable("W", [4], dtype=tf.float64)
  b = tf.get_variable("b", [1], dtype=tf.float64)
  y = tf.sigmoid( tf.reduce_sum(W*features['x']) + b)
  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=y)

  loss = tf.reduce_sum(tf.square(y - labels))

  global_step = tf.train.get_global_step()
  optimizer = tf.train.GradientDescentOptimizer(0.01)
  train = tf.group(optimizer.minimize(loss),
                   tf.assign_add(global_step, 1))

  return tf.estimator.EstimatorSpec(
      mode=mode,
      predictions=y,
      loss=loss,
      train_op=train)

estimator = tf.estimator.Estimator(model_fn=model_fn)

x_train = np.array(var_x)
y_train = np.array(var_y)
x_test = np.array(var_x_test)
y_test = np.array(var_y_test)

input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=60, shuffle=True)

estimator.train(input_fn=input_fn, steps=1000)

test_input_fn= tf.estimator.inputs.numpy_input_fn(
    x ={"x":np.array(x_test)},
    y=np.array(y_test),
    num_epochs=1,
    shuffle=False
    )

accuracy_score = estimator.evaluate(input_fn=test_input_fn["accuracy"])

print(accuracy_score)

但字典没有“准确度”键。我如何找到它?另外,如何使用 tensorboard 跟踪每一步后的准确率?

先谢谢了,tensorflow教程讲解的很烂。

【问题讨论】:

    标签: python tensorflow tensorflow-estimator


    【解决方案1】:

    您需要使用tf.metrics.accuracymodel_fn 中自己创建准确度,并将其传递给函数将返回的eval_metric_ops

    def model_fn(features, labels, mode):
        # define model...
        y = tf.nn.sigmoid(...)
        predictions = tf.cast(y > 0.5, tf.int64)
        eval_metric_ops = {'accuracy': tf.metrics.accuracy(labels, predictions)}
        #...
        return tf.estimator.EstimatorSpec(mode=mode, train_op=train_op, 
            loss=loss, eval_metric_ops=eval_metric_ops)
    

    然后estimator.evaluate() 的输出将包含一个准确度键,它将保存在验证集上计算的准确度。

    metrics = estimator.evaluate(test_input_fn)
    print(metrics['accuracy'])
    

    【讨论】:

    • 我按照你说的做了,但它抛出错误“NameError: name 'predictions' is not defined”。
    • 你必须像这样自己定义它:tf.argmax(y, axis=1)
    • 在您的情况下,您应该使用predictions = tf.cast(y > 0.5, tf.int64) sorry(当 sigmoid 的输出高于 0.5 时预测 1)。我已经更新了答案。
    • 链接坏了,这个是正确的吗? tensorflow.org/api_docs/python/tf/keras/metrics/Accuracy
    【解决方案2】:
    test_results = {}
    
    test_results['model'] = model.evaluate(
        test_features, test_labels, verbose=0)
    
    print(f" Accuracy: {test_results}")
    

    【讨论】:

    • 纯代码答案并不是特别有用。请简要说明此代码如何解决问题。
    【解决方案3】:
    accuracy_score = estimator.evaluate(input_fn=test_input_fn)
    print(accuracy_score["loss"]) 
    

    您可以像上面的方法一样获得损失以确保准确性。

    【讨论】:

    • 不起作用,字典没有“准确度”键。
    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 2018-01-19
    • 2017-02-02
    • 2018-07-03
    相关资源
    最近更新 更多