如何用JavaScript实现GCP部署的TensorFlow神经网络模型在线预测?
针对GCP AI Platform模型的JavaScript在线预测方案
我来帮你搞定这个问题,先逐个拆解你遇到的痛点:
为什么@google-cloud/automl包无法使用?
这个包是专门为Google AutoML服务设计的,只支持AutoML训练出来的模型,而你部署的是自定义TensorFlow/Keras模型,属于AI Platform(现在已整合到Vertex AI Prediction)的通用模型服务,两者的资源格式和API接口完全不同,所以会抛出"Invalid resource ID"错误——你用错工具啦!
REST API服务器端永久授权方案
既然curl调用正常,那在服务器端实现持久授权可以通过服务账号密钥来搞定,步骤如下:
- 在GCP控制台创建一个拥有
AI Platform Predictor权限的服务账号,下载其JSON格式的密钥文件 - 在你的服务器环境中设置环境变量:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json" - 使用
google-auth-library库自动获取并刷新授权令牌,无需手动管理过期时间。示例代码(用node-fetch):const { GoogleAuth } = require('google-auth-library'); const fetch = require('node-fetch'); async function predict() { const auth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const client = await auth.getClient(); const token = await client.getAccessToken(); const projectId = 'your-project-id'; const modelId = 'your-model-id'; const region = 'your-region'; // 比如us-central1 const url = `https://${region}-ml.googleapis.com/v1/projects/${projectId}/models/${modelId}:predict`; const requestBody = { instances: [/* 你的输入数据,和gcloud predict用的格式一致 */] }; const response = await fetch(url, { method: 'POST', headers: { 'Authorization': `Bearer ${token.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); const result = await response.json(); console.log(result); } predict();
推荐的官方解决方案:使用@google-cloud/aiplatform包
Google官方现在推荐用@google-cloud/aiplatform包来操作Vertex AI(包含原AI Platform的所有功能),它完美支持自定义TensorFlow模型的预测,而且封装了授权和API调用逻辑,比手动调用REST API更省心。
示例代码:
- 先安装包:
npm install @google-cloud/aiplatform - 编写预测代码:
注意这里的const { PredictionServiceClient } = require('@google-cloud/aiplatform'); async function predict() { const client = new PredictionServiceClient({ apiEndpoint: 'us-central1-aiplatform.googleapis.com', // 替换成你的模型部署区域 }); const projectId = 'your-project-id'; const modelId = 'your-model-id'; const location = 'us-central1'; const modelName = client.modelPath(projectId, location, modelId); const instances = [/* 输入数据,和gcloud predict的格式一致 */]; const parameters = {}; // 如果有预测参数可以在这里设置 const request = { endpoint: modelName, instances: instances, parameters: parameters, }; const [response] = await client.predict(request); console.log('Predictions:'); response.predictions.forEach(prediction => { console.log(prediction); }); } predict();modelName格式是projects/{project}/locations/{region}/models/{model-id},这也是之前用automl包报错的核心原因——automl的资源格式和这个完全不同,用对工具就不会有问题了。
内容的提问来源于stack exchange,提问作者shasho
相关产品推荐
相关产品推荐

