How do I get online predictions in javascript for my model on Cloud Machine Learning Engine?

你离开我真会死。 提交于 2019-12-08 04:18:42

问题


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


来源:https://stackoverflow.com/questions/45232505/how-do-i-get-online-predictions-in-javascript-for-my-model-on-cloud-machine-lear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!