Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 840
bylukas Avatar asked Oct 06 '19 09:10

bylukas


People also ask

What is the difference between TensorFlow 1 and 2?

(As per the TensorFlow team) It is important to understand that there is no battle of TensorFlow 1.0 vs TensorFlow 2.0 as TensorFlow 2.0 is the updated version and hence clearly better and smarter. It was built keeping in mind the drawbacks of TensorFlow 1.0 which was particularly hard to use and understand.

What does keras backend Clear_session () do?

clear_session function Resets all state generated by Keras. Keras manages a global state, which it uses to implement the Functional model-building API and to uniquify autogenerated layer names.

When did TensorFlow 2 come out?

In Jan 2019, Google announced TensorFlow 2.0. It became officially available in Sep 2019.


2 Answers

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() 
like image 58
donglinjy Avatar answered Oct 01 '22 02:10

donglinjy


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

like image 29
Upasana Mittal Avatar answered Oct 01 '22 02:10

Upasana Mittal