// La cible x[i+window+1] conserve un horizon de deux pas après la fenêtre.
// Le scaler et le MLP sont ajustés sur la première moitié uniquement ; les scores de préfixe restent nuls.
record ResultatMlp(double[] Scores, int TrainRows, int Iterations, double[] MoyennesScaler);
string Base64(double[] values)
{
var bytes = new byte[values.Length * sizeof(double)];
Buffer.BlockCopy(values, 0, bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes);
}
ResultatMlp PrevoirMlp(double[] x, int window = 20, int[] hidden = null, int seed = 0)
{
if (x.Length < window + 5)
return new ResultatMlp(new double[x.Length], 0, 0, Array.Empty<double>());
int rows = x.Length - window - 1, cut = rows / 2;
var features = new double[rows * window];
var targets = new double[rows];
for (int i = 0; i < rows; i++)
{
Array.Copy(x, i, features, i * window, window);
targets[i] = x[i + window + 1];
}
string code = @"import base64,numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
X=np.frombuffer(base64.b64decode(cfg['features']),dtype=cfg['dtype']).reshape(cfg['rows'],cfg['window'])
y=np.frombuffer(base64.b64decode(cfg['targets']),dtype=cfg['dtype'])
cut=cfg['cut']
sc=StandardScaler().fit(X[:cut])
Xs=sc.transform(X)
reg=MLPRegressor(hidden_layer_sizes=tuple(cfg['hidden']),max_iter=1200,random_state=cfg['seed'],early_stopping=True,n_iter_no_change=30,learning_rate_init=1e-3)
reg.fit(Xs[:cut],y[:cut])
err=np.abs(reg.predict(Xs)-y)
result_json=json.dumps({'error':err.tolist(),'iterations':int(reg.n_iter_),'mean':sc.mean_.tolist()},allow_nan=False)";
var payload = new
{
features = Base64(features),
targets = Base64(targets),
dtype = BitConverter.IsLittleEndian ? "<f8" : ">f8",
rows,
window,
cut,
hidden = hidden ?? new[]
{
32
},
seed
};
using var doc = JsonDocument.Parse(Backend(code, payload));
var root = doc.RootElement;
var err = JsonSerializer.Deserialize<double[]>(root.GetProperty("error").GetRawText());
var scores = new double[x.Length];
Array.Copy(err, 0, scores, window + 1, err.Length);
return new ResultatMlp(scores, cut, root.GetProperty("iterations").GetInt32(), JsonSerializer.Deserialize<double[]>(root.GetProperty("mean").GetRawText()));
}
var mlp1 = PrevoirMlp(s1.Valeurs);
double aucMlp1 = Auc(s1.Labels, mlp1.Scores);
Console.WriteLine($"MLP : train {mlp1.TrainRows} fenêtres ×20, {mlp1.Iterations} itérations (max1200), AUC {aucMlp1:F3} ; SPC {aucSpc1:F3}");
Console.WriteLine("Préfixe 21 scores nuls ; AUC sur série complète, pas seulement holdout.");
double maxMlp = Math.Max(mlp1.Scores.Max(), 1e-12), stdAffiche = Std(s1.Valeurs), moyAffiche = Moy(s1.Valeurs);
var mlpAffiche = mlp1.Scores.Select(v => v / maxMlp * stdAffiche + moyAffiche).ToArray();
AfficherSvg(new Svg(Courbes(new[] { s1.Valeurs, mlpAffiche }, new[] { "Série UCR", "Score MLP remis à l'échelle" }, s1, $"{s1.Nom} — SPC {aucSpc1:F3}, MLP {aucMlp1:F3}")));