Deploying Keras Models via Google Cloud ML

前端 未结 4 2278
情书的邮戳
情书的邮戳 2020-12-08 23:48

I am looking to use Google Cloud ML to host my Keras models so that I can call the API and make some predictions. I am running into some issues from the Keras side of things

4条回答
  •  情歌与酒
    2020-12-09 00:05

    After training your model on Google Cloud ML Engine (check out this awesome tutorial ), I named the input and output of my graph with

    signature = predict_signature_def(inputs={'NAME_YOUR_INPUT': new_Model.input},
                                      outputs={'NAME_YOUR_OUTPUT': new_Model.output})
    

    You can see the full exporting example for an already trained keras model 'model.h5' below.

    import keras.backend as K
    import tensorflow as tf
    from keras.models import load_model, Sequential
    from tensorflow.python.saved_model import builder as saved_model_builder
    from tensorflow.python.saved_model import tag_constants, signature_constants
    from tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def
    
    # reset session
    K.clear_session()
    sess = tf.Session()
    K.set_session(sess)
    
    # disable loading of learning nodes
    K.set_learning_phase(0)
    
    # load model
    model = load_model('model.h5')
    config = model.get_config()
    weights = model.get_weights()
    new_Model = Sequential.from_config(config)
    new_Model.set_weights(weights)
    
    # export saved model
    export_path = 'YOUR_EXPORT_PATH' + '/export'
    builder = saved_model_builder.SavedModelBuilder(export_path)
    
    signature = predict_signature_def(inputs={'NAME_YOUR_INPUT': new_Model.input},
                                      outputs={'NAME_YOUR_OUTPUT': new_Model.output})
    
    with K.get_session() as sess:
        builder.add_meta_graph_and_variables(sess=sess,
                                             tags=[tag_constants.SERVING],
                                             signature_def_map={
                                                 signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature})
        builder.save()
    

    You can also see my full implementation.

    edit: And if my answer solved your problem, just leave me an uptick here :)

提交回复
热议问题