Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

ML.NET Model Training: Step-by-Step Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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, run dotnet new console -n MLNetDemo in the terminal.

  2. 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 for Microsoft.ML and install the latest stable version. This package includes the core ML.NET APIs.

  3. Prepare your data

    Create a folder named Data in 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).

  4. 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 Label property uses bool for binary classification. For regression, use float.

  5. Load the data into an IDataView

    In the Main method, create an MLContext and 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.

  6. Split the data into training and test sets

    Use the TrainTestSplit method 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.

  7. 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.Sdca instead.

  8. Train the model

    Call the Fit method on the pipeline with the training data:

    ITransformer model = pipeline.Fit(trainData);

    This executes the training algorithm and returns a trained model (transformer).

  9. 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.Evaluate and check metrics like RootMeanSquaredError.

  10. 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.

  11. 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 bool for binary classification or float for 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 OneHotEncoding or 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 NormalizeMinMax transform to the pipeline to scale features.
  • Use cross-validation – For small datasets, use context.BinaryClassification.CrossValidate to get more reliable metrics.
  • Log the pipeline – Set context.Log to 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 MaximumNumberOfIterations parameter 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.