python - 机器学习引擎 - 推理时间慢
问题描述
从谷歌云文档我们有
Cloud Machine Learning Engine 在线预测是一项经过优化的服务,可通过托管模型以尽可能少的延迟运行您的数据。您将小批量数据发送到服务,它会在响应中返回您的预测。您可以通过其他预测概念了解有关在线预测的更多一般信息。块引用
https://cloud.google.com/ml-engine/docs/tensorflow/online-predict
我必须说我的经验低于标准。不要误会我的意思,我喜欢 ML Engine 并且我在那里进行了很多培训,但根据我的经验,推理时间是荒谬的。
我在 256x256 大小的图像上制作了一个小型语义分割网络。我正在使用 Estimators 并将模型转换为 SavedModel 格式,然后使用此代码进行预测
predictor_fn = tf.contrib.predictor.from_saved_model(
export_dir=saved_model_dir,
signature_def_key="prediction"
)
在我的电脑上,这给了我大约 0.9 秒的推理时间。我在 Datalab 实例上尝试了相同的代码,机器类型为n1-highmem-2,推理时间约为 2.3 秒。
现在,如果我在 ML-Engine 上提供我保存的模型
gcloud ml-engine models create SEM --regions europe-west1
gcloud ml-engine versions create SEM --model V0 --origin "MY_BUCKET_PATH" --runtime-version=1.6
服务输入函数是这样的:
def parse_incoming_tensors(incoming):
img = vgg16_normalize(tf.reshape(incoming, [-1, 256, 256, 3]))
return img
def serving_input_fn_web():
"""Input function to use when serving the model on ML Engine."""
inputs = tf.placeholder(tf.string, shape=(None, ))
feature_input = batch_base64_to_tensor(inputs)
feature_input = {'img': parse_incoming_tensors(feature_input)}
return tf.estimator.export.ServingInputReceiver(feature_input, inputs)
然后,我使用这个类进行预测:
class MakeQuery():
def __init__(self, project, model, version=None, client_secret=None):
# Set the environment variable
secret_path = os.path.abspath('./client_secret.json')
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = secret_path
# Create service object and prepare the name of the model we are going to query
self._service = googleapiclient.discovery.build('ml', 'v1')
self._name = 'projects/{}/models/{}'.format(project, model)
self._project = self._service.projects()
if version is not None:
self._name += '/versions/{}'.format(version)
def predict(self, instances):
response = self._project.predict(name=self._name, body=instances).execute()
if 'error' in response:
raise RuntimeError(response['error'])
return response
def get_prediction(self, img_arrays):
input_list = [{'input': array_to_base64_websafe_resize(img)} for img in img_arrays]
input_format = {'instances': input_list}
return self.predict(input_format)
然后每个预测请求需要 10 秒!每次我提出请求时,ML-Engine 是否都会认真部署模型?
TL;DR 使用来自 Estimators 的 Tensorflow SavedModel 格式,Google ML-Engine 的推理时间非常慢。
- 雷蛇 2017:0.9 秒
- Datalab n1-highmem-2:2.3 秒
- ML-Engine 10 秒
解决方案
推荐阅读
- google-apps-script - 如何在 GAS 中运行/调试私有函数?
- python - settimeout() 忽略 Try/Except 的异常 - Python
- scrapy - 将项目(或其他变量)传递给 scrapy 的中间件(或其他模块)。
- build - Thinlto 的并发性在并行构建系统中有用吗?
- google-cloud-platform - 查看 Dataflow 如何进行融合优化的最佳方法是什么
- python - Discord.py Self Bot 使用重写
- wordpress - 在没有 wordpress 帐户的情况下启动 wordpress 网站?
- authentication - WebAPI ASP Net Core JWT 承载认证“签名无效”
- node.js - 将 Loopback (Node.js) API 部署到 Azure?
- android - Android MediaRecorder 在某些设备上不起作用