diff --git a/docs-en/Libraries/MediatR/ML.md b/docs-en/Libraries/MediatR/ML.md index 430727f..d966aa5 100644 --- a/docs-en/Libraries/MediatR/ML.md +++ b/docs-en/Libraries/MediatR/ML.md @@ -104,12 +104,23 @@ public class ImageAnalysisController : ControllerBase prediction.FileName, prediction.PredictedLabel, prediction.PredictedScore, - Confidence = $"{prediction.PredictedScore:P2}" + Confidence = $"{prediction.PredictedScore:P2}", + prediction.Scores, // label -> score, for every label of the model + Model = prediction.ModelInfo?.Name, + ModelVersion = prediction.ModelInfo?.Version }); } } ``` +Besides the winning label, the prediction carries the score of every label (`Scores`) and the description of the model that produced it (`ModelInfo`: name, checksum, version, labels) - enough to store with a file which model judged it and how. + +- **Both belong to the model that made the prediction.** The labels are the ones the loaded model names its scores with. The file at `ImageClassification:ModelFilePath` is described once for every loaded model, when that model is first used. When the file is replaced and the pool does not reload it (`watchForChanges: false`), predictions keep the labels and the description of the model that still makes them. +- **`Scores` is `null`** when the model does not name its scores or the names do not match them one to one. +- **`ModelInfo` is `null`** when `ImageClassification:ModelFilePath` is not configured or the file cannot be read, when the pool replaced the model while the prediction ran, and with your own `IPredictionEnginePoolAdapter`, because the model behind it cannot be told apart from the file. The pool decides where the model is loaded from, so a prediction never depends on that file. +- **`GetModelInfo()`** describes the file as it is now. Its labels come from the `Labels.txt` entry that training writes; a file saved without it (one not trained with this library) gets the labels of the loaded model. +- **The checksum** of the model file is computed once and again only when the file's size or write time changes, so describing the model does not slow predictions down. + ### Model training ```csharp @@ -139,7 +150,7 @@ Training reads the files with the extension `.jpg` or `.png` from the source dir | `IImageClassificationService` | Interface | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interface | Abstraction over the ML.NET `PredictionEnginePool` | | `ModelInfo` | Class | Model metadata: name, checksum, version, labels | -| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` and `ModelInfo` are not filled by `ClassifyImage` | +| `ImagePrediction` | Class | Prediction result: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (label -> score for every label; `null` when the model does not name its scores) and `ModelInfo` (the model that made the prediction; `null` when it cannot be described) | | `InMemoryImageData` | Class | Model input data: the image as `byte[]` | | `ImagePredictionScore` | Class | Raw model output: `Score` (per class), `PredictedLabel` | | `ImageClassificationOptions` | Class | Options bound from the `ImageClassification` section: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -207,6 +218,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — the predicted class // result.ImagePrediction.PredictedScore — confidence (0-1) +// result.ImagePrediction.Scores — label -> score for every label; null when the model does not name its scores +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels of the model that predicted; null when it cannot be described ``` ### Model training @@ -225,6 +238,9 @@ var result = await _mediator.Send(new TrainImageClassificationModel - The model must be a ZIP file (ML.NET format) - The `ImageClassification` configuration section is required — a missing section throws `InvalidOperationException` when the options are first used - The model version and labels are stored in the archive as separate `Version.txt` and `Labels.txt` entries +- Scores and ModelInfo of a prediction describe the model that made it, not the current content of the model file +- GetModelInfo() describes the file; without `Labels.txt` (a model not trained with this library) its labels come from the loaded model +- Check ImagePrediction.Scores and ImagePrediction.ModelInfo for null before using them - Training folder: each subfolder = one class, folder name = label - PredictionEnginePool is thread-safe — safe for concurrent use - PredictedScore ∈ [0,1] — the closer to 1, the higher the model's confidence diff --git a/docs/Libraries/MediatR/ML.md b/docs/Libraries/MediatR/ML.md index 3a632d0..3f13a33 100644 --- a/docs/Libraries/MediatR/ML.md +++ b/docs/Libraries/MediatR/ML.md @@ -104,12 +104,23 @@ public class ImageAnalysisController : ControllerBase prediction.FileName, prediction.PredictedLabel, prediction.PredictedScore, - Confidence = $"{prediction.PredictedScore:P2}" + Confidence = $"{prediction.PredictedScore:P2}", + prediction.Scores, // etykieta -> wynik, dla każdej etykiety modelu + Model = prediction.ModelInfo?.Name, + ModelVersion = prediction.ModelInfo?.Version }); } } ``` +Oprócz zwycięskiej etykiety predykcja zawiera wynik każdej etykiety (`Scores`) i opis modelu, który ją wydał (`ModelInfo`: nazwa, checksum, wersja, etykiety) - tyle, ile trzeba, żeby zapisać przy pliku, który model go ocenił i jak. + +- **Jedno i drugie należy do modelu, który wykonał predykcję.** Etykiety to te, którymi załadowany model nazywa swoje wyniki. Plik z `ImageClassification:ModelFilePath` jest opisywany raz dla każdego załadowanego modelu, przy jego pierwszym użyciu. Gdy plik zostanie podmieniony, a pula go nie przeładuje (`watchForChanges: false`), predykcje zachowują etykiety i opis modelu, który nadal je wykonuje. +- **`Scores` ma wartość `null`**, gdy model nie nazywa swoich wyników albo nazwy nie odpowiadają im jeden do jednego. +- **`ModelInfo` ma wartość `null`**, gdy `ImageClassification:ModelFilePath` nie jest ustawione albo pliku nie da się odczytać, gdy pula podmieniła model w trakcie predykcji oraz przy własnej implementacji `IPredictionEnginePoolAdapter`, bo modelu za nią nie da się odróżnić od pliku. O tym, skąd ładowany jest model, decyduje pula, więc predykcja nigdy nie zależy od tego pliku. +- **`GetModelInfo()`** opisuje plik w jego obecnym stanie. Etykiety bierze z wpisu `Labels.txt`, który zapisuje trening; plik zapisany bez niego (nietrenowany tą biblioteką) dostaje etykiety załadowanego modelu. +- **Checksum** pliku modelu jest liczony raz i ponownie dopiero wtedy, gdy zmieni się rozmiar albo czas zapisu pliku, więc opis modelu nie spowalnia predykcji. + ### Trening modelu ```csharp @@ -139,7 +150,7 @@ Trening czyta pliki z rozszerzeniem `.jpg` lub `.png` z katalogu źródłowego i | `IImageClassificationService` | Interfejs | `Predict(byte[], fileName)`, `Train(images, folder, dest)`, `GetModelInfo()` | | `IPredictionEnginePoolAdapter` | Interfejs | Abstrakcja nad ML.NET `PredictionEnginePool` | | `ModelInfo` | Klasa | Metadane modelu: nazwa, checksum, wersja, etykiety | -| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`; `Scores` i `ModelInfo` nie są wypełniane przez `ClassifyImage` | +| `ImagePrediction` | Klasa | Wynik predykcji: `PredictedLabel`, `PredictedScore`, `FileName`, `Scores` (etykieta -> wynik dla każdej etykiety; `null`, gdy model nie nazywa swoich wyników) i `ModelInfo` (model, który wykonał predykcję; `null`, gdy nie da się go opisać) | | `InMemoryImageData` | Klasa | Dane wejściowe do modelu: obraz jako `byte[]` | | `ImagePredictionScore` | Klasa | Surowy wynik modelu: `Score` (per klasa), `PredictedLabel` | | `ImageClassificationOptions` | Klasa | Opcje wiązane z sekcji `ImageClassification`: `ModelFilePath`, `TrainingRoot`, `ModelsRoot`, `MaxImageBytes` | @@ -207,6 +218,8 @@ var result = await _mediator.Send(new ClassifyImage }); // result.ImagePrediction.PredictedLabel — przewidywana klasa // result.ImagePrediction.PredictedScore — pewność (0-1) +// result.ImagePrediction.Scores — etykieta -> wynik dla każdej etykiety; null, gdy model nie nazywa swoich wyników +// result.ImagePrediction.ModelInfo — Name, Checksum, Version, Labels modelu, który wykonał predykcję; null, gdy nie da się go opisać ``` ### Trening modelu @@ -225,6 +238,9 @@ var result = await _mediator.Send(new TrainImageClassificationModel - Model musi być plikiem ZIP (ML.NET format) - Sekcja konfiguracji `ImageClassification` jest wymagana — jej brak powoduje `InvalidOperationException` przy pierwszym użyciu opcji - Wersja i etykiety modelu są zapisywane w archiwum jako osobne wpisy `Version.txt` i `Labels.txt` +- Scores i ModelInfo predykcji opisują model, który ją wykonał, a nie obecną zawartość pliku modelu +- GetModelInfo() opisuje plik; bez `Labels.txt` (model nietrenowany tą biblioteką) etykiety pochodzą z załadowanego modelu +- Przed użyciem sprawdź, czy ImagePrediction.Scores i ImagePrediction.ModelInfo nie mają wartości null - Folder treningowy: każdy podfolder = jedna klasa, nazwa folderu = etykieta - PredictionEnginePool jest thread-safe — bezpieczne współbieżne użycie - PredictedScore ∈ [0,1] — im bliżej 1, tym wyższe zaufanie modelu diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs index 7987546..346c82c 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ClassificationService.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using Microsoft.ML; using Microsoft.ML.Data; @@ -21,6 +23,11 @@ public class ImageClassificationService : IImageClassificationService private readonly IPredictionEnginePoolAdapter predictionEnginePool; private readonly IModelInfoService modelInfoService; + // The description of the model file, kept for as long as the loaded model it was read for lives. When the + // file is replaced and the pool does not reload it, predictions keep the description of the model that + // still makes them instead of taking on that of the new file. + private static readonly ConditionalWeakTable descriptions = new(); + /// /// Initializes a new instance of . /// @@ -36,13 +43,17 @@ public ImageClassificationService(IPredictionEnginePoolAdapter /// A object containing the model's name, checksum, version, and labels. + /// + /// The labels come from the Labels.txt entry of the model file and, for a model saved without that + /// entry, from the loaded model itself. + /// public ModelInfo GetModelInfo() { return new ModelInfo( modelInfoService.ModelFileName, modelInfoService.ModelChecksum, modelInfoService.ModelVersion, - modelInfoService.Labels + GetLabels() ); } @@ -51,29 +62,131 @@ public ModelInfo GetModelInfo() /// /// The raw byte content of the image to classify. /// The original file name of the image, used for identification in the result. - /// An containing the predicted label and score. + /// + /// An with the predicted label and its score, the score of every label + /// () and the description of the model (). + /// + /// + /// Both belong to the model that made the prediction, not to whatever the model file holds at that moment. + /// The labels are the ones the loaded model names its scores with, and the file is described once for every + /// loaded model, when that model is first used. + /// is when the model does not name its scores or + /// the names do not match the scores one to one. is + /// when ImageClassification:ModelFilePath is not configured, the file cannot be + /// read, the pool replaced the model while the prediction ran, or the adapter is not the one this library + /// registers, because the model behind another adapter cannot be told apart from the file. + /// public ImagePrediction Predict(byte[] image, string? fileName) { var imageData = new InMemoryImageData(image, null, fileName); - ImagePredictionScore prediction = predictionEnginePool.Predict(imageData); - // ModelInfo modelInfo = GetModelInfo(); + + ImagePredictionScore prediction; + string[] labels; + object? model = null; + if (predictionEnginePool is IModelBoundPredictionEngine modelBound) + { + var result = modelBound.PredictWithModel(imageData); + prediction = result.Prediction; + labels = result.Labels; + model = result.Model; + } + else + { + prediction = predictionEnginePool.Predict(imageData); + labels = predictionEnginePool.GetLabels() ?? Array.Empty(); + } + + var scores = prediction.Score ?? throw new InvalidOperationException("The model returned no scores."); ImagePrediction imagePrediction = new ImagePrediction() { - PredictedScore = (prediction.Score ?? throw new InvalidOperationException("The model returned no scores.")).Max(), + PredictedScore = scores.Max(), FileName = fileName, PredictedLabel = prediction.PredictedLabel, - //ModelInfo = modelInfo, - //Scores = modelInfo.Labels - // .Zip(prediction.Score, (key, value) => new { key, value }) - // .ToDictionary(x => x.key, x => x.value) - + ModelInfo = model == null ? null : DescribeModel(model, labels), + Scores = MapScores(labels, scores) } ; return imagePrediction; } + // The labels of the model file: its Labels.txt entry or, for a file saved without it, the labels of the + // model the pool has loaded. + private string[] GetLabels() + { + var labels = modelInfoService.Labels; + if (labels != null && labels.Length > 0) + { + return labels; + } + + return predictionEnginePool.GetLabels() ?? Array.Empty(); + } + + private ModelInfo? DescribeModel(object model, string[] labels) + { + var path = modelInfoService.ModelFilePath; + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + if (!descriptions.TryGetValue(model, out var description) || !string.Equals(description.Path, path, StringComparison.Ordinal)) + { + try + { + description = new ModelFileDescription(path, modelInfoService.ModelFileName, modelInfoService.ModelChecksum, modelInfoService.ModelVersion); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + + descriptions.AddOrUpdate(model, description); + } + + return new ModelInfo(description.Name, description.Checksum, description.Version, labels); + } + + private static Dictionary? MapScores(string[] labels, float[] scores) + { + if (labels.Length != scores.Length) + { + return null; + } + + var result = new Dictionary(labels.Length); + for (var i = 0; i < labels.Length; i++) + { + if (!result.TryAdd(labels[i], scores[i])) + { + return null; + } + } + + return result; + } + + private sealed class ModelFileDescription + { + public ModelFileDescription(string path, string? name, string checksum, string version) + { + Path = path; + Name = name; + Checksum = checksum; + Version = version; + } + + public string Path { get; } + + public string? Name { get; } + + public string Checksum { get; } + + public string Version { get; } + } + /// /// Trains an image classification model using the provided image dataset and saves it to disk. /// diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs new file mode 100644 index 0000000..117a8bc --- /dev/null +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelBoundPrediction.cs @@ -0,0 +1,42 @@ +namespace TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; + +/// +/// A prediction together with what ties it to the model that made it. +/// +/// The output prediction type produced by the engine. +internal readonly struct ModelBoundPrediction +{ + public ModelBoundPrediction(TPrediction prediction, string[] labels, object? model) + { + Prediction = prediction; + Labels = labels; + Model = model; + } + + /// The prediction. + public TPrediction Prediction { get; } + + /// + /// The labels of the engine that made the prediction, in the order of its scores; empty when the model + /// does not name its scores. + /// + public string[] Labels { get; } + + /// + /// The model the pool held before and after the prediction, used only as its identity; + /// when the pool replaced the model while the prediction ran. + /// + public object? Model { get; } +} + +/// +/// Implemented by the adapter this library registers: one call that predicts and reports which model did it, +/// so that labels and the model description are never taken from another model than the one that scored. +/// +/// The input data type for the prediction engine. +/// The output prediction type produced by the engine. +internal interface IModelBoundPredictionEngine +{ + /// Runs a prediction and returns it with the labels and the identity of the model that made it. + ModelBoundPrediction PredictWithModel(TData example); +} diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs index 72aa052..5093080 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/ModelHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.IO; using System.IO.Compression; using System.Linq; @@ -21,6 +22,11 @@ public class ModelHelper : IModelHelper /// The name of the labels entry stored inside the model zip archive. const string labelsFileName = "Labels.txt"; + // Checksums by full path. A model is described with every prediction, and hashing a model of about + // 100 MB each time would take longer than the prediction itself; the file is hashed again only when its + // size or write time changes. + private static readonly ConcurrentDictionary checksums = new(StringComparer.Ordinal); + /// /// Adds a timestamp-based version entry to the model zip archive. /// @@ -92,10 +98,20 @@ public void AddLabels(string modelFilePath, string[] labels) /// A lowercase hexadecimal string representing the MD5 hash of the file. public string GetChecksum(string modelFilePath) { + var file = new FileInfo(modelFilePath); + if (file.Exists + && checksums.TryGetValue(file.FullName, out var known) + && known.Length == file.Length + && known.LastWriteTimeUtc == file.LastWriteTimeUtc) + { + return known.Checksum; + } + using var md5 = MD5.Create(); using var stream = File.OpenRead(modelFilePath); - var checksum = md5.ComputeHash(stream); - return BitConverter.ToString(checksum).Replace("-", string.Empty).ToLower(); + var checksum = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLower(); + checksums[file.FullName] = (file.Length, file.LastWriteTimeUtc, checksum); + return checksum; } /// @@ -109,7 +125,7 @@ public string GetVersion(string modelFilePath) { try { - using FileStream fileStream = new FileStream(modelFilePath, FileMode.Open); + using FileStream fileStream = OpenForReading(modelFilePath); using ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Read); ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(versionFileName); if (zipArchiveEntry != null) @@ -136,7 +152,7 @@ public string[] GetLabels(string modelFilePath) { try { - using FileStream fileStream = new FileStream(modelFilePath, FileMode.Open); + using FileStream fileStream = OpenForReading(modelFilePath); using ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Read); ZipArchiveEntry? zipArchiveEntry = archive.GetEntry(labelsFileName); if (zipArchiveEntry != null) @@ -151,4 +167,11 @@ public string[] GetLabels(string modelFilePath) } return new string[0]; } + + // Read access only, shared with other readers: the default of FileMode.Open asks for write access too, so + // a read-only file could not be read and two requests reading at the same time locked each other out. + private static FileStream OpenForReading(string modelFilePath) + { + return new FileStream(modelFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); + } } diff --git a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs index 3f8739b..623bc20 100644 --- a/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs +++ b/src/TailoredApps.Shared.MediatR.ML/Infrastructure/PredictionEnginePoolAdapter.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using Microsoft.Extensions.ML; +using Microsoft.ML; using Microsoft.ML.Data; using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Infrastructure; @@ -13,7 +14,7 @@ namespace TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; /// /// The input data type for the prediction engine. /// The output prediction type produced by the engine. -public class PredictionEnginePoolAdapter : IPredictionEnginePoolAdapter +public class PredictionEnginePoolAdapter : IPredictionEnginePoolAdapter, IModelBoundPredictionEngine where TData : class where TPrediction : class, new() { @@ -32,12 +33,58 @@ public PredictionEnginePoolAdapter(PredictionEnginePool pred /// /// Retrieves the class label names from the prediction engine's output schema Score slot annotations. /// - /// An array of label name strings corresponding to the Score column slots. + /// + /// An array of label name strings corresponding to the Score column slots; empty when the model has no + /// Score column or its slots are not named. + /// public string[] GetLabels() { - var labelBuffer = new VBuffer>(); var predictionEngine = predictionEnginePool.GetPredictionEngine(); - predictionEngine.OutputSchema["Score"].Annotations.GetValue("SlotNames", ref labelBuffer); + try + { + return ReadLabels(predictionEngine.OutputSchema); + } + finally + { + // The engine is only borrowed: without this every call would leave the pool one engine short + // and make it build another. + predictionEnginePool.ReturnPredictionEngine(predictionEngine); + } + } + + /// + /// Runs a prediction and reports the labels of the engine that made it and the model the pool held meanwhile. + /// + ModelBoundPrediction IModelBoundPredictionEngine.PredictWithModel(TData example) + { + var modelBefore = predictionEnginePool.GetModel(); + var predictionEngine = predictionEnginePool.GetPredictionEngine(); + try + { + var prediction = predictionEngine.Predict(example); + var labels = ReadLabels(predictionEngine.OutputSchema); + var modelAfter = predictionEnginePool.GetModel(); + + // A pool that watches its file can replace the model at any moment. When it did so during this + // call, it is not known which of the two models the engine belonged to. + return new ModelBoundPrediction(prediction, labels, ReferenceEquals(modelBefore, modelAfter) ? modelBefore : null); + } + finally + { + predictionEnginePool.ReturnPredictionEngine(predictionEngine); + } + } + + private static string[] ReadLabels(DataViewSchema schema) + { + var score = schema.GetColumnOrNull("Score"); + if (score == null || score.Value.Annotations.Schema.GetColumnOrNull("SlotNames") == null) + { + return Array.Empty(); + } + + var labelBuffer = new VBuffer>(); + score.Value.Annotations.GetValue("SlotNames", ref labelBuffer); return labelBuffer.DenseValues().Select(l => l.ToString()).ToArray(); } diff --git a/src/TailoredApps.Shared.MediatR.ML/README.md b/src/TailoredApps.Shared.MediatR.ML/README.md index df15033..26376a6 100644 --- a/src/TailoredApps.Shared.MediatR.ML/README.md +++ b/src/TailoredApps.Shared.MediatR.ML/README.md @@ -41,6 +41,8 @@ using TailoredApps.Shared.MediatR.ImageClassification.Domain.DataModel.Message.C var classified = await mediator.Send(new ClassifyImage { FileByteArray = imageBytes, FileName = "photo.jpg" }); var label = classified.ImagePrediction?.PredictedLabel; var score = classified.ImagePrediction?.PredictedScore; +var scores = classified.ImagePrediction?.Scores; // label -> score, for every label of the model +var model = classified.ImagePrediction?.ModelInfo; // Name, Checksum, Version, Labels var trained = await mediator.Send(new TrainImageClassificationModel { @@ -76,8 +78,19 @@ The `ImageClassification` section: - The section is required: without it the options throw `InvalidOperationException` when first used. - `ClassifyImage` throws `ArgumentException` for empty content, for content over `MaxImageBytes` and for - content that does not start with a JPEG or PNG signature. Only `FileName`, `PredictedLabel` and - `PredictedScore` of the returned `ImagePrediction` are filled; `Scores` and `ModelInfo` stay `null`. + content that does not start with a JPEG or PNG signature. +- The returned `ImagePrediction` has `FileName`, `PredictedLabel` and `PredictedScore`, the score of every label + in `Scores` and the description of the model in `ModelInfo`. Both belong to the model that made the + prediction: the labels are the ones the loaded model names its scores with, and the file at `ModelFilePath` + is described once for every loaded model, when that model is first used. A file replaced without the pool + reloading it (`watchForChanges: false`) therefore does not change what a prediction reports. +- `Scores` is `null` when the model does not name its scores or the names do not match them one to one. + `ModelInfo` is `null` when `ModelFilePath` is not configured or cannot be read, when the pool replaced the + model while the prediction ran, and with your own `IPredictionEnginePoolAdapter` (the model behind it cannot + be told apart from the file). The prediction itself never depends on that file. +- `IImageClassificationService.GetModelInfo()` describes the file as it is now. Its labels come from the + `Labels.txt` entry; a file saved without it (not trained with this library) gets the labels of the loaded model. +- The checksum of a model file is computed once and again only when the file's size or write time changes. - Training paths are resolved against `TrainingRoot` and `ModelsRoot`. A path outside its root throws `ArgumentException`; a root that is not configured throws `InvalidOperationException`. - Training reads files with the extension `.jpg` or `.png` from `Source` and its sub-folders and uses the name diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs index fd05f2e..ed33094 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/ImageClassificationServiceTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Moq; using TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Domain.Models; @@ -21,7 +22,7 @@ public ImageClassificationServiceTests() } [Fact] - public void When_Predict_Is_Called_Should_Map_Prediction_To_ImagePrediction() + public void When_Model_Does_Not_Name_Its_Scores_Predict_Should_Leave_Scores_And_ModelInfo_Null() { // arrange var imageBytes = new byte[] { 1, 2, 3 }; @@ -44,6 +45,201 @@ public void When_Predict_Is_Called_Should_Map_Prediction_To_ImagePrediction() Assert.Null(prediction.ModelInfo); } + [Fact] + public void When_Adapter_Is_Not_The_One_The_Library_Registers_Predict_Should_Return_Scores_Without_Describing_The_File() + { + // arrange: the model behind a foreign adapter cannot be told apart from the file, so it is not described + SetupModelFile(new[] { "circle", "square", "triangle" }); + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(new[] { "blue", "green", "red" }); + SetupPrediction("blue", 0.6f, 0.3f, 0.1f); + + // act + var prediction = sut.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); + + // assert + Assert.NotNull(prediction.Scores); + Assert.Equal(0.6f, prediction.Scores["blue"]); + Assert.Equal(0.3f, prediction.Scores["green"]); + Assert.Equal(0.1f, prediction.Scores["red"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.Labels, Times.Never); + } + + [Fact] + public void When_Predict_Is_Called_Should_Return_Every_Score_And_The_Description_Of_The_Model_That_Made_It() + { + // arrange: the file's own Labels.txt says something else than the loaded model + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "circle", "square", "triangle" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // assert + Assert.Equal("green", prediction.PredictedLabel); + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.NotNull(prediction.Scores); + Assert.Equal(3, prediction.Scores.Count); + Assert.Equal(0.1f, prediction.Scores["blue"]); + Assert.Equal(0.7f, prediction.Scores["green"]); + Assert.Equal(0.2f, prediction.Scores["red"]); + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("image.zip", prediction.ModelInfo.Name); + Assert.Equal("abc123", prediction.ModelInfo.Checksum); + Assert.Equal("20260820.101010", prediction.ModelInfo.Version); + Assert.Equal(new[] { "blue", "green", "red" }, prediction.ModelInfo.Labels); + } + + [Fact] + public void When_Model_File_Is_Replaced_But_The_Loaded_Model_Stays_Predict_Should_Keep_Describing_The_Loaded_Model() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + + // act: another file takes the place of the model file; the pool still holds the model it loaded + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("replaced"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20270101.000000"); + modelInfoServiceMock.SetupGet(m => m.Labels).Returns(new[] { "red", "green", "blue" }); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); + + // assert + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("abc123", prediction.ModelInfo.Checksum); + Assert.Equal("20260820.101010", prediction.ModelInfo.Version); + Assert.Equal(0.1f, prediction.Scores["blue"]); + Assert.Equal(0.2f, prediction.Scores["red"]); + } + + [Fact] + public void When_Pool_Loads_Another_Model_Predict_Should_Describe_The_File_Again() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + + // act: the file changed and the pool reloaded it + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("replaced"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20270101.000000"); + loaded.Model = new object(); + loaded.Labels = new[] { "circle", "square", "triangle" }; + loaded.Returns("square", 0.2f, 0.5f, 0.3f); + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); + + // assert + Assert.NotNull(prediction.ModelInfo); + Assert.Equal("replaced", prediction.ModelInfo.Checksum); + Assert.Equal("20270101.000000", prediction.ModelInfo.Version); + Assert.Equal(new[] { "circle", "square", "triangle" }, prediction.ModelInfo.Labels); + Assert.Equal(0.5f, prediction.Scores["square"]); + } + + [Fact] + public void When_Pool_Replaces_The_Model_During_A_Prediction_Predict_Should_Not_Describe_Any_Model() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" }, Model = null }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testgreen.png"); + + // assert: the scores carry the labels of the engine that made them; the file is not attributed + Assert.NotNull(prediction.Scores); + Assert.Equal(0.7f, prediction.Scores["green"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + } + + [Fact] + public void When_Model_File_Is_Not_Configured_Predict_Should_Return_Scores_Without_Reading_The_File() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("blue", 0.6f, 0.3f, 0.1f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testblue.png"); + + // assert + Assert.NotNull(prediction.Scores); + Assert.Equal(0.6f, prediction.Scores["blue"]); + Assert.Null(prediction.ModelInfo); + modelInfoServiceMock.VerifyGet(m => m.ModelChecksum, Times.Never); + modelInfoServiceMock.VerifyGet(m => m.ModelVersion, Times.Never); + } + + [Fact] + public void When_Model_File_Cannot_Be_Read_Predict_Should_Still_Return_The_Prediction_And_Describe_The_Model_Once_It_Can() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green", "red" } }; + loaded.Returns("green", 0.1f, 0.7f, 0.2f); + SetupModelFile(new[] { "blue", "green", "red" }); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Throws(new FileNotFoundException("no model")); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var withoutFile = service.Predict(new byte[] { 1, 2, 3 }, "first.png"); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("abc123"); + var withFile = service.Predict(new byte[] { 1, 2, 3 }, "second.png"); + + // assert + Assert.Equal("green", withoutFile.PredictedLabel); + Assert.Equal(0.7f, withoutFile.PredictedScore); + Assert.NotNull(withoutFile.Scores); + Assert.Null(withoutFile.ModelInfo); + Assert.NotNull(withFile.ModelInfo); + Assert.Equal("abc123", withFile.ModelInfo.Checksum); + } + + [Fact] + public void When_Labels_Do_Not_Match_The_Scores_Predict_Should_Leave_Scores_Null() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "green" } }; + loaded.Returns("red", 0.1f, 0.2f, 0.7f); + SetupModelFile(new[] { "blue", "green" }); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + + // assert + Assert.Equal("red", prediction.PredictedLabel); + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.Null(prediction.Scores); + Assert.NotNull(prediction.ModelInfo); + } + + [Fact] + public void When_A_Label_Repeats_Predict_Should_Leave_Scores_Null() + { + // arrange + var loaded = new ModelBoundAdapter { Labels = new[] { "blue", "blue", "red" } }; + loaded.Returns("red", 0.1f, 0.2f, 0.7f); + var service = new ImageClassificationService(loaded, modelInfoServiceMock.Object); + + // act + var prediction = service.Predict(new byte[] { 1, 2, 3 }, "testred.png"); + + // assert + Assert.Equal(0.7f, prediction.PredictedScore); + Assert.Null(prediction.Scores); + } + [Fact] public void When_Predict_Is_Called_Should_Forward_Image_Bytes_And_FileName_To_Engine() { @@ -98,5 +294,67 @@ public void When_GetModelInfo_Is_Called_Should_Map_Values_From_Model_Info_Servic Assert.Equal("abc123", modelInfo.Checksum); Assert.Equal("20260820.101010", modelInfo.Version); Assert.Same(labels, modelInfo.Labels); + predictionEnginePoolMock.Verify(p => p.GetLabels(), Times.Never); + } + + [Fact] + public void When_Model_File_Has_No_Labels_GetModelInfo_Should_Take_Them_From_The_Loaded_Model() + { + // arrange + var labels = new[] { "blue", "green", "red" }; + SetupModelFile(Array.Empty()); + predictionEnginePoolMock.Setup(p => p.GetLabels()).Returns(labels); + + // act + var modelInfo = sut.GetModelInfo(); + + // assert + Assert.Equal("image.zip", modelInfo.Name); + Assert.Same(labels, modelInfo.Labels); + } + + private void SetupModelFile(string[] labels) + { + modelInfoServiceMock.SetupGet(m => m.ModelFilePath).Returns("models/image.zip"); + modelInfoServiceMock.SetupGet(m => m.ModelFileName).Returns("image.zip"); + modelInfoServiceMock.SetupGet(m => m.ModelChecksum).Returns("abc123"); + modelInfoServiceMock.SetupGet(m => m.ModelVersion).Returns("20260820.101010"); + modelInfoServiceMock.SetupGet(m => m.Labels).Returns(labels); + } + + private void SetupPrediction(string predictedLabel, params float[] scores) + { + predictionEnginePoolMock + .Setup(p => p.Predict(It.IsAny())) + .Returns(new ImagePredictionScore { PredictedLabel = predictedLabel, Score = scores }); + } + + /// + /// Stands in for the adapter the library registers: it reports which model made a prediction. + /// + private sealed class ModelBoundAdapter : + IPredictionEnginePoolAdapter, + IModelBoundPredictionEngine + { + private ImagePredictionScore prediction; + + /// The model the pool holds; null plays a pool that replaced it during the prediction. + public object Model { get; set; } = new object(); + + public string[] Labels { get; set; } = Array.Empty(); + + public void Returns(string predictedLabel, params float[] scores) + { + prediction = new ImagePredictionScore { PredictedLabel = predictedLabel, Score = scores }; + } + + public string[] GetLabels() => Labels; + + public ImagePredictionScore Predict(InMemoryImageData example) => prediction; + + public ModelBoundPrediction PredictWithModel(InMemoryImageData example) + { + return new ModelBoundPrediction(prediction, Labels, Model); + } } } diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs index 566c7e4..ec2cd70 100644 --- a/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/ModelHelperTests.cs @@ -48,6 +48,110 @@ public void When_GetChecksum_Is_Called_Should_Return_Lower_Case_Md5_Of_File_Cont Assert.Equal("5d41402abc4b2a76b9719d911017c592", checksum); } + [Fact] + public void When_File_Content_Changes_GetChecksum_Should_Return_The_New_Checksum() + { + // arrange + var path = Path.Combine(workFolder, "changing.bin"); + File.WriteAllText(path, "hello"); + var first = sut.GetChecksum(path); + + // act + File.WriteAllText(path, "hello world"); + var second = sut.GetChecksum(path); + + // assert + Assert.Equal("5d41402abc4b2a76b9719d911017c592", first); + Assert.Equal("5eb63bbbe01eeed093cb22bb8f5acdc3", second); + } + + [Fact] + public void When_File_Of_The_Same_Size_Is_Written_Later_GetChecksum_Should_Return_The_New_Checksum() + { + // arrange + var path = Path.Combine(workFolder, "same-size.bin"); + File.WriteAllText(path, "hello"); + File.SetLastWriteTimeUtc(path, new DateTime(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc)); + var first = sut.GetChecksum(path); + + // act + File.WriteAllText(path, "jello"); + File.SetLastWriteTimeUtc(path, new DateTime(2026, 1, 1, 10, 0, 1, DateTimeKind.Utc)); + var second = sut.GetChecksum(path); + + // assert + Assert.Equal("5d41402abc4b2a76b9719d911017c592", first); + Assert.NotEqual(first, second); + } + + [Fact] + public void When_File_Is_Unchanged_GetChecksum_Should_Return_The_Same_Checksum_From_Another_Instance() + { + // arrange + var path = Path.Combine(workFolder, "unchanged.bin"); + File.WriteAllText(path, "hello"); + var first = sut.GetChecksum(path); + + // act + var second = new ModelHelper().GetChecksum(path); + + // assert + Assert.Equal(first, second); + } + + [Fact] + public void When_File_Does_Not_Exist_GetChecksum_Should_Throw_FileNotFoundException() + { + // arrange + var path = Path.Combine(workFolder, "missing.bin"); + + // act & assert + Assert.Throws(() => sut.GetChecksum(path)); + } + + [Fact] + public void When_Archive_Is_Read_Only_Should_Still_Read_Version_And_Labels() + { + // arrange + var path = CreateEmptyZip(); + var version = sut.AddVersion(path); + sut.AddLabels(path, new[] { "red", "green" }); + File.SetAttributes(path, FileAttributes.ReadOnly); + + try + { + // act + var readVersion = sut.GetVersion(path); + var readLabels = sut.GetLabels(path); + + // assert + Assert.Equal(version, readVersion); + Assert.Equal(new[] { "red", "green" }, readLabels); + } + finally + { + File.SetAttributes(path, FileAttributes.Normal); + } + } + + [Fact] + public void When_Archive_Is_Being_Read_By_Another_Reader_Should_Still_Read_Version_And_Labels() + { + // arrange + var path = CreateEmptyZip(); + var version = sut.AddVersion(path); + sut.AddLabels(path, new[] { "red", "green" }); + using var otherReader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + + // act + var readVersion = sut.GetVersion(path); + var readLabels = sut.GetLabels(path); + + // assert + Assert.Equal(version, readVersion); + Assert.Equal(new[] { "red", "green" }, readLabels); + } + [Fact] public void When_AddVersion_Is_Called_Should_Return_Timestamp_Version_And_Store_It_In_Archive() { diff --git a/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs new file mode 100644 index 0000000..4dc097a --- /dev/null +++ b/tests/TailoredApps.Shared.MediatR.ML.Tests/PredictionEnginePoolAdapterTests.cs @@ -0,0 +1,236 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ML; +using Microsoft.Extensions.Options; +using Microsoft.ML; +using Microsoft.ML.Data; +using TailoredApps.Shared.MediatR.ImageClassification.Infrastructure; +using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Domain.Models; +using TailoredApps.Shared.MediatR.ImageClassification.Interfaces.Infrastructure; +using Xunit; + +namespace TailoredApps.Shared.MediatR.ML.Tests; + +/// +/// The adapter against real ML.NET models: small ones trained here on a handful of numbers, saved to a file +/// and loaded through the prediction engine pool the way an application loads its model. +/// +public class PredictionEnginePoolAdapterTests : IDisposable +{ + private readonly string workFolder; + + public PredictionEnginePoolAdapterTests() + { + workFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(workFolder); + } + + public void Dispose() + { + if (Directory.Exists(workFolder)) + { + Directory.Delete(workFolder, recursive: true); + } + } + + [Fact] + public void When_Model_Is_A_Classifier_GetLabels_Should_Return_Its_Labels_In_Score_Order() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = provider.GetRequiredService>(); + + // act + var labels = sut.GetLabels(); + var prediction = sut.Predict(new ColorSample { Red = 0.05f, Green = 0.1f, Blue = 0.95f }); + + // assert + Assert.Equal(new[] { "blue", "green", "red" }, labels); + Assert.Equal("blue", prediction.PredictedLabel); + Assert.Equal(labels.Length, prediction.Score.Length); + Assert.Equal("blue", labels[Array.IndexOf(prediction.Score, prediction.Score.Max())]); + } + + [Fact] + public void When_GetLabels_Is_Called_Many_Times_Should_Keep_Returning_The_Same_Labels() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = provider.GetRequiredService>(); + + // act + var all = Enumerable.Range(0, 50).Select(_ => sut.GetLabels()).ToList(); + + // assert + Assert.All(all, labels => Assert.Equal(new[] { "blue", "green", "red" }, labels)); + } + + [Fact] + public void When_Model_Scores_Are_Not_Named_GetLabels_Should_Return_Empty_Array() + { + // arrange + using var provider = BuildProvider(SaveRegression()); + var sut = provider.GetRequiredService>(); + + // act + var labels = sut.GetLabels(); + + // assert + Assert.Empty(labels); + } + + [Fact] + public void When_Predicting_With_The_Model_Should_Return_The_Labels_And_The_Model_Of_The_Engine() + { + // arrange + using var provider = BuildProvider(SaveClassifier()); + var sut = (IModelBoundPredictionEngine) + provider.GetRequiredService>(); + + // act + var first = sut.PredictWithModel(new ColorSample { Red = 0.95f, Green = 0.1f, Blue = 0.05f }); + var second = sut.PredictWithModel(new ColorSample { Red = 0.05f, Green = 0.9f, Blue = 0.1f }); + + // assert + Assert.Equal("red", first.Prediction.PredictedLabel); + Assert.Equal("green", second.Prediction.PredictedLabel); + Assert.Equal(new[] { "blue", "green", "red" }, first.Labels); + Assert.NotNull(first.Model); + Assert.Same(first.Model, second.Model); + } + + [Fact] + public void When_Model_File_Is_Replaced_Without_A_Reload_Prediction_Should_Keep_Labels_And_Description_Of_The_Loaded_Model() + { + // arrange: a model of colours is loaded once; the pool does not watch its file + var path = SaveFileNameClassifier("model.zip", "blue", "green", "red"); + var modelHelper = new ModelHelper(); + var loadedVersion = modelHelper.AddVersion(path); + var loadedChecksum = modelHelper.GetChecksum(path); + + var services = new ServiceCollection(); + services.AddPredictionEnginePool() + .FromFile(path, watchForChanges: false) + .AddAdapter(); + using var provider = services.BuildServiceProvider(); + var adapter = provider.GetRequiredService>(); + var options = Options.Create(new ImageClassificationOptions { ModelFilePath = path }); + var sut = new ImageClassificationService(adapter, new ModelInfoService(options, modelHelper)); + var before = sut.Predict(new byte[] { 1 }, "red-7.png"); + + // act: a model of shapes, with as many labels, takes the file's place + SaveFileNameClassifier("model.zip", "circle", "square", "triangle"); + modelHelper.AddLabels(path, new[] { "circle", "square", "triangle" }); + var after = sut.Predict(new byte[] { 1 }, "red-8.png"); + + // assert: the scores still belong to the colours, and so does the description + Assert.NotEqual(loadedChecksum, modelHelper.GetChecksum(path)); + Assert.Equal("red", before.PredictedLabel); + Assert.Equal("red", after.PredictedLabel); + Assert.Equal(new[] { "blue", "green", "red" }, after.Scores.Keys.ToArray()); + Assert.Equal(after.PredictedScore, after.Scores["red"]); + Assert.Equal(loadedChecksum, before.ModelInfo.Checksum); + Assert.Equal(loadedChecksum, after.ModelInfo.Checksum); + Assert.Equal(loadedVersion, after.ModelInfo.Version); + Assert.Equal(new[] { "blue", "green", "red" }, after.ModelInfo.Labels); + } + + private ServiceProvider BuildProvider(string modelPath) where TPrediction : class, new() + { + var services = new ServiceCollection(); + services.AddPredictionEnginePool() + .FromFile(modelPath, watchForChanges: false) + .AddAdapter(); + return services.BuildServiceProvider(); + } + + private string SaveClassifier() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms.Conversion + .MapValueToKey("LabelAsKey", nameof(ColorSample.Label), keyOrdinality: Microsoft.ML.Transforms.ValueToKeyMappingEstimator.KeyOrdinality.ByValue) + .Append(mlContext.Transforms.Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue))) + .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelAsKey", "Features")) + .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "classifier.zip"); + } + + private string SaveRegression() + { + var mlContext = new MLContext(seed: 1); + var data = mlContext.Data.LoadFromEnumerable(Samples()); + var pipeline = mlContext.Transforms + .Concatenate("Features", nameof(ColorSample.Red), nameof(ColorSample.Green), nameof(ColorSample.Blue)) + .Append(mlContext.Regression.Trainers.Sdca(nameof(ColorSample.Brightness), "Features")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, "regression.zip"); + } + + // A classifier over the input type of the library, small enough to train in a test: it tells the label + // from the file name and ignores the image bytes. + private string SaveFileNameClassifier(string fileName, params string[] labels) + { + var mlContext = new MLContext(seed: 1); + var samples = labels + .SelectMany(label => Enumerable.Range(0, 30).Select(i => new InMemoryImageData(new byte[] { 1 }, label, $"{label}-{i}.png"))) + .ToArray(); + var data = mlContext.Data.LoadFromEnumerable(samples); + var pipeline = mlContext.Transforms.Conversion + .MapValueToKey("LabelAsKey", nameof(InMemoryImageData.Label), keyOrdinality: Microsoft.ML.Transforms.ValueToKeyMappingEstimator.KeyOrdinality.ByValue) + .Append(mlContext.Transforms.Text.FeaturizeText("Features", nameof(InMemoryImageData.FileName))) + .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("LabelAsKey", "Features")) + .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel", "PredictedLabel")); + + return Save(mlContext, pipeline.Fit(data), data.Schema, fileName); + } + + private string Save(MLContext mlContext, ITransformer model, DataViewSchema schema, string fileName) + { + var path = Path.Combine(workFolder, fileName); + mlContext.Model.Save(model, schema, path); + return path; + } + + private static ColorSample[] Samples() + { + var random = new Random(1); + float High() => 0.8f + (float)random.NextDouble() * 0.2f; + float Low() => (float)random.NextDouble() * 0.2f; + + return Enumerable.Range(0, 40).SelectMany(_ => new[] + { + new ColorSample { Red = High(), Green = Low(), Blue = Low(), Label = "red", Brightness = 0.3f }, + new ColorSample { Red = Low(), Green = High(), Blue = Low(), Label = "green", Brightness = 0.6f }, + new ColorSample { Red = Low(), Green = Low(), Blue = High(), Label = "blue", Brightness = 0.1f }, + }).ToArray(); + } + + public class ColorSample + { + public float Red { get; set; } + + public float Green { get; set; } + + public float Blue { get; set; } + + public string Label { get; set; } + + public float Brightness { get; set; } + } + + public class ColorPrediction + { + public string PredictedLabel { get; set; } + + public float[] Score { get; set; } + } + + public class BrightnessPrediction + { + public float Score { get; set; } + } +}