Scope
This article is about demonstrating the use of Machine Learning to do Sentiment Analysis on texts.
Introduction
Sentiment Analysis is the process of detecting the feeling or the mood of a person when writing a text (technically called contextual polarity). In other words, it determines whether a piece of writing is positive, negative or neutral.
Uses of Sentiment Analysis
- Product reviews
- Is the review positive or negative
- Analyzing customer emails
- Social Media Analytics
- What do customers think about my company
If one has about 10 mails or products, this will be quite a simple task, but what if some store has thousands of products each of them with hundreds of reviews daily.
Then, automating this process makes sense. And this is where Text Analytics comes into play.
Text Analytics API
Text Analytics API is a suite of text analytics web services built with Azure Machine Learning. The API can be used to analyze unstructured text for tasks such as sentiment analysis and key phrase extraction.
The API returns a numeric score between 0 & 1. Scores close to 1 indicate positive sentiment, while scores close to 0 indicate negative sentiment.
The advantage of this API is that a new model need not be designed and trained, the user only needs to bring the data and call the service to get the sentiment results.
However, because this is only the initial release of this service only English is supported right now.
How it works
Text Analytics API does not simply use a lexicon approach to map words such as “good or “bad” to return the results.
Instead, it uses advanced natural language processing techniques under the hood.
For even more details of the service, consult the documentation here.
Signing up for the Text Analytics Service
- Go to Text Analytics
- Select the required package.
For testing purposed, up to 10,000 transactions are available for free.
The following are the prices as on October 10, 2015.
- Once the registration is done, you shall be provided with an account key. Keep it safely, this shall be used in the applications.
Sample Chat Application
One cool application of this API can be to use it in a chat application which analyse the sentiment of each chat and automatically places a smiley for the user.
Expected Outcome
High Level Application Design
When a user sends a message, the message is first broadcast to all the connected clients. Then, an asynchronous call is made to the Web Service to get the sentiment. After the sentiment score is obtained, the chat is updated with the corresponding smiley.
Diving in the Codes
This is an ASP.NET MVC Application which makes calls to the Web Service asynchronously and place the smiley only after the result is obtained.
Calling the Text Analytics Service
- Declare the Service Base URI and Account Key
- string ServiceBaseUri = "https://api.datamarket.azure.com/";
- string accountKey = "xxxxxx";
- Connect to the Service and pass connection details
- using(var httpClient = new HttpClient()) {
- string inputTextEncoded = HttpUtility.UrlEncode(inputText);
- httpClient.BaseAddress = new Uri(ServiceBaseUri);
- 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 the sentiment score.
- string sentimentRequest = "data.ashx/amla/text-analytics/v1/GetSentiment?Text=" + inputTextEncoded;
- System.Threading.Tasks.Task < HttpResponseMessage > responseTask = httpClient.GetAsync(sentimentRequest);
- responseTask.Wait();
- HttpResponseMessage response = responseTask.Result;
- Task < string > contentTask = response.Content.ReadAsStringAsync();
- string content = contentTask.Result;
- if (!response.IsSuccessStatusCode) {
- return -1;
- }
-
- SentimentResult sentimentResult JsonConvert.DeserializeObject < SentimentResult > (content)
The UI
The UI is mainly in 2 parts; a form to capture and a div to display the result.
- The form
- <div class=" col-sm-4" <form class="form-horizontal">
- <div class="form-group">
- <div class="col-sm-10">
- <input type="text" id="name" placeholder="name" class="form-control" /> </br>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-10">
- <textarea class="form-control" id="msg" placeholder="Message" rows="3"></textarea>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-10">
- <br />
- <input type="button" id="send" value="send" class="btn btn-primary btn-lg" />
- </div>
- </div>
- </form>
- </div>
- The div to display the result.
- <div id="message" class=" col-sm-8 container" style=" height: 50%; max-height:300px; overflow: scroll;">
- </div>
The JavaScript
There are 2 main functions on the JavaScript part, to send a message and to append messages to the div.
- Append the messages to the div
Here, 2 actions are defined. Action 1 is when a broadcast happen and action 2 is when the result from the Web Service is obtained and it appends the smiley to the existing div.
- var chat = $.connection.chatHub;
-
- chat.client.addNewMessageToPageChat = function(message, id, action) {
-
- if (action == 1) {
- var text = document.getElementById('message').innerHTML;
- document.getElementById('message').innerHTML = message + '<label id =' + id + '> </label> ' + '<br/>' + text;
- }
-
- if (action == 2) {
- document.getElementById(id).innerHTML = message;
- }
-
- $('#message').emoticonize();
- };
- Send a message
This method captures the input and sends it to the server.
- $.connection.hub.start().done(function() {
- $('#send').click(function() {
- var name = $('#name').val();
- var msg = $('#msg').val();
- var tosen = name + ': ' + msg;
- chat.server.send(tosen);
- $('#msg').val('').focus();
- });
- });
C# Code
This method will be called when the send button is clicked.
This will firstly broadcast the message to all the clients by calling the JavaScript addNewMessageToPageChat function.
Then, it will call the method UpdateEmoticon which will connect to the service, get the sentiment score and asynchronously update the div on the front end to update the emoticon.
- public async Task Send(string message)
- {
- string guid = Guid.NewGuid().ToString();
- Clients.All.addNewMessageToPageChat(message, guid, 1);
- await UpdateEmoticon(guid, message);
-
- }
The method
UpdateEmoticon will then determine which smiley to use based on the Sentiment Score obtained and update the chat on the front end.
- public async Task UpdateEmoticon(string guid, string message)
- {
-
- //The codes in the method Process Text is described above in section Calling the Text Analytics Service
- double result = await ProcessText(message);
- string output = "";
- if (result >= 0.6)
- {
-
- output = " :) ";
- }
- else
- {
- output = " :| ";
-
- }
- Clients.All.addNewMessageToPageChat(output, guid, 2);
- }
References