将Keras模型导出为SavedModel模型

将Keras模型导出为SavedModel模型

keras模型结构

def get_model_keras(self):
    """构建多输入模型"""
    input_x = Input(shape=(self.feature_dim,), name='inputs')
    hidden = Dense(256, activation='relu', name='hidden1')(input_x)
    output = Dropout(rate=0.5)(hidden)
    output = Dense(16, activation='relu', name='hidden2')(output)
    output = Dropout(0.5)(output)
    output = Dense(1, activation='sigmoid', name='outputs')(output)
    model = Model(inputs=input_x, outputs=output)
    adam = optimizers.Adam(lr=self.learning_rate)
    model.compile(optimizer=adam, loss=[self.loss], metrics=['accuracy'])
    # model.summary()
    return model

导出pd模型时:

def export(self):
	train_model = load_model(self.h5_model_name, compile=False)
	sess = tf.keras.backend.get_session()
	tf.saved_model.simple_save(
		sess,
		self.saved_model_dir,
        inputs={'inputs': train_model.inputs},
        outputs={'outputs': train_model.outputs})

加载pd模型进行预测:

# 开启会话运行结果
with tf.Session(config=tf.ConfigProto()) as sess:
    sess.run(tf.local_variables_initializer())
    # 只需要指定要恢复模型的session,模型的 tag,模型的保存路径即可,
    meta_graph_def = tf.saved_model.loader.load(sess, ["serve"], saved_model_dir)
    
    # 名字与保存模型时定义的一致
    signature_key = 'serving_default'
    signature = meta_graph_def.signature_def
    input_name = signature[signature_key].inputs["inputs"].name
    output_name = signature[signature_key].outputs["outputs"].name
    print(input_name, output_name)
    input_tensor = sess.graph.get_tensor_by_name(input_name)
    output_tensor = sess.graph.get_tensor_by_name(output_name)
	try:
        while not coord.should_stop():
            # batch_features_data 为输入的数据
            pred_scores = [x[0] for x in sess.run(output_tensor, feed_dict={input_tensor: batch_features_data})]
    except tf.errors.OutOfRangeError:
        print("done")
    finally:
        # 结束子线程
        coord.request_stop()
    # 等待子线程结束
    coord.join(threads)

对于未知的pd文件,可以参考这个链接查看内容

你可能感兴趣的:(python应用,深度学习,keras,tensorflow,深度学习)