Python ml 引擎预测 : How can I make a googleapiclient. discovery.build 持久?

标签 python prediction google-api-python-client google-cloud-ml

我需要根据部署在云 ML 引擎中的模型进行在线预测。我在 python 中的代码类似于在文档 ( https://cloud.google.com/ml-engine/docs/tensorflow/online-predict ) 中找到的代码:

service = googleapiclient.discovery.build('ml', 'v1')
name = 'projects/{}/models/{}'.format(project, model)

if version is not None:
    name += '/versions/{}'.format(version)

response = service.projects().predict(
    name=name,
    body={'instances': instances}
    ).execute()

但是,我从脚本外部收到了“实例”数据,我想知道是否有一种方法可以在不生成“service = googleapiclient.discovery.build('ml', 'v1')”的情况下运行这个脚本每次在请求之前,因为这需要时间。 pd:这是我在 gcp 上的第一个项目。谢谢。

最佳答案

像这样的东西会起作用。您需要全局初始化您的服务,然后使用该服务实例进行调用。

import googleapiclient.discovery
AI_SERVICE = None

def ai_platform_init():
    global AI_SERVICE
    # Set GCP Authentication
    credentials = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')

    # Path to your credentials
    credentials_path = os.path.join(os.path.dirname(__file__), 'ai-platform-credentials.json')
    if credentials is None and os.path.exists(credentials_path):
        os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path

    # Create AI Platform Service
    if os.path.exists(credentials_path):
        AI_SERVICE = googleapiclient.discovery.build('ml', 'v1', cache=MemoryCache())

# Initialize AI Platform on load.
ai_platform_init()

然后,您可以执行以下操作:

def call_ai_platform():
   response = AI_SERVICE.projects().predict(name=name,
                                            body={'instances': instances}).execute()

奖金!如果您对 googleapiclient.discovery 调用中的 MemoryCache 类感到好奇,它是从另一个 SO 借来的:

class MemoryCache():
    """A workaround for cache warnings from Google.
    Check out: https://github.com/googleapis/google-api-python-client/issues/325#issuecomment-274349841
    """
    _CACHE = {}

    def get(self, url):
        return MemoryCache._CACHE.get(url)

    def set(self, url, content):
        MemoryCache._CACHE[url] = content

关于Python ml 引擎预测 : How can I make a googleapiclient. discovery.build 持久?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55542860/

相关文章:

python - 寻找 PyQt4 嵌入式终端小部件

python - 从expect脚本调用python脚本时出错

r - 无法将学习模型应用于 R 中的测试数据

python - 如何提高 scikit-learn 中预测的准确性

python - 无需 OAuth 且只需 API key 即可获取 Youtube Analytics

python - Django:使用 simple-history 模块我得到 auth_historicaluser 不存在错误

python - 在Python中读取带有空行的文本

python - KNN - 在 python 中预测单个案例

python - 在 Admin SDK 中使用 Google Directory API 进行 Google 身份验证的正确方法是什么?

python - Jinja2 html按钮: Catch POST on different pages