Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a C# example for Cloud ML Engine's online prediction API #290

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ml_engine/online_prediction/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
https://cloud.google.com/ml-engine/docs/concepts/prediction-overview
117 changes: 117 additions & 0 deletions ml_engine/online_prediction/predict.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;

namespace prediction_client
{
class Person
{
public int age { get; set; }
public string workclass { get; set; }
public string education { get; set; }
public int education_num { get; set; }
public string marital_status { get; set; }
public string occupation { get; set; }
public string relationship { get; set; }
public string race { get; set; }
public string gender { get; set; }
public int capital_gain { get; set; }
public int capital_loss { get; set; }
public int hours_per_week { get; set; }
public string native_country { get; set; }
}

class MainClass
{
public static void Main(string[] args)
{
RunAsync().Wait();
}

static string project = "YOUR_PROJECT";
static string model = "census"; // Name of deployed model

static HttpClient client = new HttpClient();

static async Task RunAsync()
{
client.BaseAddress = new Uri("https://ml.googleapis.com/v1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

try
{
Person person = new Person
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor comment -- I'd expect you should be able to use dynamic here rather than have to define a Person class and use strong typing, just for filling in a bunch of fields.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I originally did that, but then thought user in production probably has structured data. If, in fact, anonymous types are pretty ubiquitous, happy to change.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, you're already using dynamic in dealing with the response, as well as an anonymous type in constructing the request (new { instances = instances }) itself ... hence this bit might as well do the same.

{
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"
};
var instances = new List<Person> { person };

var predictions = await Predict(project, model, instances);
Console.WriteLine(predictions);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Console.ReadLine();
}

// [START predict_json]
static async Task<dynamic> Predict(String project, String model, List<Person> instances, String version = null)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the total nit category -- was slightly bugging me to see model and version parameters separated apart. Signature could be (instances, project, model, version). :)

{
GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
var bearer_token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token);

var version_suffix = version == null ? "" : $"/version/{version}";
var model_uri = $"projects/{project}/models/{model}{version_suffix}";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a style point of view, C# code doesn't use underscores. This would be modelUri.

var predict_uri = $"{model_uri}:predict";

var request = new { instances = instances };
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");

var responseMessage = await client.PostAsync(predict_uri, content);
responseMessage.EnsureSuccessStatusCode();

var responseBody = await responseMessage.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject(responseBody);

return response.predictions;
}
// [END predict_json]
}
}