Tensorflow加载和保存模型

时间:2018-12-11 15:44:16

标签: python tensorflow keras

我将Tensorflow与Keras结合使用,以使用Conv3D网络预测视频帧。现在,我已经创建了Conv3D模型并对其进行了训练,我想导出它,但是似乎无法正确处理它。我总是得到这样的错误:加载模型并要运行该模型时,未定义会话:

The name 'inputs:0' refers to a Tensor which does not exist. The operation, 'inputs', does not exist in the graph.

这是我的模特

x = Conv3D(32, (3,3,3), activation='relu')(images_placeholder)
x = MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))(x)
x = Conv3D(64, (3,3,3), activation='relu')(x)
x = MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))(x)
x = Conv3D(128, (3,3,3), activation='relu')(x)
x = Conv3D(128, (3,3,3), activation='relu')(x)
x = MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))(x)
x = Flatten()(x)
x = Dense(1024)(x)
x = Dropout(0.5)(x)
x = Dense(1024)(x)
x = Dropout(0.5)(x)
return Dense(1)(x)

我使用以下代码对其进行训练:

    # Create session
tf.reset_default_graph()

sess = tf.Session()
K.set_session(sess)


images_placeholder = tf.placeholder(tf.float32, (None, c3d._DEPTH, c3d._IMG_HEIGHT, c3d._IMG_WIDTH, 3))
labels_placeholder = tf.placeholder(tf.float32, (None,))

model = get_model(images_placeholder)
print(model)

loss = losses.mean_absolute_percentage_error(labels_placeholder, model)

train_step = tf.train.RMSPropOptimizer(0.001).minimize(loss)

init_op = tf.global_variables_initializer()
sess.run(init_op)

saver = tf.train.Saver()

minmax_scale = MinMaxScaler(feature_range=(0, 1), copy=True)

# Train the model
videos = glob.glob('data/videos/*.mp4')

vid_i = 0
for video in videos[:-48]:
    vid_i += 1
    print("Training on video " + str(vid_i) + ": " + video)

    images, labels = c3d.get_image_and_labels_for_video(video)
    assert images.shape[0] == labels.shape[0]

    steps = int(np.floor(len(images) / c3d._BATCH_SIZE))

    labels = minmax_scale.fit_transform(labels[:, np.newaxis]).reshape(len(labels),)

    with sess.as_default():
        for i in range(steps):
            part = i * c3d._BATCH_SIZE
            train_step.run(feed_dict={images_placeholder: images[part:part+c3d._BATCH_SIZE],
                                      labels_placeholder: labels[part:part+c3d._BATCH_SIZE],
                                      K.learning_phase(): 1})

训练完模型后,我想使用以下功能将其保存:

    prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({"inputs": input}, {"prediction": output})
valid_prediction_signature = tf.saved_model.signature_def_utils.is_valid_signature(prediction_signature)

if (valid_prediction_signature == False):
    raise ValueError("Error: Prediction signature not valid!")

builder = saved_model_builder.SavedModelBuilder(_MODEL_PATH+_MODEL_NAME+_MODEL_VERSION)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
builder.add_meta_graph_and_variables(
    sess, [tag_constants.SERVING],
    signature_def_map={
        signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature,
    },
    legacy_init_op=legacy_init_op)
builder.save()

保存后,我将其加载到:

images, labels = get_image_and_labels_for_video(video_path)

scores = np.array([])
steps = int(np.floor(len(images) / _BATCH_SIZE))
with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess, [tag_constants.SERVING], _MODEL_PATH+_MODEL_NAME+_MODEL_VERSION)
    graph = tf.get_default_graph()
    input = graph.get_tensor_by_name("inputs:0")
    model = graph.get_tensor_by_name("prediction:0")

    for i in range(steps):
        part = i * _BATCH_SIZE
        session = sess.run(model, feed_dict={input: images[part:part + _BATCH_SIZE],
                                                K.learning_phase(): 0})

但是随后崩溃,因为在保存签名时找不到我定义的输入。如何保存tensorflow keras模型并在以后重新用于预测框架。

先谢谢您

斯文

0 个答案:

没有答案