Tensorflow eval()没有会话或移动变量到其他会话

时间:2016-11-23 15:26:41

标签: python numpy tensorflow

我使用的是像iris predict examples中描述的张量流模型。因为我没有会话对象。现在我想将标签转换为带有.eval()的numpy数组。没有会话就会出现错误。

Traceback (most recent call last):
 File "myfile.py", line 273, in <module>
   tf.app.run()
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/platform/app.py", line 30, in run
   sys.exit(main(sys.argv))
 File "myfile.py", line 270, in main
   train_and_eval()
 File "myfile.py", line 258, in train_and_eval
   label.eval()
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 559, in eval
   return _eval_using_default_session(self, feed_dict, self.graph, session)
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 3642, in _eval_using_default_session
   raise ValueError("Cannot evaluate tensor using `eval()`: No default "
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`

是否有可能访问/获取后台使用的模型的会话?或者是否有其他可能将张量转换为numpy-array?

如果我创建一个新会话,那么似乎tensorflow移动到此会话但无法访问该变量。显示一个python print(),但它会运行inifite。如何将变量解析为此新会话?

网络的另一部分运行良好 - 只有这个特殊的东西将张量转换为numpy-array

    COLUMNS = ["col1", "col2", "col3", "target"]
    LABEL_COLUMN = "target"
    CATEGORICAL_COLUMNS = ["col1", "col2", "col3"]

    def build_estimator(model_dir):
        col1 = tf.contrib.layers.sparse_column_with_hash_bucket(
            "col1", hash_bucket_size=10000)
        col2........

        wide_columns = [col1, col2, col3]
        deep_columns = [
            tf.contrib.layers.embedding_column(col1, dimension=7),
            tf.contrib.layers.embedding_column(col2, dimension=7),
            tf.contrib.layers.embedding_column(col3, dimension=7)
        ]

        m = tf.contrib.learn.DNNLinearCombinedClassifier(...)
        return m

    def input_fn(file_names, batch_size):
        ...
        label = tf.string_to_number(examples_dict[LABEL_COLUMN], out_type=tf.int32)
        return feature_cols, label

    def train_and_eval():
        model_dir = "./model/"
        print(model_dir)

        m = build_estimator(model_dir)
        m.fit(input_fn=lambda: input_fn(train_file_name, batch_size), steps=steps)
        results = m.evaluate(input_fn=lambda: input_fn(test_file_name, batch_size),
            steps=1)
        pred_m = m.predict(input_fn=lambda: input_fn(test_file_name, batch_size))


        sess = tf.InteractiveSession()
        with sess.as_default():
            print("Is a session there?")
            _, label = input_fn(test_file_name, batch_size)
            label.eval()
            print(label)

    def main(_):
        train_and_eval()

    if __name__ == "__main__":
        tf.app.run()

新会话从代码段末尾开始:

        sess = tf.InteractiveSession()
        with sess.as_default():
            print("Is a session there?")
            _, label = input_fn(test_file_name, batch_size)
            label.eval()
            print(label)

3 个答案:

答案 0 :(得分:1)

您需要一个会话,并且需要先初始化变量才能访问它们:

with Session() as sess:
    sess.run(tf.global_variables_initializer())
    ...  
    label_numpy = label.eval()

答案 1 :(得分:1)

我改变了顺序以解决我的问题。

     import tensorflow as tf
     v= tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
     result = tf.clip_by_value(v, 2.5, 4.5).eval()
     with tf.Session() as sess:
          print(sess.run(result))

然后我的IDE警告“ValueError:无法使用eval()评估张量:没有注册默认会话。使用with sess.as_default()或将显式会话传递给eval(session=sess)

之后,我将其改为:

    import tensorflow as tf
    v= tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
    with tf.Session() as sess:
        result = tf.clip_by_value(v, 2.5, 4.5).eval()
        print(sess.run(result))

然后问题就解决了。

答案 2 :(得分:0)

当我尝试创建一些自定义指标/损失函数时,我遇到了同样的问题。我最终要做的是使用tf.py_func或更好的tf.py_function来调用python函数。 (Tensorflow Doc)。

传递给该函数的张量应该被转换为numpy数据/数组。 py_funcpy_function之间的唯一区别是,使用py_func时,Tensor会自动变成一个numpy数组,而使用py_function时,它仍然是Tensor,您必须手动调用.numpy()

Tensorflow将为您添加此调用到图形执行中。

def train_and_eval():
    ...
    with Session() as sess:
        sess.run(tf.global_variables_initializer())
        ...
        labels = #some tensor
        other = #some tensor
        result = tf.py_function(some_function, [labels, other], [tf.float64]) # where the last argument
        # is an array representing the return type(s) of `some_function()`.
        # If `some_function` returns nothing, then you can do
        # tf.py_function(some_function, [labels, other], [])

# your normal python function
def some_function(labels, other):
    '''
    If you called this through py_func, the inputs are already numpy arrays,
    if you called through py_function, they're Tensors and you have to call
    labels.numpy() and other.numpy() to turn them to numpy.
    '''
    labels, other = labels.numpy(), other.numpy()
    print(labels)