Machine Learning Tutorial C# Example

If you are beginners, probably you have read our earlier post what is machine learning!

ML.NET is a machine learning framework by Microsoft, it provides all machine learning API for building different type of machine learning application in C#, With ML.NET, now we can build, train, evaluate and consume our own Machine Learning models in any .net language like C#, Vb.Net, F# etc.

In this ML.Net tutorial, you will learn how to perform basic price prediction using C# machine learning API. If you are python lover then you should look at Machine learning in Python tutorial.

What problem we solve!

In our example, we will predict fruit price based on previous year data.
Note: if you don’t have data you can download Taxi fare standard data for practice.

Start Visual Studio 2019

Open your VS2019, select C# console application and click next.

Note: In this tutorial, you will learn how to use ML.net wizard in Visual Studio 2019, to create a price prediction analysis, ML.Net wizard will produce some code for you that will predict price based on previous data.

Therefore, for first time ML.Net user this will be the best way to get familiar with machine learning using C#.

However, to make changes in code, you must know C#, and if you are already using C# for your development practice, then learn how to write a machine learning regression analysis using C# Console.

ML.net C# example

C# Machine Learning Example

Click next, and then give some meaningful name to your project, then select the location where you want the project to be saved, and click create button.

Right click on project , in property menu => Add => Machine Learning

If you are using for the first time then you may need to download ML.NET Model Builder extension.

Machine Learning Regression analysis

In next window you will get a wizard of five steps, you need to complete all five steps to see the result.

Machine Learning Regression analysis

Now at this stage, you need set the data source; source can be Excel file, CSV File, XML File, SQL Server or any other database.

Now in this example i have chosen SQL server data source, so data will be fetched from my SQL database table.

For your convenient, here is the SQL script to execute.

CREATE TABLE [dbo].[tbSoldProduct](
	[SId] [bigint] IDENTITY(1,1) NOT NULL,
	[ProductId] [bigint] NOT NULL,
	[ProductName] [varchar](100) NOT NULL,
	[UnitPrice] [decimal](18, 2) NOT NULL,
	[SoldQuantity] [int] NOT NULL,
	[SDate] [datetime] NOT NULL,
 CONSTRAINT [PK_tbSoldProduct] PRIMARY KEY CLUSTERED 
(
	[SId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Here are some sample data, or you can add your own

INSERT INTO [dbo].[tbSoldProduct]
(ProductId,[ProductName],[UnitPrice],[SoldQuantity],[SDate])
VALUES
(1, 'Banana',3.50,400,getdate()),
(2, 'Orange',4.50,300,getdate()),
(3, 'apple',5.20,200,getdate()),
(4, 'cherries',1.20,900,getdate()),
(5, 'blueberries',0.50,1500,getdate()),
(1, 'Banana',2.50,900,DATEADD(month, -1, getdate())),
(2, 'Orange',4.10,400,DATEADD(month, -1, getdate())),
(3, 'apple',5.10,700,DATEADD(month, -1, getdate())),
(4, 'cherries',1.00,500,DATEADD(month, -1, getdate())),
(5, 'blueberries',0.90,1400,DATEADD(month, -1, getdate())),
(1, 'Banana',2.10,550,DATEADD(month, -2, getdate())),
(2, 'Orange',3.50,700,DATEADD(month, -2, getdate())),
(3, 'apple',4.75,500,DATEADD(month, -2, getdate())),
(4, 'cherries',1.16,950,DATEADD(month, -2, getdate())),
(5, 'blueberries',1.10,1200,DATEADD(month, -2, getdate())),

Machine Learning Regression analysis

Finally, when you complete the next two simple steps, the code will be generated and added to solution.

At this step, you may see some compilation error, because some assembly like ML.Net etc. are missing

The solution is : Add another Nuget package source with following details, and add from there
Name: nuget.org
Source: https://api.nuget.org/v3/index.json

After changing the Nuget source, you will be able to compile your solution.

Machine Learning Regression Test

Now if you examine the solution, you will see there are two projects added. One has model definition and other one has model build and program file.

Machine Learning auto generated code

As you can see in above picture how auto generated project structure will look like.

You need some data to train and test , if you have your own dataset then use them or else you can download standard data for practice like taxi-fare-train.csv and taxi-fare-test.csv datasets, save them as .csv file in some folder within your solution.

Here is how my model file look like, this file was generated based on my database table defined in SQL Server.

In above class you can change the column name as per your CSV file or SQL Table column name.

using Microsoft.ML.Data;
namespace MLAppML.Model
{
    public class ModelInput
    {
        [ColumnName("SId"), LoadColumn(0)]
        public float SId { get; set; }
        [ColumnName("ProductId"), LoadColumn(1)]
        public float ProductId { get; set; }
        [ColumnName("ProductName"), LoadColumn(2)]
        public string ProductName { get; set; }
        [ColumnName("UnitPrice"), LoadColumn(3)]
        public float UnitPrice { get; set; }
        [ColumnName("SoldQuantity"), LoadColumn(4)]
        public float SoldQuantity { get; set; }
        [ColumnName("SDate"), LoadColumn(5)]
        public string SDate { get; set; }
    }
}

Notice, the source column name and the property name can be different, attribute ColumnName("SId") indicate the source column name, and LoadColumn(0) indicate the sequence number of the column in data source.

[ColumnName("SId"), LoadColumn(0)]
public float SId { get; set; }

Remember, when we executed the ML.Net wizard with data source SQL Table, one csv file was generated from SQL data and stored under temp folder, you can copy the file and move to your application directory.

Open the Program.cs file, Which is pointing to a function Predict(sampleData), and how finally ML.Net API function CreatePredictionEngine<ModelInput, ModelOutput>(mlModel) is being called.

In following code dataFilePath is the source of CSV file, like string DATA_FILEPATH = @"G:\RND\MLApp\testData\fruit-price.csv";, So you may need to change source if you have moved the csv file to your application folder.

using Microsoft.ML;
using Microsoft.ML.Data;
// Create MLContext
MLContext mlContext = new MLContext();
// Load dataset
IDataView dataView = mlContext.Data
.LoadFromTextFile<ModelInput>(path: dataFilePath,
                                hasHeader: true,
                                separatorChar: '\t',
                                allowQuoting: true,
                                allowSparse: false);

Now if you simply run the application, you will see the predicted price from ML.net API.

Now let’s look at the next C# machine learning regression analysis, where you learn more in details about MLContext, data load, data transfer, calling machine learning algorithm.

AI Machine Learning Examples