Tensorflow估计器API:概述

Tensorflow估计器API:概述,tensorflow,Tensorflow,我无法使用Tensorflow的估计器API进行总结 Estimator类非常有用,原因有很多:我已经实现了我自己的类,这些类非常相似,但我正在尝试切换到这个类 以下是代码示例: import tensorflow as tf import tensorflow.contrib.layers as layers import tensorflow.contrib.learn as learn import numpy as np # To reproduce the error: docke

我无法使用Tensorflow的估计器API进行总结

Estimator类非常有用,原因有很多:我已经实现了我自己的类,这些类非常相似,但我正在尝试切换到这个类

以下是代码示例:

import tensorflow as tf
import tensorflow.contrib.layers as layers
import tensorflow.contrib.learn as learn
import numpy as np

 # To reproduce the error: docker run --rm -w /algo -v $(pwd):/algo tensorflow/tensorflow bash -c "python sample.py"

def model_fn(x, y, mode):
    logits = layers.fully_connected(x, 12, scope="dense-1")
    logits = layers.fully_connected(logits, 56, scope="dense-2")
    logits = layers.fully_connected(logits, 4, scope="dense-3")

    loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y), name="xentropy")

    return {"predictions":logits}, loss, tf.train.AdamOptimizer(0.001).minimize(loss)


def input_fun():
    """ To be completed for a 4 classes classification problem """

    feature = tf.constant(np.random.rand(100,10))
    labels = tf.constant(np.random.random_integers(0,3, size=(100,)))

    return feature, labels

estimator = learn.Estimator(model_fn=model_fn, )

trainingConfig = tf.contrib.learn.RunConfig(save_checkpoints_secs=60)

estimator = learn.Estimator(model_fn=model_fn, model_dir="./tmp", config=trainingConfig)

# Works
estimator.fit(input_fn=input_fun, steps=2)

# The following code does not work

# Can't initialize saver

# saver = tf.train.Saver(max_to_keep=10) # Error: No variables to save

# The following fails because I am missing a saver... :(

hooks=[
        tf.train.LoggingTensorHook(["xentropy"], every_n_iter=100),
        tf.train.CheckpointSaverHook("./tmp", save_steps=1000, checkpoint_basename='model.ckpt'),
        tf.train.StepCounterHook(every_n_steps=100, output_dir="./tmp"),
        tf.train.SummarySaverHook(save_steps=100, output_dir="./tmp"),
]

estimator.fit(input_fn=input_fun, steps=2, monitors=hooks)
如您所见,我可以创建一个估计器并使用它,但我可以实现在拟合过程中添加挂钩

日志挂钩工作得很好,但其他挂钩既需要张量,也需要保存程序,我无法提供

张量是在模型函数中定义的,因此我无法将它们传递给SummaryHook,而保存程序也无法初始化,因为没有要保存的张量

有办法解决我的问题吗?(我猜是的,但tensorflow文档中缺少该部分的文档)

  • 如何初始化我的保存程序?或者我应该使用其他物体,如脚手架
  • 既然在我的模型函数中定义了汇总,我如何将汇总传递给汇总钩子
提前谢谢


PS:我已经看过DNNClassifier API,但我想将估计器API用于卷积网和其他方面。我需要为任何估计器创建摘要。

预期的用例是让估计器为您保存摘要。中有用于配置摘要编写的选项。RunConfigs在。

仅在
模型中的
tf.summary.scalar(“loss”,loss)
中通过,并且在没有
摘要钩子的情况下运行代码。损耗记录并显示在张力板上


另见:


好的,我明白了。但是如何定义要保存的摘要?我应该在模型函数中使用标准的标量摘要函数吗?是的,这些应该被添加到摘要集合中并自动保存。@Allen Lavoie我在tensorflow Quickstart Guide/Working with Estimator上找不到这些信息。你们应该明确说明:“将您的摘要添加到收藏中-就是这样”@Pietrko感谢您的反馈。您介意吗(或者如果您有具体的更改,请提出请求)?@Allen Lavoie我想到的更改更多地是记录tensorflow API和HOW-to文档上的现有行为,而不是代码的更改。如果在我找到文档后发现了这些文档,我将很高兴为它们打开Github问题。