I have successfully deployed on model on Cloud ML Engine and verified it is working with gcloud ml-engine models predict
by following the instructions, now I want to send predictions to it from my web app / javascript code. How do I do that?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The online prediction API is a REST API, so you can use any library for sending HTTPS requests, although you will need to use Google's OAuth library to get your credentials. We will use the googleapis
library for simplicity.
The format of the prediction request is JSON, as described in the docs.
To exemplify, consider the Census example. A client for that might look like:
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));
});
}
});