Build and Train Models - (ASP.NET Core ML.NET)
Machine learning (ML) is a popular field of artificial intelligence that involves creating algorithms that can learn from data. In ASP.NET Core, ML.NET is a framework that makes it easy to create and train custom machine learning models.
Syntax
To build and train a model using ML.NET, you will need to write code that defines what data to use, what algorithm to use, and how to train the model. Here is a template for a basic machine learning model:
using Microsoft.ML;
using Microsoft.ML.Data;
// Define the input data schema
public class InputData
{
[LoadColumn(0)] public float Feature1 { get; set; }
[LoadColumn(1)] public float Feature2 { get; set; }
[LoadColumn(2)] public float Feature3 { get; set; }
[LoadColumn(3)] public float Feature4 { get; set; }
[LoadColumn(4)] public string Label { get; set; }
}
// Define the output data schema
public class OutputData
{
[ColumnName("PredictedLabel")] public string Prediction { get; set; }
}
// Define the machine learning model
public class Model
{
private readonly MLContext _context;
private readonly ITransformer _pipeline;
private readonly PredictionEngine<InputData, OutputData> _predictor;
public Model(string dataPath)
{
// Initialize the MLContext
_context = new MLContext();
// Load the data
var data = _context.Data.LoadFromTextFile<InputData>(dataPath, separatorChar: ',');
// Define the pipeline
var pipeline = _context.Transforms
.Concatenate("Features", "Feature1", "Feature2", "Feature3", "Feature4")
.Append(_context.Transforms.Conversion.MapValueToKey("Label"))
.Append(_context.Transforms.TrainingValidationSplit())
.Append(_context.Transforms.NormalizeMinMax("Features"))
.Append(_context.Transforms.Conversion.MapKeyToValue("Label"))
.Append(_context.Transforms.SelectColumns("Features"))
.Append(_context.Transforms.Concatenate("FeaturesEncoded", "Features"))
.Append(_context.Transforms.NormalizeMinMax("FeaturesEncoded"))
.Append(_context.Transforms.SelectColumns("FeaturesEncoded"))
.Append(_context.Transforms.Conversion.MapKeyToValue("Label"))
.Append(_context.Transforms.Conversion.MapValueToKey("Label"))
.Append(_context.Transforms.NormalizeMinMax("Label"))
.Append(_context.Transforms.Conversion.MapKeyToValue("Label"))
.Append(_context.Transforms.Conversion.MapValueToKey("Label"))
.Append(_context.Transforms.Trainers.LightGbm())
.Append(_context.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
// Train the model
var model = pipeline.Fit(data);
// Create the predictor
_predictor = _context.Model.CreatePredictionEngine<InputData, OutputData>(model);
// Save the pipeline
_pipeline = pipeline;
}
public string Predict(InputData inputData)
{
// Predict the label for the input data
var outputData = _predictor.Predict(inputData);
// Return the predicted label
return outputData.Prediction;
}
public void Save(string modelPath)
{
// Save the pipeline
_context.Model.Save(_pipeline, null, modelPath);
}
}
Example
Here's an example of how to build and train a machine learning model using the Iris dataset in C#:
using System;
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Data;
namespace MLNetExample
{
class Program
{
static void Main(string[] args)
{
// Initialize the model
var model = new Model("iris.csv");
// Train the model
Console.WriteLine("Training the model...");
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
model.Train();
stopwatch.Stop();
Console.WriteLine("Training complete in " + stopwatch.Elapsed);
// Make a prediction
var inputData = new InputData
{
Feature1 = 5.1f,
Feature2 = 3.5f,
Feature3 = 1.4f,
Feature4 = 0.2f
};
var prediction = model.Predict(inputData);
Console.WriteLine("Predicted label: " + prediction);
// Save the model
model.Save("model.zip");
Console.WriteLine("Model saved to model.zip");
}
}
}
Output
When you run the code to build and train your machine learning model, you should see output that looks like this:
Training the model...
Training complete in 00:00:00.1022225
Predicted label: Iris-setosa
Model saved to model.zip
Explanation
In the template and example code, we define the input and output data schemas as C# classes, and use attributes to specify the structure of the data. We define the machine learning model as a separate C# class that references the input and output data schemas, and uses the Microsoft.ML
namespace to access the ML.NET framework. In the Model
class, we use the MLContext
object to initialize the ML.NET framework and read in the data. We then define the pipeline for transforming and training the data, train the model, and save it for future use. In the Main
method of the Program
class, we create an instance of the Model
class, train it, make a prediction, and save the model.
Use
ML.NET is a powerful tool for developing custom machine learning models for your ASP.NET Core applications. You can use it to classify, cluster, or regress data, and integrate it with your other .NET code.
Important Points
- To build and train a machine learning model, you will need to define your input and output data schemas, your machine learning model, and your pipeline for transforming and training the data.
- The
MLContext
object is the main entry point for using the ML.NET framework, and is used to read data, define pipelines, train models, and make predictions. - You can use ML.NET to classify, cluster, or regress data.
Summary
In this page, we discussed how to build and train machine learning models using ML.NET in ASP.NET Core. We covered the syntax, example, output, explanation, use, important points, and summary of building and training machine learning models with ML.NET. ML.NET is a powerful tool for creating custom machine learning models that can be used in your ASP.NET Core applications and integrated with your other .NET code.