In ML.NET, after training a machine learning model using a pipeline defined in a mbconfig file, you can evaluate the model's performance using specific metrics. Here's a step-by-step guide on how you can achieve this in C#:
-
Load the Model and Create the Evaluation Set:
Start by loading your trained model. You'll also need a dataset (often split from your original data as a test set) that contains both features and labels to evaluate your model.
-
Create an ML.NET Context:
Establish an ML.NET context which is necessary for operations like model evaluation.
-
Transform the Evaluation Data:
Apply the same transformations to your test data that you used on your training data to ensure consistency in feature engineering.
-
Evaluate the Model:
Use the relevant ML.NET Evaluate method, which computes evaluation metrics.
Here's a code example illustrating these steps:
using Microsoft.ML;
using Microsoft.ML.Data;
using MyMLApp.DataModels; // Make sure to replace with your actual data model namespace
// Step 1: Create an MLContext
var mlContext = new MLContext();
// Step 2: Load the trained model
ITransformer trainedModel;
using (var stream = new FileStream("path/to/your/model.zip", FileMode.Open, FileAccess.Read))
{
trainedModel = mlContext.Model.Load(stream, out var modelInputSchema);
}
// Step 3: Prepare your data
// Load your test data into IDataView
IDataView testData = mlContext.Data.LoadFromTextFile<YourDataModel>(
path: "path/to/your/testdata.csv",
hasHeader: true,
separatorChar: ',');
// Step 4: Evaluate the model
var testMetrics = mlContext.MulticlassClassification.Evaluate(trainedModel.Transform(testData));
Console.WriteLine($"Log-loss: {testMetrics.LogLoss}");
Console.WriteLine("Per class Log-loss:");
for (int i = 0; i < testMetrics.PerClassLogLoss.Count; i++)
{
Console.WriteLine($" {testMetrics.PerClassLogLoss[i]:F4}");
}
Important Points:
-
Model and Data Loading: Adjust file paths for your model and test data files.
-
YourDataModel: Replace YourDataModel with your defined data class that matches the schema of your data files.
-
Metrics Method: The example shows evaluation for a multiclass classification model. If you're dealing with binary classification, regression, or another task, make sure to use the appropriate Evaluate method such as BinaryClassification.Evaluate, Regression.Evaluate, or others.
-
Log-loss and Other Metrics: The example demonstrates retrieving log-loss, a common metric for classification models. Depending on your model type and evaluation method used, you can access other metrics such as accuracy, F1 score, AUC, RMSE, etc.
Adjust and expand this example to suit the specific needs of your model and dataset.