我已成功部署在Cloud ML Engine上的模型,并通过关注the instructions验证它是否与gcloud ml-engine models predict
一起使用,现在我想通过我的网络应用/ javascript代码向其发送预测。我该怎么做?
答案 0 :(得分:1)
在线预测API是一个REST API,因此您可以使用任何库来发送HTTPS请求,但您需要使用Google's OAuth库来获取凭据。为简单起见,我们将使用googleapis
库。
预测请求的格式为JSON,如docs。
中所述举例说明,请考虑Census示例。客户端可能如下所示:
var google = require('googleapis');
var ml = google.ml('v1');
function auth(callback) {
google.auth.getApplicationDefault(function(err, authClient) {
if (err) {
return callback(err);
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/cloud-platform'
]);
}
callback(null, authClient);
});
}
var instance = {
age: 25,
workclass: " Private",
education: " 11th",
education_num: 7,
marital_status: " Never - married",
occupation: " Machine - op - inspct",
relationship: " Own - child",
race: " Black",
gender: " Male",
capital_gain: 0,
capital_loss: 0,
hours_per_week: 40,
native_country: " United - Stats"
}
auth(function(err, authClient) {
if (err) {
console.error(err);
} else {
var ml = google.ml({
version: 'v1',
auth: authClient
});
// Predict
ml.projects.predict({
name: 'projects/MY_PROJECT/models/census',
resource: {
instances: [instance]
}
}, function(err, result) {
if (err) {
return callback(err);
}
console.log(JSON.stringify(result));
});
}
});