如何在Tensorflow 2.0中使用K.get_session或如何迁移它?

byl*_*kas 2 real-time machine-learning deep-learning keras tensorflow2.0

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()
Run Code Online (Sandbox Code Playgroud)

get_session使用TensorFlow 2.0时RuntimeError:不可用。

don*_*njy 6

Tensorflow 2.0不再直接公开backend.get_session,但是代码仍然存在并公开给tf1。

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

您可以将其与tf1兼容的接口一起使用:

sess = tf.compat.v1.keras.backend.get_session()
Run Code Online (Sandbox Code Playgroud)

或使用内部路径导入tenforflow后端:

import tensorflow.python.keras.backend as K
sess = K.get_session()
Run Code Online (Sandbox Code Playgroud)


Upa*_*tal 5

为了避免get_session在tensorflow 2.0升级后使用,使用tf.distribute.Strategy获取模型。要加载模型,请使用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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。因为这对我有用。

我也试图在这个实用程序文章中解释相同的内容。https://www.javacodemonk.com/runtimeerror-get_session-is-not-available-when-using-tensorflow-2-0-f7238546


小智 0

可能与默认启用的 tf 2.0 eagerexecution 有关。尝试导入tensorflow as tf

tf.compat.v1.disable_eager_execution()