简体   繁体   中英

Saving model and initialization in Keras

I have created a model in Keras, which I then initialised by calling

session=tf.Session()
session.run(tf.global_variables_initializer())

After training, I tried to save the model by running

saver = tf.train.Saver()
saver.save(session, "action_inference_cart_pole_plan16_5000episode.ckpt")

However, it keeps returning this error

FailedPreconditionError: Attempting to use uninitialized value dense_241/kernel
 [[Node: dense_241/kernel/_21554 = _Send[T=DT_FLOAT, client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_1854_dense_241/kernel", _device="/job:localhost/replica:0/task:0/gpu:0"](dense_241/kernel)]]
 [[Node: dense_284/bias/_21741 = _Recv[_start_time=0, client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_1947_dense_284/bias", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](^_arg_save_15/Const_0_0, ^save_15/SaveV2/tensor_names, ^save_15/SaveV2/shape_and_slices)]]

I have tried to manually initialize the variables that failed, and that worked once before. However, now there are different variables, and I can't even find them. I would like to understand why this is happening.

Here is the full code

Keras usually has it's own built-in model save and load methods. When training keras models, you should use them instead of the TF saver, since keras has its own meta computation graph, that should probably be initialized when loading a model.

Here is an example (copied from the keras documentation ) for how to save and load a keras model

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM