#r "nuget: Microsoft.ML,5.0.0"
#r "nuget: pythonnet,3.1.0"
#load "../../../Config/PythonNetLoader.cs"
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Trainers;
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Text;
using System.Text.Json;
using Microsoft.DotNet.Interactive.Formatting;
using Python.Runtime;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
record MlFigure(string Markup);
Formatter.Register<MlFigure>((figure, writer) => writer.Write(figure.Markup), "image/svg+xml");
Formatter.SetPreferredMimeTypesFor(typeof(MlFigure), "image/svg+xml");
static void RequireMl(bool condition, string explanation)
{
if (!condition)
throw new InvalidOperationException(explanation);
}
// Le quantile linéaire NumPy correspond à une interpolation entre deux statistiques d'ordre.
static double QuantileMl(IEnumerable<double> values, double probability)
{
var sorted = values.Order().ToArray();
double index = probability * (sorted.Length - 1);
int lower = (int)Math.Floor(index);
int upper = Math.Min(lower + 1, sorted.Length - 1);
return sorted[lower] + (index - lower) * (sorted[upper] - sorted[lower]);
}
// Le dénominateur n convient aux tirages qui constituent la distribution représentée.
static double StdMl(IReadOnlyCollection<double> values)
{
double mean = values.Average();
return Math.Sqrt(values.Sum(value => Math.Pow(value - mean, 2)) / values.Count);
}
// Le petit contrat JSON ne transfère que les données et résultats des appels ciblés aux estimateurs.
static T InferenceMl<T>(string program, object request)
{
using var gil = Py.GIL();
using var scope = Py.CreateScope();
using var data = new PyString(JsonSerializer.Serialize(request));
scope.Set("request_json", data);
scope.Exec(program);
return JsonSerializer.Deserialize<T>(scope.Get<string>("response_json")) ?? throw new InvalidOperationException("Le moteur n’a pas renvoyé de résultat.");
}
static string PyVersionMl(string package)
{
using var gil = Py.GIL();
using var module = Py.Import(package);
using var version = module.GetAttr("__version__");
return version.As<string>();
}
record MlSeries(string Name, string Color, double[] X, double[] Y, bool Scatter = false);
static void PlotMl(string title, string xLabel, string yLabel, params MlSeries[] series)
{
// Les limites suivent les données plutôt que les résultats d'un run de référence.
const int left = 82, top = 52, width = 660, height = 240;
double xMin = series.SelectMany(s => s.X).Min(), xMax = series.SelectMany(s => s.X).Max();
double yMin = series.SelectMany(s => s.Y).Min(), yMax = series.SelectMany(s => s.Y).Max();
if (xMin == xMax)
xMax += 1;
if (yMin == yMax)
yMax += 1;
static string F(double v) => v.ToString("G5", CultureInfo.InvariantCulture);
static string E(string v) => SecurityElement.Escape(v)!;
double X(double v) => left + width * (v - xMin) / (xMax - xMin);
double Y(double v) => top + height * (yMax - v) / (yMax - yMin);
var svg = new StringBuilder();
svg.Append($"<svg xmlns='http://www.w3.org/2000/svg' role='img' aria-label='{E(title)}' viewBox='0 0 790 410' width='790'><rect width='100%' height='100%' fill='white'/>");
svg.Append($"<g font-family='system-ui,sans-serif' fill='#172742' font-size='13'><text x='{left}' y='28' font-size='17' font-weight='bold'>{E(title)}</text>");
for (int tick = 0; tick <= 5; tick++)
{
double part = tick / 5.0, zx = left + width * part, zy = top + height * (1 - part);
svg.Append($"<path d='M{left} {F(zy)}H{left + width}' stroke='#d9e1e8'/><text x='{left - 8}' y='{F(zy + 4)}' text-anchor='end'>{F(yMin + part * (yMax - yMin))}</text>");
svg.Append($"<text x='{F(zx)}' y='{top + height + 20}' text-anchor='middle'>{F(xMin + part * (xMax - xMin))}</text>");
}
svg.Append($"<path d='M{left} {top}V{top + height}H{left + width}' stroke='#526479' fill='none'/><text x='{left + width / 2}' y='340' text-anchor='middle'>{E(xLabel)}</text><text x='22' y='175' transform='rotate(-90 22 175)' text-anchor='middle'>{E(yLabel)}</text>");
for (int i = 0; i < series.Length; i++)
{
var s = series[i];
// Conserver les points individuels pour matérialiser des observations, des mesures ou des valeurs par groupe.
var points = s.X.Zip(s.Y, (x, y) => (X: X(x), Y: Y(y))).ToArray();
if (!s.Scatter)
{
string path = string.Join(" ", points.Select(p => $"{F(p.X)},{F(p.Y)}"));
svg.Append($"<polyline points='{path}' fill='none' stroke='{s.Color}' stroke-width='2.4'/>");
}
else
{
foreach (var point in points)
svg.Append($"<circle cx='{F(point.X)}' cy='{F(point.Y)}' r='3.2' fill='{s.Color}'/>");
}
int keyX = left + i % 2 * 320, keyY = 365 + i / 2 * 20;
svg.Append($"<rect x='{keyX}' y='{keyY - 9}' width='18' height='8' fill='{s.Color}'/><text x='{keyX + 25}' y='{keyY}'>{E(s.Name)}</text>");
}
svg.Append("</g></svg>");
display(new MlFigure(svg.ToString()));
}
record MlData(double[][] X, int[] Y)
{
// Les sous-ensembles sont construits en C# à partir d'indices, jamais par duplication de lignes.
public MlData Select(int[] ids) => new(ids.Select(i => X[i]).ToArray(), ids.Select(i => Y[i]).ToArray());
}
record MlSplit(int[] Train, int[] Test);
record FitScores(int[] Prediction, double[] Probability, int[] TrainPrediction);
record ModelConfig(string Family, int Seed = 42, int Trees = 100, int? Depth = null, int MinimumLeaf = 1);
const string sklearnSplits = """
import json
import numpy as np
from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, TimeSeriesSplit
a = json.loads(request_json)
y = np.asarray(a["Labels"])
indexes = np.arange(y.size)
if a["Kind"] == "holdout":
train, test = train_test_split(indexes, test_size=0.30, random_state=42, stratify=y)
folds = [(train, test)]
elif a["Kind"] == "ordered":
folds = TimeSeriesSplit(n_splits=a["Count"]).split(indexes)
else:
S = StratifiedKFold if a["Kind"] == "stratified" else KFold
random_state = 0 if a["Shuffle"] else None
folds = S(n_splits=a["Count"], shuffle=a["Shuffle"], random_state=random_state).split(indexes, y)
response_json = json.dumps([{"Train": tr.tolist(), "Test": te.tolist()} for tr, te in folds])
""";
static MlSplit[] GetSplits(int[] labels, string kind, int count = 5, bool shuffle = false)
{
var folds = InferenceMl<MlSplit[]>(sklearnSplits, new { Labels = labels, Kind = kind, Count = count, Shuffle = shuffle });
// Disjonction stricte, couverture et ordre causal sont des propriétés du protocole.
foreach (var fold in folds)
RequireMl(!fold.Train.Intersect(fold.Test).Any() && (kind != "ordered" || fold.Train.Max() < fold.Test.Min()), "Fuite entre entraînement et test.");
if (kind != "holdout" && kind != "ordered")
RequireMl(folds.SelectMany(f => f.Test).Order().SequenceEqual(Enumerable.Range(0, labels.Length)), "Chaque ligne doit entrer dans un seul pli de test.");
return folds;
}
const string sklearnFit = """
import json
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
a = json.loads(request_json)
c = a["Config"]
if c["Family"] == "forest":
model = RandomForestClassifier(n_estimators=c["Trees"], max_depth=c["Depth"],
min_samples_leaf=c["MinimumLeaf"], random_state=c["Seed"], n_jobs=1)
elif c["Family"] == "tree":
model = DecisionTreeClassifier(random_state=c["Seed"])
else:
raise ValueError("Famille d'estimateur appelée inconnue")
x = np.asarray(a["Train"]["X"])
test_x = np.asarray(a["Test"]["X"])
model.fit(x, a["Train"]["Y"], sample_weight=a["Weights"])
positive_col = int(np.where(model.classes_ == 1)[0][0])
response_json = json.dumps({"Prediction": model.predict(test_x).tolist(),
"Probability": model.predict_proba(test_x)[:, positive_col].tolist(),
"TrainPrediction": model.predict(x).tolist()})
""";
static FitScores FitTreeModel(ModelConfig config, MlData train, MlData test, double[]? weights = null)
{
return InferenceMl<FitScores>(sklearnFit, new { Config = config, Train = train, Test = test, Weights = weights });
}
static double Accuracy(int[] expected, int[] predicted)
{
RequireMl(expected.Length == predicted.Length && expected.Length > 0, "Étiquettes et prédictions doivent être appariées.");
return expected.Zip(predicted, (y, p) => y == p ? 1.0 : 0.0).Average();
}
static int[, ] Confusion(int[] labels, int[] prediction)
{
// On garde les observations en lignes et les décisions en colonnes.
var counts = new int[2, 2];
for (int i = 0; i < labels.Length; i++)
counts[labels[i], prediction[i]]++;
RequireMl(counts.Cast<int>().Sum() == labels.Length, "Une prédiction doit contribuer à une seule case.");
return counts;
}
if (PythonNetLoader.Initialize(typeof(PythonEngine).Assembly, "sklearn")is not null)
PythonEngine.BeginAllowThreads();
Console.WriteLine($".NET {Environment.Version} | scikit-learn {PyVersionMl("sklearn")} | NumPy {PyVersionMl("numpy")}");
class LogisticRow
{
public bool Label { get; set; }
public float[] Features { get; set; } = [];
}
class LogisticScore
{
public bool PredictedLabel { get; set; }
public float Probability { get; set; }
}
static FitScores FitLogistic(MlData train, MlData test, int iterations)
{
var ml = new MLContext(seed: 42);
var schema = SchemaDefinition.Create(typeof(LogisticRow));
schema[nameof(LogisticRow.Features)].ColumnType = new VectorDataViewType(NumberDataViewType.Single, train.X[0].Length);
IDataView View(MlData data) => ml.Data.LoadFromEnumerable(data.X.Zip(data.Y, (x, y) => new LogisticRow { Features = x.Select(v => (float)v).ToArray(), Label = y == 1 }), schema);
var rows = View(train);
// La mise à l'échelle s'ajuste sur chaque train/pli, puis s'applique au test par le pipeline.
var estimator = ml.Transforms.NormalizeMeanVariance(nameof(LogisticRow.Features)).Append(ml.BinaryClassification.Trainers.LbfgsLogisticRegression(new LbfgsLogisticRegressionBinaryTrainer.Options { MaximumNumberOfIterations = iterations, L1Regularization = 0f, L2Regularization = 1f / train.Y.Length }));
var fitted = estimator.Fit(rows);
var holdout = ml.Data.CreateEnumerable<LogisticScore>(fitted.Transform(View(test)), reuseRowObject: false).ToArray();
var training = ml.Data.CreateEnumerable<LogisticScore>(fitted.Transform(rows), reuseRowObject: false).ToArray();
return new FitScores(holdout.Select(p => p.PredictedLabel ? 1 : 0).ToArray(), holdout.Select(p => (double)p.Probability).ToArray(), training.Select(p => p.PredictedLabel ? 1 : 0).ToArray());
}
static FitScores FitComparison(ModelConfig model, MlData train, MlData test, int iterations = 1000)
{
return model.Family == "logistic" ? FitLogistic(train, test, iterations) : FitTreeModel(model, train, test);
}
static double[] ScoreFolds(ModelConfig config, MlData data, MlSplit[] folds, int iterations = 1000)
{
// Chaque pli réajuste l'estimateur et ses transformations en isolation.
return folds.Select(fold =>
{
var test = data.Select(fold.Test);
return Accuracy(test.Y, FitComparison(config, data.Select(fold.Train), test, iterations).Prediction);
}).ToArray();
}
static void ShowScores(string label, double[] scores)
{
Console.WriteLine($"{label, -22} {string.Join(" / ", scores.Select(s => s.ToString("F3")))} | moyenne {scores.Average():F3} | écart-type {StdMl(scores):F3}");
}