gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:26:01 34 4
gpt4 key购买 nike

我需要根据部署在云 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com