Tensorflow: setting default session using as_default().__enter__()

后端 未结 1 709
执笔经年
执笔经年 2021-01-21 00:24

I write

import tensorflow as tf
x = tf.Session()
x.as_default().__enter__()
print(tf.get_default_session()) # prints \"None\"

Why am I not acco

1条回答
  •  逝去的感伤
    2021-01-21 01:08

    Simple fix:

    import tensorflow as tf
    x = tf.Session().__enter__()
    print(tf.get_default_session())
    

    Result:

    
    

    Cause:

    as_default() is returning a context manager, not a session, you're calling enter on a _GeneratorContextManager object when you mean to enter a Session object.

    >>> tf.Session().as_default()
    
    >>> tf.Session()
    
    

    Update

    To answer your (initially perplexing) follow up question:

    What you are doing with the with statement is entering and exiting the context manager. This is causing the default session to be set and unset. But it is not opening and closing your session (it appears, this was confusing to me and I'm only seeing it after some experimentation). Try this code out to see it operate:

    >>> print(tf.get_default_session())
    None
    
    >>> x = tf.Session()
    >>> print(tf.get_default_session())
    None
    
    >>> with x.as_default():
    ...     print(tf.get_default_session())
    ... 
    
    >>> print(x)
    
    

    We see at the end of those statements that your session never closed, but along the way we see that the default session was set and unset as expected.

    Using the standard with statement both closes the session and sets/unsets the default session.

    >>> with tf.Session() as sess:
    ...     print(tf.get_default_session())
    
    

    0 讨论(0)
提交回复
热议问题