【问题标题】:TensorFlow: tf.layers vs low-level APITensorFlow:tf.layers 与低级 API
【发布时间】:2017-12-10 14:22:12
【问题描述】:

我目前正在计划我的第一次转化。 Tensorflow 中的 NN 实现,并且一直在阅读 Tensorflow 的website 上的许多教程以获取见解。

似乎基本上有两种方法可以创建自定义 CNN:

1) 使用 Tensorflow 层模块tf.layers,它是“高级 API”。使用此方法,您定义一个由tf.layers 对象组成的模型定义函数,并在主函数中实例化一个tf.learn.Estimator,将模型定义函数传递给它。从这里,fit()evaluate() 方法可以在 Estimator 对象上调用,分别训练和验证。链接:https://www.tensorflow.org/tutorials/layers。主要功能如下:

def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
       tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)

完整代码here


2) 使用 Tensorflow 的“低级 API”,其中层在定义函数中定义。在这里,图层是手动定义的,用户必须手动执行许多计算。在主函数中,用户启动tf.Session(),并使用 for 循环手动配置训练/验证。链接:https://www.tensorflow.org/get_started/mnist/pros。主要功能如下:

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                        logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

完整代码here


我的困境是,我喜欢使用 tf.layers(选项 1)定义神经网络的简单性,但我想要“低级 API”(选项 2)提供的训练的可定制性。具体来说,当使用tf.layers 实现时,有没有办法在每 n 次训练迭代中报告验证准确度?或者更一般地说,我可以使用tf.Session() 进行训练/验证,还是仅限于使用tf.learn.Estimatorfit()evaluate() 方法?

在所有训练完成后想要一个最终评估分数似乎很奇怪,因为我认为验证的全部目的是在训练期间跟踪网络进展。否则,验证和测试有什么区别?

任何帮助将不胜感激。

【问题讨论】:

    标签: python machine-learning tensorflow neural-network conv-neural-network


    【解决方案1】:

    你几乎是对的,但是 tf.layersEstimator 类函数等是分开的。如果你愿意,你可以使用 tf.Layers 来定义你的层,然后构建你自己的训练循环或任何你喜欢的东西.您可以认为tf.Layers 只是您可以在上面的第二个选项中创建的那些函数。

    如果您对能够快速构建基本模型但能够使用其他功能、您自己的训练循环等进行扩展感兴趣,那么您没有理由不能使用层来构建您的模型并与之交互随心所欲。

    tf.Layers - https://www.tensorflow.org/api_docs/python/tf/layers

    tf.Estimator - https://www.tensorflow.org/api_docs/python/tf/estimator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-03
      • 2018-01-04
      • 2019-08-21
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多