How do I get online predictions in javascript for

2019-05-29 13:19发布

问题:

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));
        });
    }
});