Sentiment Analysis In ASP.NET Core Using ML.Net

In this article, we'll learn how ML.NET framework is used to build sentiment analysis machine learning solutions and integrate them into ASP.NET Core applications.

Problem

 
This problem is centered around predicting if a customer's review has a positive or negative sentiment. We will use small Wikipedia-detox-datasets (one dataset for training and a second dataset for model's accuracy evaluation) that were processed by humans and each comment has been assigned a sentiment label:
  • 0 - nice/positive
  • 1 - toxic/negative
Using those datasets we will build a model that when predicting, will analyze a string and predict a sentiment value of 0 or 1.
 
Prerequisites
  • Visual Studio 2019 or 2017 
  • ML.NET Model Builder Extension for Visual Studio

Solution

 
To solve this problem, first, we will build an ML model. Then we will train the model on existing data, evaluate how good it is, and lastly, we'll consume the model and integrate it into our Asp.Net Core application to predict sentiment for new comments or reviews.
Sentiment Analysis In ASP.NET Core Using ML.Net 
Let's start,
  • Download and Install ML.NET Model Builder tool from Visual Studio Marketplace. Click here.
  • After ML.NET Model Builder installation open your Visual Studio (in my case I'm using VS2019) 

    Sentiment Analysis In ASP.NET Core Using ML.Net

  •  After Project has been selected, enter your Project Name.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • Select Asp.Net Core template which you want to use, I'm using Web Application MVC.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • After the project has been created, we will start to build our model. Right-click on Project > Add > Machine Learning,

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • ML.NET Model Builder tool GUI has been opened. Select Sentiment Analysis.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • After scenario selection, we will select the data set that will be used to train our model. You add data from the file as well as using SQL Server Database. I will use wikiDetoxAnnotated40kRows data to train my model. You can download it from here. After data source selection click on Train link

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • After data source selection, enter the time for which you want to train the model and click on Start training button, and the model training will be started for the entered time.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • After the model has been successfully trained click on the evaluation button.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • You can see the new build machine learning model evaluation. Click on code button to consume the model into your project.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • As you can see in solution explorer, the ML.NET Machine Learning model has been created.

    Sentiment Analysis In ASP.NET Core Using ML.Net

  • Now, the machine learning model for semantic analysis has been created. Now, first, we need to add the reference Semantic AnalysisML.Model project into our Semantic Analysis Web project and also add ML.NET package from NuGet.

    Sentiment Analysis In ASP.NET Core Using ML.Net

Create a new empty controller named Semantic and copy the snippet code.
  1. using System;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.ML;  
  4. using SentimentAnalysisML.Model.DataModels;  
  5.   
  6. namespace Sentiment_Analysis.Controllers  
  7. {  
  8.     public class SemanticController : Controller  
  9.     {  
  10.         [HttpGet]  
  11.         public IActionResult Analysis()  
  12.         {  
  13.             return View();  
  14.         }  
  15.         [HttpPost]  
  16.         public IActionResult Analysis(ModelInput input)  
  17.         {  
  18.             // Load the model  
  19.             MLContext mlContext = new MLContext();  
  20.             ITransformer mlModel = mlContext.Model.Load(@"..\Sentiment AnalysisML.Model\MLModel.zip"out var modelInputSchema);
  21.             // Create predection engine related to the loaded train model
  22.             var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel);  
  23.             //Input  
  24.             input.Year = DateTime.Now.Year;  
  25.             // Try model on sample data and find the score
  26.             ModelOutput result = predEngine.Predict(input); 
  27.              // Store result into ViewBag
  28.             ViewBag.Result = result;  
  29.             return View();  
  30.         }  
  31.     }  
  32. }  
Add a new view named Analysis in Semantic Folder and copy the snippet code.
  1. @model SentimentAnalysisML.Model.DataModels.ModelInput  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Semantic Analysis";  
  5. }  
  6. <h2>Semantic Analysis</h2>  
  7. <hr />  
  8. @{  
  9.     var result = ViewBag.Result;  
  10. }  
  11. <div class="row">  
  12.     <div class="col-md-4">  
  13.         <form asp-action="Analysis">  
  14.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  15.             <div class="form-group">  
  16.                 <label asp-for="Comment" class="control-label"></label>  
  17.                 <input asp-for="Comment" class="form-control" />  
  18.                 <span asp-validation-for="Comment" class="text-danger"></span>  
  19.             </div>  
  20.             <div class="form-group">  
  21.                 <input type="submit" value="Check" class="btn btn-default" />  
  22.             </div>  
  23.         </form>  
  24.     </div>  
  25.     <div class="col-md-offset-4 col-md-4">  
  26.         @if (result != null)  
  27.         {  
  28.             <h2>Result</h2>  
  29.             <h3>Predection:@result.Prediction</h3>  
  30.             <h3>Score:@result.Score</h3>  
  31.         }  
  32.     </div>  
  33. </div>  
  34.   
  35. @section Scripts {  
  36.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  37. }

Demo

  • false - nice/positive
  • true - toxic/negative 
Sentiment Analysis In ASP.NET Core Using ML.Net
Source Code
 
You can also access the source code from GitHub