Monday 12 February 2024

ML.NET model training and prediction separately

 In ML.NET, we can train and predict using models in separate steps. ML.NET provides a modular approach to machine learning, allowing you to train a model using training data and then use the trained model to make predictions on new data.

1. Model Training:

First, you need to create a machine-learning pipeline to define your model and its training process. This typically involves loading and transforming your training data, choosing an algorithm, training the model, and saving the trained model to a file. Here's an example using a simple scenario:

TrainData.csproj .net console application

    public class HouseData
        public float Size { get; set; }
        public float Price { get; set; }

    public class HousePricePrediction
        public float Price { get; set; }

// See for more information
using Microsoft.ML;
using System.Data;
using TrainData.Models;

MLContext mlContext = new MLContext();

// 1. Import or create training data
HouseData[] houseData = {
               new HouseData() { Size = 1.1F, Price = 11.1F },
               new HouseData() { Size = 2.2F, Price = 22.2F },
               new HouseData() { Size = 3.3F, Price = 33.3F },
               new HouseData() { Size = 4.4F, Price = 44.4F } };
IDataView trainingData = mlContext.Data.LoadFromEnumerable(houseData);

// 2. Specify data preparation and model training pipeline
var pipeline = mlContext.Transforms.Concatenate("Features", new[] { "Size" })
    .Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "Price", maximumNumberOfIterations: 100));

// 3. Train model
var model = pipeline.Fit(trainingData);

// 4. Save model
mlContext.Model.Save(model, trainingData.Schema, "");

2. Model Prediction: 

Now that you have a trained model saved to a file, you can load the model and use it to make predictions on new data:

PredictionApi.csproj .net webapi


    using Microsoft.Extensions.ML;
using TrainData.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// Learn more about configuring Swagger/OpenAPI at


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())






using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.ML;
using TrainData.Models;

namespace PredictionApi.Controllers
    public class FlatController : ControllerBase

        private readonly ILogger _logger;
        public PredictionEnginePool _predictionEnginePool { get; }

        public FlatController(ILogger logger, PredictionEnginePool predictionEnginePool)
            _logger = logger;
            _predictionEnginePool = predictionEnginePool;

        public string Get(float size)

            var houseData = new HouseData { Size =size};
            var prediction = _predictionEnginePool.Predict(houseData);
            string sentiment = $"{prediction.Price}";

            return sentiment;