ML.NET Model Training: Step-by-Step Guide
In this article
This guide shows you how to train machine learning models in C# using ML.NET, Microsoft's open-source, cross-platform machine learning framework. You'll learn to build, train, evaluate, and save a model for common tasks like classification or regression, all within the .NET ecosystem. No prior machine learning experience is required, but basic C# and Visual Studio familiarity helps.
What You'll Need
- .NET SDK (version 6.0 or later) – download from the official Microsoft .NET website.
- An IDE – Visual Studio 2022 (Community edition is free) or Visual Studio Code with the C# extension.
- ML.NET NuGet package – installed via the Package Manager Console or the NuGet Package Manager UI.
- A dataset – a CSV file or similar structured data for training. For this guide, we'll use a simple CSV with numeric features and a label.
Step-by-Step
-
Create a new console application
In Visual Studio, select Create a new project, choose Console App (C#), and name it something like
MLNetDemo. For Visual Studio Code, rundotnet new console -n MLNetDemoin the terminal. -
Install the ML.NET package
Open the Package Manager Console and run
Install-Package Microsoft.ML. Alternatively, use the NuGet Package Manager UI to search forMicrosoft.MLand install the latest stable version. This package includes the core ML.NET APIs. -
Prepare your data
Create a folder named
Datain your project and add a CSV file (e.g.,sample-data.csv). For a binary classification example, the file might look like:Feature1,Feature2,Label 1.2,3.4,0 2.1,5.6,1 3.3,6.7,1 4.5,8.9,0 ...
Ensure the CSV has a header row and that all columns are numeric (or categorical, which you'll handle later).
-
Define the data model classes
In your
Program.cs, add two classes: one for the input data and one for the prediction output. For the CSV above:public class ModelInput { public float Feature1 { get; set; } public float Feature2 { get; set; } public bool Label { get; set; } } public class ModelOutput { public bool PredictedLabel { get; set; } public float Score { get; set; } }Note that the
Labelproperty usesboolfor binary classification. For regression, usefloat. -
Load the data into an IDataView
In the
Mainmethod, create anMLContextand load the CSV file:var context = new MLContext(); string dataPath = "Data/sample-data.csv"; IDataView dataView = context.Data.LoadFromTextFile<ModelInput>(dataPath, separatorChar: ',', hasHeader: true);
This reads the CSV into an
IDataView, the fundamental data structure in ML.NET. -
Split the data into training and test sets
Use the
TrainTestSplitmethod to reserve a portion for evaluation:var split = context.Data.TrainTestSplit(dataView, testFraction: 0.2); IDataView trainData = split.TrainSet; IDataView testData = split.TestSet;
The test set (20% here) is used to evaluate the model after training.
-
Define the data processing pipeline
Create a pipeline that first concatenates all features into a single column, then applies the trainer. For binary classification with logistic regression:
var pipeline = context.Transforms.Concatenate("Features", nameof(ModelInput.Feature1), nameof(ModelInput.Feature2)) .Append(context.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));For regression, use
context.Regression.Trainers.Sdcainstead. -
Train the model
Call the
Fitmethod on the pipeline with the training data:ITransformer model = pipeline.Fit(trainData);
This executes the training algorithm and returns a trained model (transformer).
-
Evaluate the model
Transform the test data and compute metrics:
var predictions = model.Transform(testData); var metrics = context.BinaryClassification.Evaluate(predictions, labelColumnName: "Label"); Console.WriteLine($"Accuracy: {metrics.Accuracy:F2}"); Console.WriteLine($"AUC: {metrics.AreaUnderRocCurve:F2}");For regression, use
context.Regression.Evaluateand check metrics likeRootMeanSquaredError. -
Save the model
If metrics are acceptable, save the model to a file for later use:
context.Model.Save(model, trainData.Schema, "model.zip");
This creates a zip file containing the model and its schema.
-
Make predictions
To use the model, create a prediction engine and pass new data:
var predictionEngine = context.Model.CreatePredictionEngine<ModelInput, ModelOutput>(model); var sample = new ModelInput { Feature1 = 2.0f, Feature2 = 5.0f }; var result = predictionEngine.Predict(sample); Console.WriteLine($"Predicted label: {result.PredictedLabel}");You can also load the saved model later with
context.Model.Load.
Common Mistakes
- Forgetting to concatenate features – ML.NET requires a single 'Features' column; if you skip the Concatenate transform, the trainer will fail or behave unpredictably.
- Mismatched data types – The CSV columns must match the property types in your input class. For example, if your label is numeric (0/1), use
boolfor binary classification orfloatfor regression. - Using the same data for training and evaluation – Always split the data; otherwise, metrics will be overly optimistic and the model may overfit.
- Not handling missing values – ML.NET expects complete data. If your CSV has empty cells, you'll get exceptions. Preprocess your data to fill or remove missing entries.
- Ignoring categorical features – If you have string columns, you must convert them to numeric using
OneHotEncodingor similar transforms before training.
Tips
- Start with a simple model – Use a fast trainer like logistic regression or SDCA first; if accuracy is poor, try more complex algorithms like FastTree or LightGBM.
- Normalize features – For distance-based algorithms, add a
NormalizeMinMaxtransform to the pipeline to scale features. - Use cross-validation – For small datasets, use
context.BinaryClassification.CrossValidateto get more reliable metrics. - Log the pipeline – Set
context.Logto a delegate to see training progress and debug issues. - Save the model schema – When saving, ensure you pass the training data schema; this is required for loading later.
Troubleshooting
- "Column 'Features' not found" error – You likely forgot the Concatenate transform. Add it before the trainer.
- "Invalid data type" exception – Check that your CSV columns match the property types. Convert strings to numbers or booleans as needed.
- Poor accuracy – Increase the training data size, add more features, or try a different algorithm. Also check for class imbalance in binary classification.
- Training takes too long – Reduce the number of features or use a simpler trainer. You can also set the
MaximumNumberOfIterationsparameter in the trainer options. - Model loads but predictions are wrong – Ensure the input data for prediction has the same schema (column names and types) as the training data.
Frequently Asked Questions
Can I use ML.NET with .NET Framework?
Yes, ML.NET supports .NET Framework 4.7.2 and later, but .NET Core/5+ is recommended for better performance and cross-platform support.
How do I handle text data like reviews?
Use the Text.FeaturizeText transform to convert text into numeric vectors, then feed them into a trainer like BinaryClassification.Trainers.SdcaLogisticRegression.
What is the difference between binary and multiclass classification?
Binary classification predicts one of two labels (e.g., true/false), while multiclass predicts one of many (e.g., categories). Use context.MulticlassClassification for the latter.
Can I export the model to ONNX?
Yes, ML.NET supports ONNX export via context.Model.ConvertToOnnx in the latest versions. This allows deployment to other platforms.
How do I use a pre-trained model like BERT?
ML.NET can load ONNX models; you can download a pre-trained BERT model in ONNX format and use it with the Transforms.Onnx transform.
Is ML.NET free to use?
Yes, ML.NET is open-source and free, part of the .NET Foundation.