Home » Machine Learning with C#
Machine Learning with C#
In this section we’ll learn about ML.Net. How we can work with C#.
Prerequisites:
- Prior knowledge of .NET
- It will be supported in Visual Studio 2017 / 2019 version
What is ML?
Machine learning is the study of computer algorithms that can improve automatically through experience and by the use of data. It is the field of study that gives computers the capability to learn without being explicitly programmed.
What is AI?
Artificial intelligence is intelligence demonstrated by machines, as opposed to the natural intelligence displayed by humans or animals. It is a constellation of many different technologies working together to enable machines to sense, comprehend, act, and learn with human-like levels of intelligence. AI isn’t just one thing.
ML & AI:
Artificial intelligence and machine learning are the part of computer science that are correlated with each other. These two technologies are the most trending technologies which are used for creating intelligent systems.
“AI is a bigger concept to create intelligent machines that can simulate human thinking capability and behavior, whereas, machine learning is an application or subset of AI that allows machines to learn from data without being programmed explicitly.”
Let’s take an Example:
Basic Structure of ML with Example:

Algorithm:
Algorithm is a finite sequence of well-defined, computer-implementable instructions.
We do not have to make changes in code. The algorithm makes the intelligent decision it self and gives the predicted output.
- User can set different algorithams as per there requirement
Training Data:
Machine learning algorithms build a model based on sample data, known as “training data”.
In other words, Training data is a data set of examples used during the learning process and is used to fit the parameters.
Model:
A machine learning model is a file that has been trained to recognize certain types of patterns. You train a model over a set of data, providing it an algorithm that it can use to reason over and learn from those data.
Feature is nothing but it is the Input and Label is the output. Training data trains the algorithm with the proper features and label, will get very important output as a Model. Model is the heart of Machine learning.
If any case do not get expected output then need to refine the training data and retrain the algorithm. Model is final important artifact of machine learning.
Pipeline:
A machine learning pipeline is a way to codify and automate the workflow it takes to produce a machine learning model. Machine learning pipelines consist of multiple sequential steps that do everything from data extraction and preprocessing to model training and deployment.
Let’s take a example:
- Open Visual studio 2019

Step 1: Create a console application

Set Application name:

Step 2: Create and set Training Data

class TrainingData
{
public bool AnswerStr { get; set; }
public string QuestionStr { get; set; }
}
static List<TrainingData> LoadData()
{
List<TrainingData> actualData = new List<TrainingData>();
actualData.Add(new TrainingData
{
QuestionStr = "Components",
AnswerStr = true
});
actualData.Add(new TrainingData
{
QuestionStr = "Is this Single Page Application",
AnswerStr = true
});
actualData.Add(new TrainingData
{
QuestionStr = "Connect with DB",
AnswerStr = false
});
actualData.Add(new TrainingData
{
QuestionStr = "Backend",
AnswerStr = false
});
return actualData;
}
Step 3: Load training data for ML process
class Program
{
static void Main(string[] args)
{
var actualData = LoadData();
}
}
Step 4: Install Nuget package Microsoft.ML
- Right click on application name -> Manage nuget package

Step 5: Install Nuget package Microsoft.ML.FastTree

Step 6: Create object of MLcontext
var mlContext = new MLContext();
Step 7: Convert data into the data view
IDataView dataView = mlContext.Data.LoadFromEnumerable<TrainingData>(actualData);
Step 8: Create a pipeline for work flow
- All column ordering and output columnname into the model

- Here we are using BinaryClassification algoritham. Which have been predicted output will be true / false.
var pipeLine = mlContext.Transforms.Text.FeaturizeText(outputColumnName: "Features", inputColumnName: "QuestionStr").Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));
Step 9: Here trained the algorithm and get model
var model = pipeLine.Fit(dataView);

Step 10: Prepare input data
var ip = new TrainingData();
ip.QuestionStr = inputString;
Create a prediction engine for one-time prediction. It’s mainly used in conjunction with Load(Stream, DataViewSchema), where input schema is extracted during loading the model.
Step 11: Create Prediction Engine to get output
Use the Predict method and pass in your input data as a parameter. Notice that using the Predict method does not require the input to be an (DataView). This is because it conveniently internalizes the input data type manipulation so you can pass in an object of the input data type.
- Create a class for output data :
class OutputData
{
[ColumnName("PredictedLabel")]
public bool AnswerStr { get; set; }
}
var predictor = mlContext.Model.CreatePredictionEngine<TrainingData, OutputData>(model);
var feedback = predictor.Predict(ip);
Console.WriteLine(feedback.AnswerStr); // Print the output
Code Snippet:
static void Main(string[] args)
{
var actualData = LoadData();
var mlContext = new MLContext();
IDataView dataView = mlContext.Data.LoadFromEnumerable<TrainingData>(actualData);
var pipeLine = mlContext.Transforms.Text.FeaturizeText(outputColumnName: "Features", inputColumnName: "QuestionStr").Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));
var model = pipeLine.Fit(dataView);
Console.WriteLine("Insert angular terms \n");
for (int i = 0; i <= 4; i++)
{
Console.WriteLine("Enter Input");
string inputString = Console.ReadLine().ToString();
var ip = new TrainingData();
ip.QuestionStr = inputString;
var predictor = mlContext.Model.CreatePredictionEngine<TrainingData, OutputData>(model);
var feedback = predictor.Predict(ip);
Console.WriteLine("Output is \t" + feedback.AnswerStr);
//Console.WriteLine(feedback.AnswerStr);
Console.ReadLine();
}
}
Run the Application:
Test 1: “Component” (exists in training data list) is the input

Test 2:

Test 3:

That’s it. Over To You!
That’s it for now. Today you have learned about Machine Learning in C# with example. Happy Coding…
>>Explore more Dot NET Development Tutorials and Updates
I am working as Jr. Full Stack Developer (.NET/Angular) at Samarpan Infotech. I've good analytical thinking and collaboration skills, and I love working with a team.


