向ML Engine请求图像

时间:2018-08-06 05:32:27

标签: python-3.x numpy keras google-cloud-ml

我正在尝试为我的ML Engine模型提出正确的请求。

我明白了

$ gcloud ml-engine predict --model=plantDisease01 --json-instances=request-float32.json  
{
  "error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, 
details=\"Matrix size-incompatible: In[0]: [1,50176], In[1]: [25088,256]\n\t [[Node: dense_1_1/MatMul = MatMul[T=DT_FLOAT, _output_shapes=[[?,256]], transpose_a=false, transpose_b=false, _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"](_arg_dense_1_input_1_0_0, dense_1_1/kernel/read)]]\")"
}

我生成了一个示例请求

python -c 'req = []; [req.append(0.2) for i in range(224*224)]; print(req)' &> request-float32.json

我使用以下代码段生成了协议缓冲区版本

# convert keras model to mlengine model
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('vgg16_no_augmentation.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 = 'mlengine-03' + '/export'
builder = saved_model_builder.SavedModelBuilder(export_path)

signature = predict_signature_def(inputs={'foo-input': new_Model.input},
                                  outputs={'serve': 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()

模型是直到单元格6为止的那个https://github.com/ClaudeCoulombe/deep-learning-with-python-notebooks/blob/master/5.3-using-a-pretrained-convnet.ipynb

(我与链接模型略有不同,它使用的是input_dim = 4 * 4 * 512,我使用了更大的一个)

我知道25088 = 7 * 7 * 512,这是模型中的input_dim。但是我不确定如何从图像转到其中包含25088个浮点数的文件?

1 个答案:

答案 0 :(得分:1)

挑战在于,您必须在图像客户端使用卷积基础,然后将提取的特征发送到模型托管服务。

我选择使用模型的版本,该版本将卷积基础集成到模型中。然后,我创建了一个简单的API,用于运行模型,接受图像上传并调整大小,然后再将图像输入模型。

https://github.com/morenoh149/simple-keras-rest-api/tree/hm-plant-model上可见