将Keras模型转换为张量流模型会给我带来错误

时间:2019-03-04 10:38:27

标签: python tensorflow keras

嗨,我正在尝试将“保存的模型”(h5文件)另存为张量流文件。这是我使用的代码。

import tensorflow as tf
def tensor_function(i):
    tf.keras.backend.set_learning_phase(0)  # Ignore dropout at inference
    model = tf.keras.models.load_model('/home/ram/Downloads/AutoEncoderModels_ch2/19_hour/autoencoder_models_ram/auto_encoder_model_pos_' + str(i) + '.h5')
    export_path = '/home/ram/Desktop/tensor/' + str(i)
    #sess = tf.Session()

    # Fetch the Keras session and save the model
    # The signature definition is defined by the input and output tensors
    # And stored with the default serving key
    with tf.keras.backend.get_session() as sess:
        tf.saved_model.simple_save(
            sess,
            export_path,
            inputs={'input_image': model.input},
            outputs={t.name: t for t in model.outputs})
        sess.close()

for i in range(4954):
    tensor_function(i)

我也尝试通过使用sess = tf.session()(也已删除with)来手动打开会话,但徒劳

上面的错误是我在使用jupyter笔记本时和在Linux终端中运行该错误时得到的。

tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_73/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_73/bias)
     [[{{node dense_73/bias/Read/ReadVariableOp}} = ReadVariableOp[_class=["loc:@dense_73/bias"], dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dense_73/bias)]]

当我尝试仅保存一个“保存的模型文件”时,它成功运行。仅当我尝试以循环方式运行它时,问题才会发生(可能是某些会话问题)。

我尝试了this answer,但并没有太大帮助。

1 个答案:

答案 0 :(得分:1)

对我来说,以下两个选项有效:

选项1:tf.keras.backend.clear_session()的开头添加tensor_function并使用'with'块:

def tensor_function(i):
    tf.keras.backend.clear_session()
    tf.keras.backend.set_learning_phase(0)  # Ignore dropout at inference

    model = ...

    export_path = 'so-test/' + str(i)

    with tf.keras.backend.get_session() as sess:
        tf.saved_model.simple_save(
            sess,
            export_path,
            inputs={'input_image': model.input},
            outputs={t.name: t for t in model.outputs})
        sess.close()

选项2:使用tf.Session()代替'with'块,但添加行sess.run(tf.global_variables_initializer())

def tensor_function(i):
    tf.keras.backend.set_learning_phase(0)  # Ignore dropout at inference

    model = ...

    export_path = 'so-test/' + str(i)
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    tf.saved_model.simple_save(
        sess,
        export_path,
        inputs={'input_image': model.input},
        outputs={t.name: t for t in model.outputs})
    sess.close()