0

我正在尝试使用 Google 预测 API。我已经训练了我的模型,并通过网页测试了预测,效果很好。但是,我现在正在尝试使用 java api 来预测一堆记录,但我一直收到错误

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value for: Unable to parse '[feature1, feature2, feature3, feature4, feature5]'.",
    "reason" : "invalid"
  } ],
  "message" : "Invalid value for: Unable to parse '[feature1, feature2, feature3, feature4, feature5]'."

对我来说,似乎 json 创建者并没有在功能周围加上引号,但我尽可能地关注示例,并且它们不会更改或修改 json 工厂。这是凭证和预测构建代码。

private static GoogleCredential authorize() throws Exception {

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountScopes(Collections.singleton(PredictionScopes.PREDICTION))
            .setServiceAccountPrivateKeyFromP12File(new File("p12filefromdevconsole.p12"))
            .build();
    return credential;

}

...
Prediction prediction = new Prediction.Builder(
            httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

...
private static Output predict(Prediction prediction, String... features) throws IOException {
    Input input = new Input();
    InputInput inputInput = new InputInput();
    inputInput.setCsvInstance(Collections.<Object>singletonList(features));
    input.setInput(inputInput);
    Output output = prediction.trainedmodels().predict(PROJECT_ID, MODEL_ID, input).execute();
    return output;
}

有什么想法我做错了吗?

4

1 回答 1

0

经过多次挫折和反复试验,我通过使用new ArrayList(Arrays.asList(features))而不是使用Collections.singletonList(features)解决了这个问题。这是修改后的预测方法。请记住,我最初的实现直接来自 Google 网站上的示例 :(

private static Output predict(Prediction prediction, String... features) throws IOException {
    Input input = new Input();
    InputInput inputInput = new InputInput();
    inputInput.setCsvInstance(new ArrayList(Arrays.asList(features)));
    input.setInput(inputInput);
    Output output = prediction.trainedmodels().predict(PROJECT_ID, MODEL_ID, input).execute();
    return output;
}
于 2014-10-10T13:25:10.653 回答