Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions docs-en/Libraries/MediatR/ML.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<TData, TPred>` | 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` |
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
20 changes: 18 additions & 2 deletions docs/Libraries/MediatR/ML.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<TData, TPred>` | 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` |
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,6 +23,11 @@ public class ImageClassificationService : IImageClassificationService
private readonly IPredictionEnginePoolAdapter<InMemoryImageData, ImagePredictionScore> 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<object, ModelFileDescription> descriptions = new();

/// <summary>
/// Initializes a new instance of <see cref="ImageClassificationService"/>.
/// </summary>
Expand All @@ -36,13 +43,17 @@ public ImageClassificationService(IPredictionEnginePoolAdapter<InMemoryImageData
/// Retrieves metadata about the currently loaded ML model.
/// </summary>
/// <returns>A <see cref="ModelInfo"/> object containing the model's name, checksum, version, and labels.</returns>
/// <remarks>
/// The labels come from the <c>Labels.txt</c> entry of the model file and, for a model saved without that
/// entry, from the loaded model itself.
/// </remarks>
public ModelInfo GetModelInfo()
{
return new ModelInfo(
modelInfoService.ModelFileName,
modelInfoService.ModelChecksum,
modelInfoService.ModelVersion,
modelInfoService.Labels
GetLabels()
);
}

Expand All @@ -51,29 +62,131 @@ public ModelInfo GetModelInfo()
/// </summary>
/// <param name="image">The raw byte content of the image to classify.</param>
/// <param name="fileName">The original file name of the image, used for identification in the result.</param>
/// <returns>An <see cref="ImagePrediction"/> containing the predicted label and score.</returns>
/// <returns>
/// An <see cref="ImagePrediction"/> with the predicted label and its score, the score of every label
/// (<see cref="ImagePrediction.Scores"/>) and the description of the model (<see cref="ImagePrediction.ModelInfo"/>).
/// </returns>
/// <remarks>
/// 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.
/// <see cref="ImagePrediction.Scores"/> is <see langword="null"/> when the model does not name its scores or
/// the names do not match the scores one to one. <see cref="ImagePrediction.ModelInfo"/> is
/// <see langword="null"/> when <c>ImageClassification:ModelFilePath</c> 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.
/// </remarks>
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<InMemoryImageData, ImagePredictionScore> 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<string>();
}

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<string>();
}

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<string, float>? MapScores(string[] labels, float[] scores)
{
if (labels.Length != scores.Length)
{
return null;
}

var result = new Dictionary<string, float>(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; }
}

/// <summary>
/// Trains an image classification model using the provided image dataset and saves it to disk.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace TailoredApps.Shared.MediatR.ImageClassification.Infrastructure;

/// <summary>
/// A prediction together with what ties it to the model that made it.
/// </summary>
/// <typeparam name="TPrediction">The output prediction type produced by the engine.</typeparam>
internal readonly struct ModelBoundPrediction<TPrediction>
{
public ModelBoundPrediction(TPrediction prediction, string[] labels, object? model)
{
Prediction = prediction;
Labels = labels;
Model = model;
}

/// <summary>The prediction.</summary>
public TPrediction Prediction { get; }

/// <summary>
/// The labels of the engine that made the prediction, in the order of its scores; empty when the model
/// does not name its scores.
/// </summary>
public string[] Labels { get; }

/// <summary>
/// The model the pool held before and after the prediction, used only as its identity;
/// <see langword="null"/> when the pool replaced the model while the prediction ran.
/// </summary>
public object? Model { get; }
}

/// <summary>
/// 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.
/// </summary>
/// <typeparam name="TData">The input data type for the prediction engine.</typeparam>
/// <typeparam name="TPrediction">The output prediction type produced by the engine.</typeparam>
internal interface IModelBoundPredictionEngine<in TData, TPrediction>
{
/// <summary>Runs a prediction and returns it with the labels and the identity of the model that made it.</summary>
ModelBoundPrediction<TPrediction> PredictWithModel(TData example);
}
Loading