Hi I am trying to save my 'saved models' (h5 files) as tensorflow file.This is the code I used.
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)
I tried to open the session manually by using sess = tf.session()
(removed with
as well) as well but in vain
And the above error I got when I used jupyter notebook and when I ran the same in linux terminal.I get the following error
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)]]
And when I tried to save just the one 'saved model file' it ran successfully.Problems happen only when I try to run it in a loop(probably some session problem).
I tried this answer in SO but didnt help much.
For me the following two options work:
Option 1: Add tf.keras.backend.clear_session()
at the beginning of your tensor_function
and use a 'with' block:
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()
Option 2: Use tf.Session()
instead of the 'with' block but add the line 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.