Tensorflow eval() without session or move variable to an other session

18,476

Solution 1

You need a Session and you need to initialize your variables before being able to access them:

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

Solution 2

I changed the order so as to solved my problem.

     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))

Then my IDE warned"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)"

Afterwards, I changed it into:

    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))

Then the problem is solved.

Share:
18,476
Gersee
Author by

Gersee

Updated on June 29, 2022

Comments

  • Gersee
    Gersee almost 2 years

    I'm using tensorflow-models like it is described in the iris predict examples. Because of that I do not have a session object. Now I want to convert the labels to a numpy-array with .eval(). Without a session there comes an error.

    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)`
    

    Is there a possibility to access / get the session the model used in background? Or is there an other possibility to convert the tensor to a numpy-array?

    If I create a new session, then it seems that tensorflow moves to this session but has no access to the variable. A python print() is displayed, but then it runs inifite. How can I parse a variable to this new session?

    The other part of the net works well - it's only this special thing convert the tensor to a 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()
    

    The new session starts at the end of the code-snippet:

            sess = tf.InteractiveSession()
            with sess.as_default():
                print("Is a session there?")
                _, label = input_fn(test_file_name, batch_size)
                label.eval()
                print(label)
    
  • Gersee
    Gersee over 7 years
    Thanks for your support. But this does not work like it was asked. I can use the new session (this already worked with my code), but I do not have access to the variables of the other session. How can I pass them to the new session? Or alternatively how can I change my code / the iris predict example to use an explicit session or how can I get access to the default session of this code?
  • ribbit
    ribbit about 4 years
    Did you ever find how to do this?