python - 从图像为自定义神经网络创建 AI Platform 的 json 实例
问题描述
我最近创建了一个自定义神经网络,其中包含以下基本架构代码:
def gen_base_model(n_class):
cnn_model = InceptionResNetV2(include_top=False, input_shape=(width, width, 3), weights='imagenet')
inputs = Input((width, width, 3))
x = inputs
x = Lambda(preprocess_input, name='preprocessing')(x)
x = cnn_model(x)
x = GlobalAveragePooling2D()(x)
x = Dropout(0.5)(x)
x = Dense(n_class, activation='softmax', name='softmax')(x)
model = Model(inputs, x)
return model
我已经训练了模型,现在我想在 Cloud ML Engine / AI Platform 上部署模型。
我使用以下代码将 keras 模型转换并保存为 Saved Model :
def convert_and_save(model, path):
full_path = './savedmodels/' + path
signature = tf.saved_model.signature_def_utils.predict_signature_def(
inputs={'image': model.input}, outputs={'scores': model.output})
builder = tf.saved_model.builder.SavedModelBuilder(full_path)
builder.add_meta_graph_and_variables(
sess=K.get_session(),
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
signature
})
builder.save()
但是,现在我无法创建一个实例来预测输出。谷歌云网站指定以下格式:
{"instances": [<instance>, <instance>, ...]}
我尝试使用以下代码来转换图像:
width = 299
image_pre = cv2.resize(cv2.imread('image.jpg'), (width, width))
img_pred = np.expand_dims(image_pre, axis=0)
print(img_pred.shape)
img_pred_1 = img_pred.tolist()
instances = {'image': img_pred_1}
但它失败并出现以下错误:
RuntimeError: Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="input must be 4-dimensional[1,1,299,299,3]
[[{{node inception_resnet_v2/conv2d_1/convolution}}]]")
另外,在本地使用模型时,我使用以下代码(keras)进行预测:
width = 299
image_pre = cv2.resize(cv2.imread('image.jpg'), (width, width))
img_pred = np.expand_dims(image_pre, axis=0)
prediction = model.predict(img_pred)
ind = np.argmax(prediction[0])
predicted_class = model_classes[ind]
解决方案
推荐阅读
- android - 在 Android studio 3.2 中使用 Build Bundle Option
- javascript - 从 Windows 10 设备上的浏览器访问本机相机应用程序
- laravel - laravel 嵌套路由与前缀和资源剂量工作
- php - 为什么 Group by & HAVING 子句不起作用?
- php - Laravel 使用迁移时显示 1215(无法添加外键约束):通过 ssh 刷新
- deployment - 在 JBoss EAP 6.4 中创建部署监听器 ESB
- ibm-cloud - IBM Chatbot Assistant - 如何跳到下一个插槽
- loops - 如何让一只乌龟能够在 Netlogo 中保存其他乌龟 ID?
- xamarin - Xamarin 表单中具有不同子项的可扩展 ListView
- python - 如何按递增顺序打印奇数?