#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
// --- la foret aleatoire -----------------------------------------------------------
public sealed class ForestOptions
{
public int NTrees { get; set; } = 100;
/// <summary>Profondeur maximale ; int.MaxValue signifie « aucune limite ».</summary>
public int MaxDepth { get; set; } = int.MaxValue;
public int MinLeaf { get; set; } = 1;
public int Seed { get; set; } = 0;
/// <summary>Descripteurs examines par coupure ; 0 = racine carree du nombre total.</summary>
public int Mtry { get; set; } = 0;
public ForestOptions Clone() => new ForestOptions
{
NTrees = NTrees, MaxDepth = MaxDepth, MinLeaf = MinLeaf, Seed = Seed, Mtry = Mtry,
};
}
public sealed class TreeNode
{
public int Feature = -1;
public double Threshold;
public TreeNode? Left;
public TreeNode? Right;
/// <summary>Proportion de classe 1 dans la feuille — ou dans le noeud si celui-ci est terminal.</summary>
public double Probability;
}
public sealed class RandomForest
{
private readonly List<TreeNode> _trees = new();
public int NFeatures { get; }
public double[] Importances { get; }
public RandomForest(double[][] X, int[] y, ForestOptions options)
{
if (X.Length != y.Length) throw new ArgumentException("X et y de longueurs differentes");
NFeatures = X[0].Length;
Importances = new double[NFeatures];
int n = X.Length;
int mtry = options.Mtry > 0 ? options.Mtry : Math.Max(1, (int)Math.Sqrt(NFeatures));
var rng = new Rng(options.Seed);
for (int t = 0; t < options.NTrees; t++)
{
var bootstrap = new int[n];
for (int i = 0; i < n; i++) bootstrap[i] = rng.NextInt(0, n);
_trees.Add(Build(bootstrap, X, y, options, mtry, 0, rng));
}
}
private TreeNode Build(int[] idx, double[][] X, int[] y, ForestOptions options, int mtry, int depth, Rng rng)
{
int n = idx.Length;
int positives = 0;
foreach (int i in idx) positives += y[i];
double probability = n == 0 ? 0.0 : (double)positives / n;
// Un noeud pur n'a plus rien a separer ; une feuille trop petite serait du bruit.
if (depth >= options.MaxDepth || n < 2 * options.MinLeaf || positives == 0 || positives == n)
{
return new TreeNode { Probability = probability };
}
int p = X[0].Length;
var features = Enumerable.Range(0, p).ToArray();
for (int i = p - 1; i > 0; i--)
{
int j = rng.NextInt(0, i + 1);
(features[i], features[j]) = (features[j], features[i]);
}
int examined = Math.Min(mtry, p);
double parentImpurity = 2.0 * probability * (1.0 - probability);
double bestGain = 0.0;
int bestFeature = -1;
double bestThreshold = 0.0;
for (int fi = 0; fi < examined; fi++)
{
int f = features[fi];
// Candidats de coupure : seize quantiles des valeurs du noeud pour ce descripteur.
var values = idx.Select(i => X[i][f]).OrderBy(v => v).ToArray();
int nQuantiles = Math.Min(16, n - 1);
for (int q = 1; q <= nQuantiles; q++)
{
int at = (int)((long)q * n / (nQuantiles + 1));
double lo = values[at - 1], hi = values[at];
if (hi <= lo) continue;
double threshold = 0.5 * (lo + hi);
int nLeft = 0, posLeft = 0;
foreach (int i in idx)
{
if (X[i][f] <= threshold) { nLeft++; posLeft += y[i]; }
}
int nRight = n - nLeft;
int posRight = positives - posLeft;
if (nLeft < options.MinLeaf || nRight < options.MinLeaf) continue;
double pLeft = (double)posLeft / nLeft;
double pRight = (double)posRight / nRight;
double gain = parentImpurity
- ((double)nLeft / n) * 2.0 * pLeft * (1.0 - pLeft)
- ((double)nRight / n) * 2.0 * pRight * (1.0 - pRight);
if (gain > bestGain + 1e-12)
{
bestGain = gain;
bestFeature = f;
bestThreshold = threshold;
}
}
}
if (bestFeature < 0) return new TreeNode { Probability = probability };
Importances[bestFeature] += bestGain * n;
var left = idx.Where(i => X[i][bestFeature] <= bestThreshold).ToArray();
var right = idx.Where(i => X[i][bestFeature] > bestThreshold).ToArray();
return new TreeNode
{
Feature = bestFeature,
Threshold = bestThreshold,
Probability = probability,
Left = Build(left, X, y, options, mtry, depth + 1, rng),
Right = Build(right, X, y, options, mtry, depth + 1, rng),
};
}
public double PredictProbability(double[] x)
{
double sum = 0.0;
foreach (TreeNode tree in _trees) sum += LeafProbability(tree, x);
return sum / _trees.Count;
}
public int Predict(double[] x) => PredictProbability(x) >= 0.5 ? 1 : 0;
private static double LeafProbability(TreeNode node, double[] x)
{
while (node.Feature >= 0)
{
node = x[node.Feature] <= node.Threshold ? node.Left! : node.Right!;
}
return node.Probability;
}
/// <summary>Importances normalisees : la somme vaut 1, comme scikit-learn.</summary>
public double[] NormalizedImportances()
{
double total = Importances.Sum();
return total <= 0 ? Importances : Importances.Select(v => v / total).ToArray();
}
}
// --- les decoupages ---------------------------------------------------------------
public static class Splits
{
public sealed record Fold(int[] Train, int[] Test);
/// <summary>
/// Plis groupes et stratifies. Les sujets sont repartis en blocs : aucun sujet ne peut
/// etre des deux cotes. La repartition est gloutonne — le plus gros sujet restant va au
/// pli qui en contient le moins — ce qui approche le StratifiedGroupKFold de scikit-learn
/// sans le reproduire a l'identique.
/// </summary>
public static List<Fold> GroupKFolds(int[] y, int[] groups, int k, int seed)
{
var rng = new Rng(seed);
var ids = groups.Distinct().ToList();
// Melange de Fisher-Yates, puis tri par effectif decroissant : les gros sujets d'abord.
for (int i = ids.Count - 1; i > 0; i--)
{
int j = rng.NextInt(0, i + 1);
(ids[i], ids[j]) = (ids[j], ids[i]);
}
var counts = ids.ToDictionary(g => g, g => Enumerable.Range(0, groups.Length).Count(i => groups[i] == g));
ids = ids.OrderByDescending(g => counts[g]).ToList();
var foldGroups = Enumerable.Range(0, k).Select(_ => new List<int>()).ToArray();
var foldCounts = new int[k];
foreach (int g in ids)
{
int target = Enumerable.Range(0, k).OrderBy(f => foldCounts[f]).First();
foldGroups[target].Add(g);
foldCounts[target] += counts[g];
}
var folds = new List<Fold>();
for (int f = 0; f < k; f++)
{
var test = Enumerable.Range(0, groups.Length).Where(i => foldGroups[f].Contains(groups[i])).ToArray();
var inTest = new HashSet<int>(foldGroups[f]);
var train = Enumerable.Range(0, groups.Length).Where(i => !inTest.Contains(groups[i])).ToArray();
folds.Add(new Fold(train, test));
}
return folds;
}
/// <summary>
/// Plis stratifies naifs : les epochs sont repartis sans egard au sujet. C'est le
/// decoupage fautif assume — il fait fuir les sujets entre apprentissage et test.
/// </summary>
public static List<Fold> StratifiedFolds(int[] y, int k, int seed)
{
var rng = new Rng(seed);
var testSets = Enumerable.Range(0, k).Select(_ => new List<int>()).ToArray();
foreach (int classe in y.Distinct())
{
var indices = Enumerable.Range(0, y.Length).Where(i => y[i] == classe).ToList();
for (int i = indices.Count - 1; i > 0; i--)
{
int j = rng.NextInt(0, i + 1);
(indices[i], indices[j]) = (indices[j], indices[i]);
}
for (int i = 0; i < indices.Count; i++) testSets[i % k].Add(indices[i]);
}
var folds = new List<Fold>();
for (int f = 0; f < k; f++)
{
var test = testSets[f].ToArray();
var inTest = new HashSet<int>(test);
var train = Enumerable.Range(0, y.Length).Where(i => !inTest.Contains(i)).ToArray();
folds.Add(new Fold(train, test));
}
return folds;
}
}
// --- la procedure d'evaluation -----------------------------------------------------
public sealed record Hyperparameters(int MaxDepth, int MinLeaf);
public static class Decodeur
{
public static readonly Hyperparameters[] GRID_COARSE =
{
new(int.MaxValue, 1),
new(int.MaxValue, 4),
new(8, 1),
new(8, 4),
};
public static readonly Hyperparameters[] GRID_FINE =
(from depth in new[] { int.MaxValue, 4, 8, 12 }
from leaf in new[] { 1, 2, 4, 8 }
select new Hyperparameters(depth, leaf)).ToArray();
public static double Accuracy(RandomForest forest, double[][] X, int[] y, int[] indices)
{
if (indices.Length == 0) return double.NaN;
int correct = 0;
foreach (int i in indices)
{
if (forest.Predict(X[i]) == y[i]) correct++;
}
return (double)correct / indices.Length;
}
public static RandomForest Fit(double[][] X, int[] y, Hyperparameters hp, int seed)
=> new RandomForest(X, y, new ForestOptions
{
NTrees = N_TREES,
MaxDepth = hp.MaxDepth,
MinLeaf = hp.MinLeaf,
Seed = seed,
});
public static int[] Slice(int[] source, int[] indices)
=> indices.Select(i => source[i]).ToArray();
public static double[][] Slice(double[][] source, int[] indices)
=> indices.Select(i => source[i]).ToArray();
/// <summary>Validation interne : moyenne des precisions des plis internes.</summary>
public static double InnerScore(double[][] X, int[] y, int[] groups, Hyperparameters hp, int seed, bool aware)
{
var folds = aware ? Splits.GroupKFolds(y, groups, 3, seed) : Splits.StratifiedFolds(y, 3, seed);
double total = 0.0;
foreach (var fold in folds)
{
var forest = Fit(Slice(X, fold.Train), Slice(y, fold.Train), hp, seed);
total += Accuracy(forest, X, y, fold.Test);
}
return total / folds.Count;
}
/// <summary>
/// Precision en validation croisee imbriquee : quatre plis exterieurs, trois plis
/// interieurs pour choisir les hyperparametres. La grille ne voit jamais le pli de test.
/// </summary>
public static double NestedCv(double[][] X, int[] y, int[] groups, int seed, bool aware = true,
Hyperparameters[]? grid = null)
{
grid ??= GRID_COARSE;
var outer = aware ? Splits.GroupKFolds(y, groups, 4, seed) : Splits.StratifiedFolds(y, 4, seed);
double total = 0.0;
foreach (var fold in outer)
{
var XTrain = Slice(X, fold.Train);
var yTrain = Slice(y, fold.Train);
var gTrain = Slice(groups, fold.Train);
Hyperparameters best = grid[0];
double bestScore = double.NegativeInfinity;
foreach (var hp in grid)
{
double score = InnerScore(XTrain, yTrain, gTrain, hp, seed, aware);
if (score > bestScore)
{
bestScore = score;
best = hp;
}
}
var finalForest = Fit(XTrain, yTrain, best, seed);
total += Accuracy(finalForest, X, y, fold.Test);
}
return total / outer.Count;
}
/// <summary>
/// Raccourci fautif, reproduit volontairement : la grille est choisie sur TOUTES les
/// donnees, puis la performance est mesuree sur un decoupage groupe. Les hyperparametres
/// ont vu le test — c'est le biais que la section 6 quantifie.
/// </summary>
public static (double accuracy, Hyperparameters best) NonNestedCv(double[][] X, int[] y, int[] groups,
int seed, Hyperparameters[]? grid = null)
{
grid ??= GRID_COARSE;
Hyperparameters best = grid[0];
double bestScore = double.NegativeInfinity;
foreach (var hp in grid)
{
double score = InnerScore(X, y, groups, hp, seed, aware: true);
if (score > bestScore)
{
bestScore = score;
best = hp;
}
}
var outer = Splits.GroupKFolds(y, groups, 4, seed);
double total = 0.0;
foreach (var fold in outer)
{
var forest = Fit(Slice(X, fold.Train), Slice(y, fold.Train), best, seed);
total += Accuracy(forest, X, y, fold.Test);
}
return (total / outer.Count, best);
}
}
// --- un graphe en caracteres : aucune dependance graphique, aucun NuGet --------------
// Le carnet Python trace avec matplotlib ; le portage n'a pas d'equivalent en BCL, et la
// consigne est de n'installer aucun paquet. Plutot qu'un rendu factice, les figures sont
// redessinees ici en caracteres, depuis les valeurs imprimees : elles se lisent dans le
// meme bloc de sortie que la table dont elles viennent.
public static class Graphe
{
/// <summary>Jauge : la valeur en '#', un repere '|' a la position demandee.</summary>
public static string Jauge(double valeur, double lo, double hi, int largeur, double? repere)
{
var chars = Enumerable.Repeat('.', largeur).ToArray();
if (repere.HasValue)
{
int m = (int)Math.Round((repere.Value - lo) / (hi - lo) * (largeur - 1));
if (m >= 0 && m < largeur) chars[m] = '|';
}
int p = (int)Math.Round((valeur - lo) / (hi - lo) * (largeur - 1));
p = Math.Max(0, Math.Min(largeur - 1, p));
chars[p] = '#';
return new string(chars);
}
/// <summary>Barre proportionnelle, pour un profil d'importance.</summary>
public static string Barre(double valeur, double max, int largeur)
=> new string('#', max <= 0 ? 0 : Math.Min(largeur, Math.Max(0, (int)Math.Round(largeur * valeur / max))));
}
// Les trois vues des memes donnees : multi-region, HFD seul, LZC seul.
static double[][] Flatten(double[][][] feats)
{
var rows = new double[feats.Length][];
for (int i = 0; i < feats.Length; i++)
{
rows[i] = new double[N_ROI * 2];
for (int r = 0; r < N_ROI; r++)
{
rows[i][2 * r] = feats[i][r][0];
rows[i][2 * r + 1] = feats[i][r][1];
}
}
return rows;
}
static double[][] Single(double[][][] feats, int idx)
{
var rows = new double[feats.Length][];
for (int i = 0; i < feats.Length; i++)
{
rows[i] = new double[N_ROI];
for (int r = 0; r < N_ROI; r++) rows[i][r] = feats[i][r][idx];
}
return rows;
}
var X_MULTI = Flatten(cohort.Feats);
var X_HFD = Single(cohort.Feats, 0);
var X_LZC = Single(cohort.Feats, 1);
Console.WriteLine($"descripteurs : multi {X_MULTI[0].Length} | HFD {X_HFD[0].Length} | LZC {X_LZC[0].Length}");
Console.WriteLine($"foret : {N_TREES} arbres | grille grossiere {Decodeur.GRID_COARSE.Length} combinaisons | grille fine {Decodeur.GRID_FINE.Length}");