Click here to Skip to main content
15,879,474 members
Articles / Artificial Intelligence / ML.Net

Getting Started with ML.NET Model Builder for using in ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
12 Mar 2020CPOL9 min read 16.8K   280   9   1
How to create ML.NET Application using ML.NET Model Builder and use the trained model to predict the result in ASP.NET Core.
In this article, we take a look at the basic concept of the ML.NET which needs to be used to develop our Machine learning applications. Using ML.NET model builder, it's easy to Load the data either from CSV, Excel or from the database, select and train our preferred available ML.NET Models or go with Custom model training, evaluate the model and finally predict and display the trained model result to any of our .NET applications. Now in this article, we will take a look at the trained and predicted results we will be displaying in our ASP.NET Core application.

Introduction

Image 1

In this article, we will see in detail how to create ML.NET Application using ML.NET Model Builder and use the trained model to predict the result in ASP.NET Core.

ML.NET Model builders make our work easier to develop ML.NET application as to build, train and deploy the models more easily for all kinds of ML .NET supporting models as well us for developing the custom models. If you are new to ML.NET, kindly read my previous articles related to ML.NET. The latest version of ML.NET also established to develop easy custom ML using AutoML and with ML.NET Model builders.

Before getting started with the ML.NET, let's understand the basic concept of the ML.NET which needs to be used to develop our Machine learning applications.

Load Data: For the perfect prediction of results, we need to give lot of data to train the model. In ML.Net, we can give the data for both train and test by Text (CSV/TSV, Relational Database).

Train: We need to select the right algorithm to train the model. Depending on our needs, we have to pick the correct algorithm to train and predict the results.

Evaluate: Select the Machine learning type for our model training and prediction. If you need to work with segment, then you can select the Clustering model. If you need to find the price of stock prediction, you can select the Regression and if you need to find the sentiment analysis, then can select the Classification model.

Predicted Results: Based on the train and test data with trained model, the final prediction will be displayed using the ML.NET application. Trained model will be saved as the binary format which can also be integrated with our other .NET applications.

Image 2

Now using ML.NET model builder, it's easy to Load the data either from CSV, Excel or from the Database, select and train our preferred available ML.NET Models or go with Custom model training. Evaluate the model and finally predict and display the trained model result to any of our .NET applications. Now in this article, let's take a look at the trained and predicted results we will be displaying in our ASP.NET Core application.

In ML.NET Mode builder, we can see the following scenario (Note: Microsoft can add more scenario as it might be different from each version.)

Image 3

In this sample program, we will be using ML.NET Model builder to predict the Item Stock using the Custom Scenario.

In my previous article which I wrote on April 2018, I have explained about same Item Stock Prediction using the console application, I have used the same Item Stock Data as CSV file and use the data to train the model and predict the result and finally bind the result to the ASP.NET Core application.

Item Stock data will look like this and here I have the columns as Item Code, Location Code, Warehouse in Quantity, Warehouse Out Quantity, Item Type and finally Remaining Item total Stock quantity of each item in each location. We will use the below dataset to train, evaluate and predict the result using the ML.NET Model builder.

Image 4

Background

Prerequisites

Using the Code

Step 1 - Create ASP.NET Core Application

(Note: I have used Visual Studio 2019.)

After installing the prerequisites, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop >> click Create a Project. Click Continue.

Image 5

Select ASP.NET Core Web Application and click Next.

Image 6

Select the Project Folder and check the Place solutions in the same directory and on create button.

Image 7

Now select Web Application (Model-View-Controller) and click Create button.

Image 8

We can see our ASP.NET Project has been created with Controllers/Models and Views.

Image 9

Step 2: Working with ML.NET Model Builder

Right click on the project and select Add and click on the Machine Learning.

Image 10

We can see as the ML.NET Model Builder.

Image 11

In ML.NET Model Builder left side, we can see the menu like Scenario, Data, Train, Evaluate and Code.

Scenario: From the Scenario, you can see the available ML.NET Models for the development example like Binary classification, Image Classification, etc. Also, you can see the Custom Scenario to build our own custom models. In our demo, we will be using the custom model.

Data: You can load the data for training from the file or from the database.

Train: Select the model to be trained

Evaluate: Evaluate will be performed after the model training has been completed. In evaluate, the trained model will be compared with the test data to compare and predict the final result to be produced.

Code: Finally, the code will be used to create for the trained model and use it in any of our applications we will be using final trained and evaluated model code for our ASP.NET Core application to predict and display the result for Total Item stock Quantity available per location.

Custom Scenario: Here, we have selected the Custom scenario of our demo application in order to predict the Stock quantity.

Image 12

Data

After selecting our Scenario, we can see the next menu will be displayed as here we have selected the Custom Scenario and next, the Data menu has been displayed and from here, we have the option to load the data to be trained as from the file or from the Database. Here, we will be using the file to load the data.

Click on the Select a file and load the file. We can see here as we have loaded the file to be trained.

Image 13

Next, we need to select the column to be predict (In Machine Learning, the prediction column is called as the Label). In our demo, we are going to predict the TotalStockQty. Also, we need to select the Input column given by us to predict the result. Here for our demo, we need to predict the Stock Qty based on the Item and by the Location. So here, we have selected Input columns (Feature) columns as ItemID and Loccode.

Image 14

Train

After that, click on the train button to train the model with the loaded data.
In the train screen, we can see the Machine Learning tasks to be selected for training our model and also we can see the time to train the model in seconds to be selected.

Image 15

Machine Learning Task: We can see for the custom scenario, the task available for ML.NET is multiclass-classification, Binary-classification and regression. Here for our demo, we have selected the multiclass-classification.

Image 16

Here, our file size is very less and up to 10MB data size, we can select approximate 10 seconds to train the model.

After selecting the Machine learning task and training time, click on the Start training button and wait for few seconds to complete the training.

Image 17

Now we can see the training is completed and also best algorithm used and next, we need to click on the Evaluate button to evaluate our training model.

Evaluate

In evaluate screen, we can evaluate the trained model and finally click on the code button to get the code.

Image 18

Code

We can see as the ML.NET Model, training and testing project can been added to our solutions. We will add this model to our ASP.NET Code project solution. For that, we need to click on the Add to projects button.

Image 19

We can see as the both Model and the console project have been added to our ASP.NET Core solution. Now let’s see how to import the model to our ASP.NET core and display the predicted result to the users.

Image 20

Step 3: Add the ML.NET to ASP.NET Core Project for Prediction

Select Tools from the menu, Select NuGet Package Manager and click on Manage NuGet Packages for Solution .

Image 21

Select Browse and enter ML.NET in search and select the Microsoft.ML also in the right side, we can see our ML.NET model projects will be displayed, select the project and click on Install.

Image 22

Step 4: Create New ASP.NET Core Controller

Right click on the Controller Class and click new Empty control and give the controller name as the StockPrediction and add the controller to the controller folder.

Image 23

Step 5: Create New ASP.NET Core View

Next create a new folder inside the View folder as StockPrediction and also add a view as the name of StockPrediction.cshtml.

Image 24

Controller Code

In the StockPredictionController Controller, add the below code:

C#
using ShanuASPMLNETML.Model;

After import that add the below code. Here, we change the default view with our new View name also we have created one more post Action result and return the predicted result to the view to bind the results.

C#
public class StockPredictionController : Controller
    {
        [HttpGet]
        public IActionResult StockPrediction()
        {
            return View();
        }

        [HttpPost]
        public ActionResult StockPrediction(ModelInput input)
        {
            ViewBag.Result = "";
            var stockPredictions = ConsumeModel.Predict(input);
            ViewBag.Result = stockPredictions;

            ViewData["ItemID"] = input.ItemID;
            ViewData["Loccode"] = input.Loccode;
            return View();
        }
    }

View Code

In the StockPrediction View, add the below code. Here, we have added 2 textboxes as one for the item Code input and one for the Location code input and we have set the same name as our model name so that the data will be passed to our Trained model and return the predicted results and finally we bind the predicted results to the users.

HTML
 @model ShanuASPMLNETML.Model.ModelInput
@{
    ViewData["Title"] = "item Stock Predicti0n";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Welcome to Shanu Stock Prediction for the Item by Warehouse Location</h2>
<h3>using ML.NET in ASP.NET Core</h3>
<hr />

<div class="row">
    <div class="col-md-12">
        <form asp-action="StockPrediction">
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="ItemID" class="control-label">Item ID</label>
                    <input asp-for="ItemID" class="form-control" />
                </div>
                <div class="form-group col-md-4">
                    <label asp-for="Loccode" class="control-label">
                         Warehouse Location Code:</label>
                    <input asp-for="Loccode" class="form-control" />
                </div>

            </div>
            <div class="form-group col-md-4 text-left">
                <label class="control-label"></label>
                <input type="submit" value="Stock Prediction" class="btn btn-primary" />
            </div>
        </form>
        <hr />
    </div>

</div>

@if (ViewBag.Result != null)
{
    <div class="row">
        <div class="col-md-12">
            <h2 style="color:#103f62">Here is the Test result for Item : 
            <span style="color:#a50f0f"> @ViewData["ItemID"]  </span> 
            for the Warehouse location <span style="color:#a50f0f">@ViewData["Loccode"] 
            </span>  </h2>
            <h1 style="color:#a50f0f">Final Predicted Stock Quantity is 
            :@ViewBag.Result.Prediction  </h1>
        </div>
    </div>
    <hr />
}

Build and Run the Project

We can enter the Item code and Location code to be predicted and display the Stock Quantity.

Here, we have entered the Item code as Item001 and Location code as 1.

Image 25

We can see the Predicted result as :90.

In the Excel file, we can also cross check the result or our original data.

Image 26

Same like above, we test for one more data for prediction and you can see the result.

Here, we have entered the Item code as Item003 and Location code as 2.

Image 27

The Excel file data for Item003 we have added in the file is as below:

Image 28

From both the results, we can find the prediction is done 100% and the result is as expected.

Points of Interest

ML.NET (Machine Learning DotNet) is a great framework for all the .NET lovers who are looking to work with machine learning. Now only preview version of ML.NET is available and I can’t wait till the release of the public version of ML.NET. If you are .NET lovers, not aware about Machine Learning and looking forward to work with machine learning, then ML.Net is for you all and it's a great framework to getting started with ML.NET. Hope you all enjoyed reading this article and see you all soon with another post.

History

  • 9th March, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionMy vote of 5 Pin
Dean Allcorn19-Mar-20 8:00
Dean Allcorn19-Mar-20 8:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.