How to use K.get_session in Tensorflow 2.0 or how to migrate it?

30,198

Solution 1

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

Solution 2

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

Share:
30,198
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years
    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.

  • cserpell
    cserpell almost 4 years
    I have disabled eager execution, and I still have the get_session problem, so it is not related.
  • piotrwiercinski
    piotrwiercinski over 3 years
    I don't think this is related.