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 { [ColumnName("Score")] public float Price { get; set; } }
// See https://aka.ms/new-console-template 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, "model.zip"); Console.WriteLine(mlContext);
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
//Program.cs using Microsoft.Extensions.ML; using TrainData.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddPredictionEnginePool() .FromFile("H:\\Work\\RND\\ML\\MLSplit\\TrainData\\bin\\Debug\\net7.0\\model.zip"); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); //FlatController.cs using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.ML; using TrainData.Models; namespace PredictionApi.Controllers { [ApiController] [Route("[controller]")] public class FlatController : ControllerBase { private readonly ILogger _logger; public PredictionEnginePool _predictionEnginePool { get; } public FlatController(ILogger logger, PredictionEnginePool predictionEnginePool) { _logger = logger; _predictionEnginePool = predictionEnginePool; } [HttpGet("{size}:float")] public string Get(float size) { var houseData = new HouseData { Size =size}; var prediction = _predictionEnginePool.Predict(houseData); string sentiment = $"{prediction.Price}"; return sentiment; } } }