如何在云端机器学习引擎上为我的模型获取javascript的在线预测?

时间:2017-07-21 08:14:50

标签: javascript google-cloud-ml-engine

我已成功部署在Cloud ML Engine上的模型,并通过关注the instructions验证它是否与gcloud ml-engine models predict一起使用,现在我想通过我的网络应用/ javascript代码向其发送预测。我该怎么做?

1 个答案:

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