20
def __init__(self, **kwargs):
    self.__dict__.update(self._defaults) # set up default values
    self.__dict__.update(kwargs) # and update with user overrides
    self.class_names = self._get_class()
    self.anchors = self._get_anchors()
    self.sess = K.get_session()

RuntimeError: get_session is not available when using TensorFlow 2.0.

bylukas
  • 201
  • 1
  • 2
  • 4

4 Answers4

30

Tensorflow 2.0 does not expose the backend.get_session directly any more but the code still there and expose for tf1.

https://github.com/tensorflow/tensorflow/blob/r2.0/tensorflow/python/keras/backend.py#L465

You can use it with tf1 compatible interface:

sess = tf.compat.v1.keras.backend.get_session()

Or import tenforflow backend with internal path:

import tensorflow.python.keras.backend as K
sess = K.get_session()
donglinjy
  • 922
  • 4
  • 13
4

In order to avoid using get_session after tensorflow 2.0 upgrade, Use tf.distribute.Strategy to get model. To load model, use tf.keras.models.load_model

import tensorflow as tf

another_strategy = tf.distribute.MirroredStrategy()
with another_strategy.scope():
    model = Service.load_deep_model()

def load_deep_model(self, model):
    loaded_model = tf.keras.models.load_model("model.h5")
    return loaded_model

Hope this helps. As this worked for me.

I have tried to explain same at this utility article as well. https://www.javacodemonk.com/runtimeerror-get_session-is-not-available-when-using-tensorflow-2-0-f7238546

Upasana Mittal
  • 1,816
  • 9
  • 17
0

Probably has something to do with tf 2.0 eager execution that is enabled by default. Try import tensorflow as tf

tf.compat.v1.disable_eager_execution()

Miles High
  • 27
  • 3
0

I had the same error and tried installing and uninstalling. In the end, I found that the library was not actually installed correctly.

I went through each library in my:

C:\Users\MyName\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\

I tracked down the file in within the site-packages in Keras, which was calling from the Tensorflow library, which was calling from another folder. I found the final folder had the get_session(), but this was not being called in. When I checked the directory, I found that get_session wasn't being loaded in. Within the file directory /tensorflow/keras/backend.py it was importing everything, but missed out the get_session.

To fix this I added this line:

from tensorflow.python.keras.backend import get_session

Then saved it. The next time I ran my code it was fine.

I gave the same answer for this page How to fix ' module 'keras.backend.tensorflow_backend' has no attribute '_is_tf_1''

SHEP AI
  • 31
  • 4