Language: EN

csharp-ml-dotnet

Introduction to Machine Learning in C# with ML.NET

ML.NET is an open-source library developed by Microsoft that allows .NET developers to integrate Machine Learning (ML) capabilities into their applications.

ML.NET provides a robust platform for creating, training, and deploying machine learning models without the need for deep knowledge in ML, and it integrates seamlessly with the .NET ecosystem.

Additionally, Microsoft provides the ML.NET Model Builder, a graphical tool that allows .NET to create, train, and consume machine learning models directly from Visual Studio, without the need to have in-depth knowledge in the field of machine learning.

Model Builder uses a scenario-based approach, guiding us step by step through the process of creating models for common tasks such as classification, regression, and anomaly detection.

Some features of ML.NET include:

  • Support for Pretrained Models: Utilizes pretrained models from TensorFlow and ONNX, enabling the use of existing models without the need to train from scratch.
  • Interoperability with Data Environments: Supports data in common formats like CSV, SQL, and others, facilitating integration with various systems.
  • Ease of Use: Provides an intuitive and easy-to-use API for .NET developers, allowing the creation of ML models with minimal configuration.
  • Supervised and Unsupervised Learning Capabilities: Includes support for regression, classification, clustering, and anomaly detection.
  • Training and Evaluation: Facilitates model training, performance evaluation, and hyperparameter tuning.

For more information, documentation, and additional examples, visit the official ML.NET repository on GitHub and the official ML.NET page. Here you will find additional resources to get started and make the most of this little marvel.

Installing ML.NET

To start using ML.NET in your C# project, you need to add the corresponding package to your solution. You can do this through the NuGet package manager. Open the terminal or the package manager console in Visual Studio and run the following command:

Install-Package Microsoft.ML

Alternatively, you can search for Microsoft.ML in the NuGet interface in Visual Studio and install it from there.

Installing ML.NET Builder

Although it is possible to start using ML.Net directly, the easiest way is to use ML.NET Model Builder, which is installed as an extension in Visual Studio. To do this,

ml-net-demo-1

  1. Open Visual Studio.
  2. Navigate to Extensions > Manage Extensions.
  3. Search for “ML.NET Model Builder” in the search box.
  4. Click Download and install the extension.

In this case, there is no need to add the NuGet directly as we saw in the previous step. Model Builder configures the dependencies for us.

How to Use ML.NET

Once you have the extension installed, you can start creating and training machine learning models.

In your Visual Studio project, right-click on the project in the Solution Explorer. Select Add > Machine Learning.

ml-net-demo-2

Model Builder will guide you through a wizard where you can select the type of problem you want to solve, such as classification, regression, or anomaly detection.

ml-net-demo-4

Depending on the model you have chosen, Model Builder will prompt you to load the dataset you will use to train the model. You can load data from a CSV file, a SQL Server database, among others.

Select the data source, load and configure the data, and proceed to train the model. Model Builder will automatically select the best algorithm and tune the hyperparameters.

Once the training is complete, Model Builder will show you performance metrics of the model, such as accuracy and mean squared error, depending on the type of problem selected.

Example of Generated Code

Model Builder will generate the necessary code to integrate and consume the model in your application.

ml-net-demo-3

The generated code will include two main parts: model configuration and prediction of new data.

Below is an example of what the generated code might look like for a classification task.

// Model configuration
public static ITransformer TrainModel(MLContext mlContext, string dataPath)
{
    IDataView dataView = mlContext.Data.LoadFromTextFile<ModelInput>(dataPath, hasHeader: true, separatorChar: ',');

    var pipeline = mlContext.Transforms.Conversion.MapValueToKey("Label")
                    .Append(mlContext.Transforms.Concatenate("Features", "Feature1", "Feature2"))
                    .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features"))
                    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));

    var model = pipeline.Fit(dataView);
    return model;
}

// Prediction of new data
public static void UseModel(MLContext mlContext, ITransformer model)
{
    var predictionEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(model);

    var input = new ModelInput { Feature1 = 1.5f, Feature2 = 2.3f };
    var result = predictionEngine.Predict(input);

    Console.WriteLine($"Predicted Label: {result.PredictedLabel}");
}

Additionally, it will provide the necessary code to easily use it from our project. For example,

//Load sample data
var sampleData = new MLModel1.ModelInput()
{
    Input = 2F,
};

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

It’s that simple. From there, you can make modifications to the code generated by ML.NET Model Builder or consume it directly in your application. It truly cannot be more convenient and practical.