You are on page 1of 5

AzureCon Challenge

Azure ML and Consuming a Model


Overview
Azure Machine Learning is how you use data and mathematical models to predict future outcomes. There are two aspects to Machine Learning. The first is
creating the model and the process around validating and improving the predictive accuracy of the model this is the realm of the data scientist. The
second aspect and the one YOU will focus on in this challenge is just using existing models, which are published as services in the Azure Machine
Learning Marketplace.
In this challenge you will learn how to consume one of our machine learning offers, text analytics. This service allows you to understand the sentiment of text
in terms of the sentiment being positive or negative as a probability. You send the service a paragraph of text and it will return a probability as well as a
series of phrases from your text that were key in determining the sentiment.
In this challenge, you will provision the ML service and build a simple application that talks to the API for this service. You will use the application to solve a
puzzle. This offer is one of many machine learning offers you can find in the Azure Marketplace.

1. Login to Azure
For this challenge, you have either elected to use your own subscription or have created a new Azure
subscription using the provided Azure Pass (or Free Trial). If you want to switch to use the provided
Azure Pass the promotion code is displayed on the My Account page on the
http://challenge.azurecon.com web site. If there is no promo code displayed, you will need to use the
free trial - http://azure.microsoft.com/pricing/free-trial.
Azure has TWO management portals - the classic portal (http://manage.windowsazure.com) and a new
portal that is in Preview at http://portal.azure.com. You will use the classic portal in this challenge
(unless you need Visual Studio the instructions are using the preview portal).
1.

Open a browser and go to http://manage.windowsazure.com

2.

Enter your Microsoft Account email address and password for the Microsoft Account
you associated with your Azure Pass or your own subscription.

3.

You will now be in your Azure subscription (see opposite) and from here you can create and
manage Azure services.

2. Ensure you have everything! This lab requires Visual Studio.


1.

If you do not have Visual Studio installed, you can easily create a virtual machine that has it ready. Use the following steps to provision a Visual
Studio Virtual Machine if you need Visual Studio. If you have done this in a previous challenge, you can use that Virtual Machine. If not, skip this
section.

2.

Using the Azure Preview Portal (http://portal.azure.com) click +New -> Compute -> and then Marketplace

3.

In the Search Box, enter Visual Studio Community 2015, click the Visual
Studio Community 2015 with Azure SDK 2.7 on Windows Server 2012 R2
image and press ENTER

4.

Change the deployment model to Resource Manager and click Create.

5.

Name the virtual machine vsDevBox, and specify a user name and a
password you will remember (write it down!). Specify the resource group as vsDevBoxRG and pick a location that is close to you, and then click
OK.

6.

Choose a virtual machine size, either A2 or D2 will work. Click OK.

7.

Accept the default settings by clicking OK. Click OK on the summary page to create the virtual machine.

8.

After the virtual machine is provisioned (it will take around 5 minutes), you will connect to it but you can move on with the next section now.

Page | 1

3. Provision the Text Analytics Service from the Azure ML Marketplace.


1.

On the Classic Portal (remember you need to be in the Classic Portal), click + NEW (bottom left)
and select MARKETPLACE.
You can always SWITCH between Classic and Preview portals just click your login name
(top right) on either portal and you will see the other portal listed to switch to.

2.

You will see the Choose a Developer Service dialog. Scroll down near the bottom and select the
Text Analytics service and click the next arrow.

3.

The Text Analytics service (which is deployed in the Azure Machine Learning service) is monetized based on the number of transactions/month you
perform. There is a free tier in this service that gives you 10,000 transactions/month at no charge select this option.

4.

In the NAME field, enter a globally unique name. Suggest you use your email alias prefix and -sentiment. So if your email was
bsmith@contoso.com, you would use bsmith-sentiment.

5.

Choose any region and click NEXT.

6.

Wait on the Review Purchase screen until your purchase details are displayed (this can take 1015 seconds). Click PURCHASE.

7.

Click on the Marketplace category in the left nav bar (towards the bottom scroll down), you
will see your service listed. It will take 30-45 seconds to provision.

8.

Now click on the MANAGE KEYS icon on the bottom center of the screen, and copy the key in
the box so you can use it in your next section.

4. Connect to Your DevBox (if you did step 2, if not skip this section)
1.

Switch to the Preview Portal

2.

Click on the Microsoft Azure logo on the top left of the Portal. This will take you to the startboard.

3.

Your devbox VM should be in running state now, click the tile and at the top of the blade, click the Connect button. Depending on your
browser, you will get some sort of download notification about an .rdp file. If you are running on a Mac, you will need to install the Microsoft
Remote Desktop Client from the App Store.

4.

Open the file and follow the prompts to connect. You will need to enter your credentials for the machine you are connecting to at some point.
These are the username and password that you entered when you created your VM. Accept any security warnings.

Page | 2

5.

Click the RESTORE button on the Remote Desktop Connection Bar at the top of your screen.

6.

On the new smaller window, right click the remote desktop application icon at the top left and then in
the context menu, select Smart Sizing. This puts your remote connection window into a resizable state so
the desktop resizes to the window size.

7.

At this point you have a ready, working computer at your disposal. You need to activate the installed copy
of Visual Studio and there is a VS icon on your desktop. Double Click it.

8.

Be Patient ! ! it will take a few minutes for Visual Studio to do its thing and eventually you will see the
VS Sign in screen. You need to sign in (using a Microsoft Account) or Visual Studio wont let you complete setup.

9.

Select your dev setting (e.g. C#) and click Start Visual Studio button. Wait a bit more and you will be ready to move on

5. Building an App to Use the Text Analytics Service.


Like most modern, web based applications that are composed of services, the pattern we use is one where the various components expose a REST based API
and we call that API using standard http protocols and use a standard data exchange format JSON. This is how we talk to the Azure ML service. So you will
build a .NET simple console application and use http/rest/json.
1.

Open Visual Studio, click File -> New Project and create a new C# Console application accept all the defaults.

2.

Install the popular JSON library Json.NET by going to Tools > NuGet Package Manager > Manage NuGet Packages for Solution JSON is
really the file format that is used between a client and a Web API to exchange data, but very often you need to serialize and de-serialize objects to
this format so thats what this library does for you.

3.

Type json in the Search field and select INSTALL


the Newtonsoft.Json library and click Install
and then OK on the preview dialog.

4.

Close the Package Manager.

5.

Open the Program.cs file in your project.

6.

First, within your Main function, lets save that


Account Key you copied earlier. Type the
following:
string accountkey = "";

7.

PASTE (CTRL-V) between the two quotes, the account key you copied earlier.

8.

Add the following FOUR references below the existing using statements in program.cs:
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

9.

In Solution Explorer, right click References -> Add Reference. In the Assemblies category (top left of
the dialog), choose Framework. Locate System.Net.Http and System.Web and add them both.

10.

The Text Analysis service works by accepting some text and returning a probability score called the
sentiment index as well as a list of key phrases that were key to determining the sentiment score. So we
need in our app a structure to get this data back from the service.

Page | 3

After the Main method in your program class, copy/paste in this structure.
/// Class to hold result of text analysis
public struct TextAnalysisResult
{
public List<string> KeyPhrases { get; set; }
public double SentimentIndex;
}

11.

The main work in your app will use the .NET httpclient library this is the library that allows you to form http interactions with web sites and in our
case a REST based web service. You will create a function that does all the work of communicating with the Text Analysis service, passing it some
input text and getting back the TextAnalysisResult structure.
Copy/Paste in the following function after your TextAnalysisResult structure:
static TextAnalysisResult AnalyzeText(string inputText, string accountkey)
{
TextAnalysisResult result = new TextAnalysisResult();
using (var httpClient = new HttpClient())
{
// Set http client parameters to call data market and encode text
string inputTextEncoded = HttpUtility.UrlEncode(inputText);
httpClient.BaseAddress = new Uri("https://api.datamarket.azure.com/");
string creds = "AccountKey:" + accountkey;
string authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
httpClient.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Get key phrases
string keyPhrasesRequest = "data.ashx/amla/text-analytics/v1/GetKeyPhrases?Text=" + inputTextEncoded;
HttpResponseMessage response = httpClient.GetAsync(keyPhrasesRequest).Result;
string content = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call failed. HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
result = JsonConvert.DeserializeObject<TextAnalysisResult>(content);
// Get sentiment
string sentimentRequest = "data.ashx/amla/text-analytics/v1/GetSentiment?Text=" + inputTextEncoded;
response = httpClient.GetAsync(sentimentRequest).Result;
content = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call failed. HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
dynamic sentimentResult = Newtonsoft.Json.Linq.JObject.Parse(content);
result.SentimentIndex = sentimentResult.Score;
}
return result;
}

Page | 4

12.

Ok, you have all you need, but you need something in your main program to validate the user input, call the AnalyseText function you just created
and then display the results. Since this is a console application, you will pass in the text you want to analyze on the command line as a parameter.
Copy/Paste in this code within your Main function after your string accountkey= statement.
if (args.Length != 1)
{
Console.WriteLine("Invalid arguments. This program requires 1 argument -");
Console.WriteLine("\t input text: string to be analyzed");
return;
}
string inputText = args[0];
TextAnalysisResult myTAR;
myTAR = AnalyzeText(inputText, accountkey);
Console.WriteLine("Sentiment Score: {0}", myTAR.SentimentIndex);
Console.WriteLine("Key phrases: " + string.Join(",", myTAR.KeyPhrases));
Console.ReadLine();

13.

From the toolbar, select BUILD -> Build Solution. If everything built successfully, you can test your application.

6. Running Your Finished Application.


1.

In Solution Explorer, right click your project folder and select Open Folder in File
Explorer (at the bottom of the menu).

2.

In file explorer, navigate to the Bin\Debug folder thats your executable file that you
will run from a command prompt.

3.

Click in the address bar in File Explorer to highlight the entire path to the bin folder and
press Ctrl-C to copy.

4.

Press the Window button, type Command and select Command Prompt.

5.

At the prompt type cd then a space and then click the application icon at the top left
of the window and select Edit -> Paste. Press Enter and you should now be pointing at
the bin directory.

6.

Type dir to see your .exe file

7.

As a little test, type in the name of your executable file, in


the example above this would be consoleapplication1 and
then enter some text in quotes for example I am very happy
to be doing this challenge and press enter.
Your application calls the Text Analysis service, which returns a
sentiment score indicating this is likely a very positive statement and also returns key phrases that have been pulled out in the analysis.

8.

Run your application again and this time enter the phrase the stock market made losses today. You can probably guess, the sentiment will be
negative.

9.

Run the application again and this time enter the phrase the stock market made fantastic losses today. Surprised..?

The service you are using is a service running in the Azure Machine Learning service. You can use this service to create your own predictive engines based
on whatever domain is important to you there is a whole toolset as part of this service more focused on the building of the models and the workflow
around model tuning based on feeding the model datasets so that prediction is improved. In this lab, all that complexity is hidden from you, you just got to
use a service.

--- END OF LAB --Go back to the AzureCon Challenge web site (http://challenge.azurecon.com) and complete the challenge question to get your points.
REMEMBER: You only have one chance at the question, make sure you really know the answer!

Page | 5

You might also like