在生产服务中使用CloudML预测API的最佳方法是什么?
我见过: https://cloud.google.com/ml/docs/quickstarts/prediction 但它依赖于gcloud工具
我正在寻找的解决方案并不依赖于在发出请求的机器上安装和初始化gcloud。拥有适用于GCP,AWS和其他云的解决方案会很棒。
由于
答案 0 :(得分:8)
我将向您展示如何验证您的生产环境以使用CloudML在线预测。 CloudML快速入门使用gcloud
通过用户名,密码等对最终用户进行身份验证。gcloud
无法很好地扩展到100台计算机启动和停止的环境。下面,我将引导您完成创建云服务帐户并生成私钥的步骤,以便您的生产实例能够向Google服务器标识自己。请参阅身份验证文档here。
这是您可以使用的食谱。
PROJECT=
MODEL_NAME=
SERVICE_ACCOUNT_PREFIX=cloud-ml-predict
SERVICE_ACCOUNT="${SERVICE_ACCOUNT_PREFIX}@${PROJECT}.iam.gserviceaccount.com"
这些步骤只需执行一次,并为您创建服务帐户和私钥。
# Make a new service account
gcloud iam service-accounts create ${SERVICE_ACCOUNT_PREFIX} \
--display-name ${SERVICE_ACCOUNT_PREFIX}
# Provide correct role to service account permissions:
gcloud projects add-iam-policy-binding $PROJECT \
--member "serviceAccount:$SERVICE_ACCOUNT" --role roles/viewer
# Create private key for the service account:
gcloud iam service-accounts keys create --iam-account \
$SERVICE_ACCOUNT private_key.json
现在我们有了一个私钥(在private_key.json
中),我们可以从任何具有googleapiclient
Python库的机器调用预测API。现在,无论是否有gcloud
的任何计算机,您只需要包含以下行,即可通过HTTP访问CloudML预测服务
scopes = ['https://www.googleapis.com/auth/cloud-platform']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_filename, scopes=scopes)
ml_service = discovery.build('ml', 'v1beta1', credentials=credentials)
最后,假设您从quickstarts部署了MNIST模型,这是一个有效的例子。
cat > key_pair_cloud_ml_serve.py <<EOD
from googleapiclient import discovery
import json
from oauth2client.service_account import ServiceAccountCredentials
import sys
def get_mnist_prediction(ml_service, project, model_name, instance):
parent = 'projects/{}/models/{}'.format(project, model_name)
request_dict = {'instances': [json.loads(instance)]}
request = ml_service.projects().predict(name=parent, body=request_dict)
print request.execute() # waits till request is returned
if __name__ == '__main__':
usage_str = 'usage: python prog private_key.json MODEL_NAME data/predict*json'
assert len(sys.argv) == 4, usage_str
key_file = sys.argv[1]
model_name = sys.argv[2]
data_file = sys.argv[3]
scopes = ['https://www.googleapis.com/auth/cloud-platform']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file,
scopes=scopes)
ml_service = discovery.build('ml', 'v1beta1', credentials=credentials)
with open(key_file) as ff:
project = json.load(ff)['project_id']
with open(data_file) as ff:
for ii, instance in enumerate(ff):
get_mnist_prediction(ml_service, project, model_name, instance)
EOD
在Cloud ML samples的mnist/deployable
文件夹中,我们称之为代码......
python key_pair_cloud_ml_serve.py private_key.json \
$MODEL_NAME data/predict_sample.tensor.json
{u'predictions': [{u'prediction': 5, u'key': 0, u'scores': [0.04025577753782272, 0.00042669562390074134, 0.005919951014220715, 0.4221051335334778, 2.2986243493505754e-05, 0.5084351897239685, 0.0007824163185432553, 0.01125132292509079, 0.008616944774985313, 0.0021835025399923325]}]}
瞧!我们使用私钥,从不需要使用gcloud进行身份验证或查询我们的预测模型!
答案 1 :(得分:4)