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

偶尔善良 提交于 2020-05-29 02:29:44

问题


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.


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/58255821/how-to-use-k-get-session-in-tensorflow-2-0-or-how-to-migrate-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!