使用tf.estimator在JSON中的base64输入上对模型导出的模型进行预测

时间:2018-10-27 14:36:03

标签: python tensorflow machine-learning keras

我想建立一个用于模型预测的rest api,因为我已经在Google Cloud ML上进行了测试,因此我的模型接受json文件中的base64图像字符串。而且它不接受来自Android应用程序的预测请求,因此我正尝试使用rest api。从python脚本我的预测是,通过仅在没有api的情况下进行本地测试,就给了我很多错误  这是我的出口型号代码

import os
import shutil
import tensorflow as tf
from tensorflow import keras



HEIGHT = 48
WIDTH = 48
CHANNELS = 1
version = 'v1'


h5_model_path = os.path.join('model_4layer_2_2_pool  yes.h5')
tf_model_path = os.path.join('D:/university/working/trying/Facial- 
Expression-Recognition-master/tryMore')
estimator = keras.estimator.model_to_estimator(
keras_model_path=h5_model_path,
model_dir=tf_model_path)


def image_preprocessing(image):

 image = tf.expand_dims(image, 0)
 image = tf.image.resize_bilinear(image, [HEIGHT, WIDTH], 
 align_corners=False)
 image = tf.squeeze(image, axis=[0])
 image = tf.cast(image, dtype=tf.uint8)
 return image

作为BASE64字节的图像

def serving_input_receiver_fn():
  def prepare_image(image_str_tensor):
    image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
    return image_preprocessing(image)

 input_ph = tf.placeholder(tf.string, shape=[None])
 images_tensor = tf.map_fn(
    prepare_image, input_ph, back_prop=False, dtype=tf.uint8)
 images_tensor = tf.image.convert_image_dtype(images_tensor, 
 dtype=tf.float32)

 return tf.estimator.export.ServingInputReceiver(
    {'conv2d_1_input': images_tensor},
    {'image_bytes': input_ph})

 export_path = os.path.join('models\json_b64', version)
 if os.path.exists(export_path):  # clean up old exports with this 
 version
 shutil.rmtree(export_path)
 estimator.export_savedmodel(
 export_path,
 serving_input_receiver_fn=serving_input_receiver_fn)

,我的预测代码如下

import tensorflow as tf 
import pickle
import os
import imgJSON

dir_path = os.path.dirname(__file__)
exported_path= os.path.join(dir_path,  "models/json_b64/v1/1539157474")

model_input=imgJSON.img_bytes
global data
def main():
with tf.Session() as sess:

 Model=tf.saved_model.loader.load(sess, 
               [tf.saved_model.tag_constants.SERVING], exported_path)

 predictor= tf.contrib.predictor.from_saved_model(exported_path)

import json 
with open("D:/university/working/trying/Facial-Expression-Recognition- 
  master/tryMore/test_json_b64.json") as f:
  data = json.loads(f.read())
  print(data["image_bytes"])


output_dict= predictor({"image_bytes":[model_input]})
print(" prediction is " , output_dict['scores'])


if __name__ == "__main__":
   main()

我的错误消息如下:

InvalidArgumentError (see above for traceback): Expected image (JPEG, PNG, or GIF), got unknown format starting with '/9j/4AAQSkZJRgAB'
 [[Node: map/while/DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=1, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](map/while/TensorArrayReadV3)]]

如何预测将base64字符串传递给我各自导出的模型?

0 个答案:

没有答案