Sentiment analysis in an ASP.NET web application with ML.NET
Published: 2021-10-07 16:49:14

Hey, there! It's a pleasure to greet you. In this tutorial article, we will learn step by step to generate a custom Machine Learning model from ML.NET for sentiment analysis in text, and then learn to consume that model from a web application on ASP.NET with the MVVM pattern (Model, View, ViewModel).

###**What is ML.NET and how does it work?**

ML.NET is an open source Machine Learning platform that allows us to transform input data into an ML model, and then be able to integrate it into any type of application on the .NET ecosystem, whether web, mobile, desktop, or any other type of application.  

These are the types of models that we can generate in ML.NET:

| Model type| Objective |
| ------------- |:-------------:|
| Classification/Categorization | Automatically divide customer reviews into positive and negative categories. |
| Regression/Prediction of continuous values | Predict the price of homes based on size and location. |
| Anomaly detection. | Detect fraudulent banking transactions. |
| Recommendations | Suggest products that online shoppers want to buy, based on their previous purchases. |
| Time series/sequential data | Forecast weather/sales. |
| Classification of images| Categorize pathologies in medical images. |

In our case we will focus on the classification/categorization of text comments. 

###**Text sentiment analysis**

For sentiment analysis, the intention is to be able to classify text entries into two groups: positive comments (1) and negative comments (0). 

To achieve this goal, we will perform three 
activities in this article: 

+ 1. Meet the necessary requirements and prepare our solution in Visual Studio. 
+ 2. Create our Machine Learning model with ML.NET. 
+ 3. Consume the model generated from ASP.NET. 

With this mentioned, let's get started! 

##**Part 1: Prerequisites and Solution Preparation in Visual Studio**

In order to generate our Machine Learning model, we will use the Model Builder interpreter of ML.NET. For this, we need to have the following workload in Visual Studio (.NET Cross-Platform Development):

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av5w0cfcd4n4m8e52pey.png)

With this workload, we can now create our solution. In this case, the intention is to consume the ML model that we are going to generate from a web application, for this purpose we will use the DotVVM framework that allows us to work with HTML pages and C# classes on ASP.NET with the MVVM pattern (Model, View, ModelView).

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/csglgk3be7fkmto8m4ae.png)

##**Part 2: Building the Machine Learning Model**

It's time to see ML.NET in action! As in any other process in the world of Machine Learning to generate a model, the steps to build the sentiment analysis model are as follows: 

+ Set the ML scenario.
+ Prepare the environment for data training. 
+ Load the dataset. 
+ Train the model.
+ Evaluate the model. 
+ Consume the model. 

To begin with, in the main project of our solution we will add a component of type Machine Learning:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sves3lt3cmdqayrk7aht.png)

With this option, the ML.NET Model Builder interpreter will be initialized and we can start customizing the model. 

**Scenario:**

The first step is to select the scenario with which we want to work, in this case it will be *Text classification*:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c230u7rzvksroy41dyyf.png)

**Environment:**

Now, we must select the computing resources for the training of our model. For text classification in particular we can only use the CPU of our computer.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1casjjksgqvpeh2qnlcg.png)

**Data source:**

This is one of the most important parts, since with the data we can customize our model. To do this we can select two types of sources, either by making a connection and at the same time a query to a SQL Server database, or by means of a CSV file. 

In this case we will use a CSV file with two columns, the first with the text in question, and the second column with the type of comment (0 negative – 1 positive). 

Here's an example of a dataset: [wikipedia-detox-250-line-data.tsv](https://raw.githubusercontent.com/dotnet/machinelearning/main/test/data/wikipedia-detox-250-line-data.tsv).

By loading it we can have a preview of the data, and select the column that we want to predict later.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzlnggkbm4sjdouzmzrk.png)

**Training:**

With everything we have already established so far, we can already perform the training process, and finally generate the desired model. In this section the only thing we can customize is the maximum time in which ML.NET can search for the ideal model for text classification. 

At the end of the training process we can visualize how many models ML.NET evaluated, and the accuracy of the best model found.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7o9sbvj0ka03fm4r6psl.png)

**Evaluation:**

Up to this point we already have the model established, anyway, from the Model Builder of ML.NET we can evaluate the model with a particular example.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0mtlcggcy60h6jt7jms.png)

**Consume:**

Finally, the interpreter will give us options to consume the created model, either by creating other projects (by console or with a web api), or indicating the calls we must make from our own application.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6zeoumqahcul755cg25.png)

In this case, we can already consume the model from our web application with DotVVM on ASP.NET with the new generated package: `MLModel.mbconfig`. 

##**Part 2: Consume the generated model from ASP.NET**

To consume the model we must refer to the MLModel class, which was generated by ML.NET in the group `MLModel.mbconfig`:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kco3jipwhgpnx0lgdbw0.png)

In this sense, it is necessary to establish an instance of ModelInput with the comment we want to predict, and then call the Predict method, and obtain an object of type ModelOutput with the corresponding prediction (1 positive, 0 negative), and its probability.

**ViewModel:**

For this purpose, and to be able to establish a web page with DotVVM, in a ViewModel, in this case the `DefaultViewModel.cs`, we will define three attributes or global variables:

```csharp
public string InputText { get; set; }
public string Result { get; set; } = null;
public decimal? Score { get; set; } = null;
```

These variables will allow us to store the text entered by the user in `InputText`, and represent the results of the prediction in the attributes `Result` and `Score`.

Then we can set a method in this class, in such a way that it represents the action of a button to make the prediction:

```csharp
public void Predict()
{
	var sampleData = new MLModel.ModelInput()
	{
		Col0 = InputText,
	};

	//Load model and predict output
	var output = MLModel.Predict(sampleData);

	if ((int)output.Prediction == 0)
	{
		Result = "Negative.";
	}
	else
	{
		Result = "Positive.";
	}

	Score = decimal.Round((decimal)(output.Score[(int)output.Prediction] * 100), 2);
}
```

In this code we have three important parts:

+ Initialize an `MLModel.ModelInput` with the comment entered by the user. 
+ Call the `MLModel.Predict` with the `ModelInput` as a parameter, thus obtaining the `ModelOutput` with the results.
+ Prepare the `Result` to visualize the result later (positive or negative), and its accuracy in the prediction. 

**View:**

Very well, we can now construct the view by referencing the attributes and method created in the `ViewModel`. This view will be encoded in the file `Default.dothtml` as follows:

```html
<table style="border: hidden">
    <tbody style="border: hidden">
        <tr style="border: hidden">
            <td style="border: hidden" align="center">
                <dot:TextBox Text="{value: InputText}" placeholder="Write your text..." />
            </td>
            <td style="border: hidden" align="center">
                <dot:Button Click="{command: Predict()}" Text="Predict" />
            </td>
            <td style="border: hidden" align="center">
                <b>{{value: Result}}</b> {{value: Score}}
            </td>
        </tr>
    </tbody>
</table>
```

Here the most important thing is the `TextBox` control for the user to enter their comment and store it in the `InputText` attribute, the call to the `Predict()` method with a `Button`, and the display of the results by displaying the values of the variables `Result`, and `Score`.
 
**Examples running:** 

With this *View*, and its *ViewModel*, our website is ready. Here we can see two examples at runtime:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdebrfw1gh5kkqdjawg3.png)

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxpao6rn0gevgd5he39p.png)

The source code for this demo is available in this GitHub repository: [github.com/esdanielgomez/MLNET_SentimentAnalysis](https://github.com/esdanielgomez/MLNET_SentimentAnalysis).

##**Thank you!**

Thank you very much for reading, I hope this demo can be useful to you. If you have any questions or ideas that you need to discuss, it will be a pleasure to be able to collaborate and together exchange knowledge with each other.

See you at [Twitter](https://twitter.com/esDanielGomez)! Or if you like you can also write to me by [Facebook] (https://www.facebook.com/esDanielGomez) or by mail: daniel@esdanielgomez.com. :=)

*- Header image reference*: [Real Python](https://realpython.com/).