Wednesday, April 25, 2012

Google Predict - how to predict from your code using OAuth2

I had an idea to try Google Predict product to predict Forex. I will make another post about my attempt and in this post will be example of how to start using Google Predict and how actually access prediction from your code.
To get started please read this article. The article covers all the steps you need to to except the last one: how to get prediction in your code? While I was trying to do this I found Google libraries for this - don't try them - it is hard to understand them and they use old accessing framework OAuth1 which will be turned off soon. The good thing that Google also support new OAuth2 framework which is much more simple than ver1. I wrote an article about how easy is to use OAuth2 from any programing language.
Simple steps to get prediction:
  1. Create training data, upload it and train your model as described here.
  2. Get access token as described. Note: then creating URL to request user approve, in scope parameter include also 'https://www.googleapis.com/auth/prediction'
  3. Send you data sample to get prediction. The Java code is below.

try {
    String access_token="the token you received from Google from step 2";
    String modelId = "trained model ID you created in step 1";
    List<Object> values; //here should be all your data which will be sent to Google Predict to get prediction
    
    Scheme httpsScheme = new Scheme("https", 443, new EasySSLSocketFactory());
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(cm);

    HttpPost httppost = new HttpPost("https://www.googleapis.com/prediction/v1.5/trainedmodels/"+modelId+"/predict?access_token="+access_token);
    httppost.setEntity(new StringEntity(getRequestBody(values)));
    httppost.setHeader("Content-type", "application/json");

    log.debug("executing request to get token:" + httppost.getRequestLine());

    HttpResponse response = httpClient.execute(httppost);

    HttpEntity entity = response.getEntity();

    log.debug("response status:" + response.getStatusLine());
    ContentType contentType = ContentType.getOrDefault(entity);
    if (contentType.getMimeType().equals("application/json")) {
        //Here is reply from Google Predict
        String responseStr = IOUtils.toString(entity.getContent());
        log.debug("parsing json response:"+responseStr);
    }
    EntityUtils.consume(entity);
    httppost.releaseConnection();
    httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
    log.error("Error retrieving prediction", e);
}


/*
Google predict expects input as this:
{
"input":{
  "csvInstance":[ col1_value, col2_value, ... ]
}
}
*/
private String getRequestBody(List<Object> values){
    StringBuffer sb = new StringBuffer("{\n\"input\":{\n\"csvInstance\":[");
    for(Object o:values){
        sb.append(o).append(",");
    }
    sb.deleteCharAt(sb.length()-1); //delete last coma(,)
    sb.append("]\n}\n}");
    log.debug("request body:"+sb.toString());
    return sb.toString();
}

 Now then you know basics you can read about other web services Google prediction support. Good luck predicting!

No comments:

Post a Comment