This repository has been archived by the owner on May 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
TNRNetBuilder.cs
559 lines (523 loc) · 27 KB
/
TNRNetBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
using RCNet.MathTools;
using RCNet.MiscTools;
using RCNet.Neural.Data;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RCNet.Neural.Network.NonRecurrent
{
/// <summary>
/// Implements the builder of trained non-recurrent network.
/// </summary>
public class TNRNetBuilder
{
//Delegates
/// <summary>
/// The delegate of a network build process controller invoked during each training epoch.
/// </summary>
/// <remarks>
/// The goal of the build process is to build a network that gives good results both on the training data and the testing data.
/// BuildProgress object contains the best trained network so far and the current one. The primary purpose of controller is
/// to make decision whether the current network is better than the best network so far.
/// The controller can also tell the build process that it does not make any sense to continue. It can
/// stop the current build attempt or the whole build process.
/// </remarks>
/// <param name="buildProgress">The BuildProgress object containing all the necessary information to control the build process.</param>
/// <returns>Instructions for the network build process.</returns>
public delegate BuildInstr BuildControllerDelegate(BuildProgress buildProgress);
/// <summary>
/// The delegate of the NetworkBuildProgressChanged event handler.
/// </summary>
/// <param name="buildProgress">The current state of the build process.</param>
public delegate void NetworkBuildProgressChangedHandler(BuildProgress buildProgress);
/// <summary>
/// This informative event occurs every time the epoch of the network build process is done.
/// </summary>
public event NetworkBuildProgressChangedHandler NetworkBuildProgressChanged;
//Attributes
private readonly string _networkName;
private readonly INonRecurrentNetworkSettings _networkCfg;
private readonly TNRNet.OutputType _networkOutput;
private readonly VectorBundle _trainingBundle;
private readonly VectorBundle _testingBundle;
private readonly Random _rand;
private readonly BuildControllerDelegate _controller;
//Constructor
/// <summary>
/// Creates an initialized instance.
/// </summary>
/// <param name="networkName">The name of the network to be built.</param>
/// <param name="networkCfg">The configuration of the network to be built.</param>
/// <param name="networkOutput">The type of output of the network to be built.</param>
/// <param name="trainingBundle">The bundle of input and ideal vectors to be used for the network training.</param>
/// <param name="testingBundle">The bundle of input and ideal vectors to be used for the network testing.</param>
/// <param name="rand">The random generator to be used (optional).</param>
/// <param name="controller">The build process controller (optional).</param>
public TNRNetBuilder(string networkName,
INonRecurrentNetworkSettings networkCfg,
TNRNet.OutputType networkOutput,
VectorBundle trainingBundle,
VectorBundle testingBundle,
Random rand = null,
BuildControllerDelegate controller = null
)
{
_networkName = networkName;
NonRecurrentNetUtils.CheckNetCfg(networkOutput, networkCfg);
_networkCfg = networkCfg;
_networkOutput = networkOutput;
NonRecurrentNetUtils.CheckData(_networkOutput, trainingBundle);
_trainingBundle = trainingBundle;
NonRecurrentNetUtils.CheckData(_networkOutput, testingBundle);
_testingBundle = testingBundle;
_rand = rand ?? new Random(0);
_controller = controller ?? DefaultNetworkBuildController;
return;
}
//Properties
/// <summary>
/// Gets the boolean border of the network.
/// </summary>
private double BoolBorder
{
get
{
if (_networkOutput == TNRNet.OutputType.Probabilistic)
{
return Interval.IntZP1.Mid;
}
else
{
return Interval.IntN1P1.Mid;
}
}
}
//Static methods
/// <summary>
/// Evaluates whether the "candidate" network achieved a better result than the best network so far.
/// </summary>
/// <remarks>
/// The default implementation.
/// </remarks>
/// <param name="candidate">The candidate network to be evaluated.</param>
/// <param name="currentBest">The best network so far.</param>
public static bool IsBetter(TNRNet candidate, TNRNet currentBest)
{
//Binary decisions comparison
if (candidate.HasBinErrorStats)
{
if (candidate.CombinedBinaryError > currentBest.CombinedBinaryError)
{
return false;
}
else if (candidate.CombinedBinaryError < currentBest.CombinedBinaryError)
{
return true;
}
//CombinedBinaryError is the same
else if (candidate.TestingBinErrorStat.BinValErrStat[0].Sum > currentBest.TestingBinErrorStat.BinValErrStat[0].Sum)
{
return false;
}
else if (candidate.TestingBinErrorStat.BinValErrStat[0].Sum < currentBest.TestingBinErrorStat.BinValErrStat[0].Sum)
{
return true;
}
//CombinedBinaryError is the same
//TestingBinErrorStat.BinValErrStat[0].Sum is the same
else if (candidate.TrainingBinErrorStat.BinValErrStat[0].Sum > currentBest.TrainingBinErrorStat.BinValErrStat[0].Sum)
{
return false;
}
else if (candidate.TrainingBinErrorStat.BinValErrStat[0].Sum < currentBest.TrainingBinErrorStat.BinValErrStat[0].Sum)
{
return true;
}
}
//Numerical precision comparison
if (candidate.CombinedPrecisionError < currentBest.CombinedPrecisionError)
{
return true;
}
else
{
return false;
}
}
//Methods
/// <summary>
/// The default implementation of the build process controler.
/// </summary>
protected BuildInstr DefaultNetworkBuildController(BuildProgress buildProgress)
{
BuildInstr instructions = new BuildInstr
{
CurrentIsBetter = IsBetter(buildProgress.CurrNetwork,
buildProgress.BestNetwork
),
StopProcess = (buildProgress.CurrNetwork.HasBinErrorStats &&
buildProgress.BestNetwork.TrainingBinErrorStat.TotalErrStat.Sum == 0 &&
buildProgress.BestNetwork.TestingBinErrorStat.TotalErrStat.Sum == 0 &&
buildProgress.CurrNetwork.CombinedPrecisionError > buildProgress.BestNetwork.CombinedPrecisionError
)
};
return instructions;
}
/// <summary>
/// Builds the trained network.
/// </summary>
/// <returns>The trained network.</returns>
public TNRNet Build()
{
TNRNet bestNetwork = null;
int bestNetworkAttempt = 0;
int bestNetworkAttemptEpoch = 0;
int currNetworkLastImprovementEpoch = 0;
double currNetworkLastImprovementCombinedPrecisionError = 0d;
double currNetworkLastImprovementCombinedBinaryError = 0d;
//Create network and trainer
NonRecurrentNetUtils.CreateNetworkAndTrainer(_networkCfg,
_trainingBundle.InputVectorCollection,
_trainingBundle.OutputVectorCollection,
_rand,
out INonRecurrentNetwork net,
out INonRecurrentNetworkTrainer trainer
);
//Iterate training cycles
while (trainer.Iteration())
{
//Compute current error statistics after training iteration
//Training data part
TNRNet currNetwork = new TNRNet(_networkName, _networkOutput)
{
Network = net,
TrainerInfoMessage = trainer.InfoMessage,
TrainingErrorStat = net.ComputeBatchErrorStat(_trainingBundle.InputVectorCollection, _trainingBundle.OutputVectorCollection, out List<double[]> trainingComputedOutputsCollection)
};
if (TNRNet.IsBinErrorStatsOutputType(_networkOutput))
{
currNetwork.TrainingBinErrorStat = new BinErrStat(BoolBorder, trainingComputedOutputsCollection, _trainingBundle.OutputVectorCollection);
currNetwork.CombinedBinaryError = currNetwork.TrainingBinErrorStat.TotalErrStat.Sum;
}
currNetwork.CombinedPrecisionError = currNetwork.TrainingErrorStat.ArithAvg;
//Testing data part
currNetwork.TestingErrorStat = net.ComputeBatchErrorStat(_testingBundle.InputVectorCollection, _testingBundle.OutputVectorCollection, out List<double[]> testingComputedOutputsCollection);
currNetwork.CombinedPrecisionError = Math.Max(currNetwork.CombinedPrecisionError, currNetwork.TestingErrorStat.ArithAvg);
if (TNRNet.IsBinErrorStatsOutputType(_networkOutput))
{
currNetwork.TestingBinErrorStat = new BinErrStat(BoolBorder, testingComputedOutputsCollection, _testingBundle.OutputVectorCollection);
currNetwork.CombinedBinaryError = Math.Max(currNetwork.CombinedBinaryError, currNetwork.TestingBinErrorStat.TotalErrStat.Sum);
}
//Restart lastImprovementEpoch when new trainer's attempt started
if (trainer.AttemptEpoch == 1)
{
currNetworkLastImprovementEpoch = trainer.AttemptEpoch;
currNetworkLastImprovementCombinedPrecisionError = currNetwork.CombinedPrecisionError;
if (TNRNet.IsBinErrorStatsOutputType(_networkOutput))
{
currNetworkLastImprovementCombinedBinaryError = currNetwork.CombinedBinaryError;
}
}
//First initialization of the best network
if (bestNetwork == null)
{
bestNetwork = currNetwork.DeepClone();
bestNetworkAttempt = trainer.Attempt;
}
if ((TNRNet.IsBinErrorStatsOutputType(_networkOutput) && currNetwork.CombinedBinaryError < currNetworkLastImprovementCombinedBinaryError) ||
currNetwork.CombinedPrecisionError < currNetworkLastImprovementCombinedPrecisionError
)
{
currNetworkLastImprovementCombinedPrecisionError = currNetwork.CombinedPrecisionError;
if (TNRNet.IsBinErrorStatsOutputType(_networkOutput))
{
currNetworkLastImprovementCombinedBinaryError = currNetwork.CombinedBinaryError;
}
currNetworkLastImprovementEpoch = trainer.AttemptEpoch;
}
//BuildProgress instance
BuildProgress buildProgress = new BuildProgress(_networkName,
trainer.Attempt,
trainer.MaxAttempt,
trainer.AttemptEpoch,
trainer.MaxAttemptEpoch,
currNetwork,
currNetworkLastImprovementEpoch,
bestNetwork,
bestNetworkAttempt,
bestNetworkAttemptEpoch
);
//Call controller
BuildInstr instructions = _controller(buildProgress);
//Better?
if (instructions.CurrentIsBetter)
{
//Adopt current regression unit as a best one
bestNetwork = currNetwork.DeepClone();
bestNetworkAttempt = trainer.Attempt;
bestNetworkAttemptEpoch = trainer.AttemptEpoch;
//Update build progress
buildProgress.BestNetwork = bestNetwork;
buildProgress.BestNetworkAttemptNum = bestNetworkAttempt;
buildProgress.BestNetworkAttemptEpochNum = bestNetworkAttemptEpoch;
}
//Raise notification event
NetworkBuildProgressChanged?.Invoke(buildProgress);
//Process instructions
if (instructions.StopProcess)
{
break;
}
else if (instructions.StopCurrentAttempt)
{
if (!trainer.NextAttempt())
{
break;
}
}
}//while (iteration)
//Create statistics of the best network weights
bestNetwork.NetworkWeightsStat = bestNetwork.Network.ComputeWeightsStat();
return bestNetwork;
}
//Inner classes
/// <summary>
/// Implements the holder of the network build progress information.
/// </summary>
public class BuildProgress : IBuildProgress
{
//Attribute properties
/// <summary>
/// Name of the network.
/// </summary>
public string NetworkName { get; }
/// <summary>
/// Information about the progress of network build attempts.
/// </summary>
public ProgressTracker AttemptsTracker { get; }
/// <summary>
/// Information about the progress of network build epochs within the current attempt.
/// </summary>
public ProgressTracker AttemptEpochsTracker { get; }
/// <summary>
/// The current network and its error statistics.
/// </summary>
public TNRNet CurrNetwork { get; }
/// <summary>
/// An epoch number within the current build attempt when was found an improvement of the current network.
/// </summary>
public int CurrNetworkLastImprovementAttemptEpochNum { get; }
/// <summary>
/// The best network so far and its error statistics.
/// </summary>
public TNRNet BestNetwork { get; set; }
/// <summary>
/// The attempt number in which was found the best network so far.
/// </summary>
public int BestNetworkAttemptNum { get; set; }
/// <summary>
/// The epoch number within the BestNetworkAttempt in which was found the best network so far.
/// </summary>
public int BestNetworkAttemptEpochNum { get; set; }
/// <summary>
/// Creates an initialized instance.
/// </summary>
/// <param name="networkName">Name of the network.</param>
/// <param name="attemptNum">The current attempt number.</param>
/// <param name="maxNumOfAttempts">The maximum number of attempts.</param>
/// <param name="attemptEpochNum">The current epoch number within the current attempt.</param>
/// <param name="maxNumOfAttemptEpochs">The maximum number of epochs.</param>
/// <param name="currNetwork">The current network and its error statistics.</param>
/// <param name="currNetworkLastImprovementEpochNum">An epoch number within the current build attempt when was found an improvement of the current network.</param>
/// <param name="bestNetwork">The best network so far and its error statistics.</param>
/// <param name="bestNetworkAttemptNum">The attempt number in which was found the best network so far.</param>
/// <param name="bestNetworkAttemptEpochNum">The epoch number within the bestNetworkAttemptNum in which was found the best network so far.</param>
public BuildProgress(string networkName,
int attemptNum,
int maxNumOfAttempts,
int attemptEpochNum,
int maxNumOfAttemptEpochs,
TNRNet currNetwork,
int currNetworkLastImprovementEpochNum,
TNRNet bestNetwork,
int bestNetworkAttemptNum,
int bestNetworkAttemptEpochNum
)
{
NetworkName = networkName;
AttemptsTracker = new ProgressTracker((uint)maxNumOfAttempts, (uint)attemptNum);
AttemptEpochsTracker = new ProgressTracker((uint)maxNumOfAttemptEpochs, (uint)attemptEpochNum);
CurrNetwork = currNetwork;
CurrNetworkLastImprovementAttemptEpochNum = currNetworkLastImprovementEpochNum;
BestNetwork = bestNetwork;
BestNetworkAttemptNum = bestNetworkAttemptNum;
BestNetworkAttemptEpochNum = bestNetworkAttemptEpochNum;
return;
}
//Properties
/// <inheritdoc cref="TNRNet.OutputType"/>
public TNRNet.OutputType NetworkOutputType { get { return CurrNetwork.Output; } }
/// <summary>
/// Indicates the current network is also the best network so far.
/// </summary>
public bool CurrentIsBest { get { return (BestNetworkAttemptNum == AttemptsTracker.Current && BestNetworkAttemptEpochNum == AttemptEpochsTracker.Current); } }
/// <inheritdoc/>
public bool NewEndNetwork
{
get
{
return AttemptsTracker.Current == 1 && AttemptEpochsTracker.Current == 1;
}
}
/// <inheritdoc/>
public bool ShouldBeReported
{
get
{
return NewEndNetwork || CurrentIsBest || AttemptEpochsTracker.Last;
}
}
/// <inheritdoc/>
public int EndNetworkEpochNum
{
get
{
return (int)AttemptEpochsTracker.Current;
}
}
//Methods
/// <summary>
/// Gets textual information about the build basic progress.
/// </summary>
/// <param name="shortVersion">Specifies whether to build short version of the informative text.</param>
public string GetBasicProgressInfoText(bool shortVersion = true)
{
StringBuilder text = new StringBuilder();
if (shortVersion)
{
text.Append($"Attempt {AttemptsTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(AttemptsTracker.Target.ToString(CultureInfo.InvariantCulture).Length)}");
text.Append($", Epoch {AttemptEpochsTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(AttemptEpochsTracker.Target.ToString(CultureInfo.InvariantCulture).Length)}");
}
else
{
text.Append($"Attempt {AttemptsTracker}");
text.Append($", Epoch {AttemptEpochsTracker}");
}
return text.ToString();
}
/// <summary>
/// Gets textual information about the training and test samples.
/// </summary>
/// <param name="shortVersion">Specifies whether to build short version of the informative text.</param>
public string GetSamplesInfoText(bool shortVersion = true)
{
StringBuilder text = new StringBuilder();
int numOfTrainingSamples = CurrNetwork.TrainingErrorStat.NumOfSamples / CurrNetwork.Network.NumOfOutputValues;
int numOfTestingSamples = CurrNetwork.TestingErrorStat.NumOfSamples / CurrNetwork.Network.NumOfOutputValues;
if (shortVersion)
{
text.Append($"Samples {numOfTrainingSamples.ToString(CultureInfo.InvariantCulture)}");
text.Append($"/{numOfTestingSamples.ToString(CultureInfo.InvariantCulture)}");
}
else
{
text.Append($"Training samples {numOfTrainingSamples.ToString(CultureInfo.InvariantCulture)}");
text.Append($", Testing samples {numOfTestingSamples.ToString(CultureInfo.InvariantCulture)}");
}
return text.ToString();
}
/// <summary>
/// Gets textual information about the specified trained network instance.
/// </summary>
/// <param name="network">An instance of trained network.</param>
/// <param name="shortVersion">Specifies whether to build short version of the informative text.</param>
public string GetNetworkInfoText(TNRNet network, bool shortVersion = true)
{
StringBuilder text = new StringBuilder();
if (shortVersion)
{
text.Append("TrainErr ");
text.Append(network.TrainingErrorStat.ArithAvg.ToString("E3", CultureInfo.InvariantCulture));
if (network.HasBinErrorStats)
{
text.Append("/" + network.TrainingBinErrorStat.TotalErrStat.Sum.ToString(CultureInfo.InvariantCulture));
text.Append("/" + network.TrainingBinErrorStat.BinValErrStat[1].Sum.ToString(CultureInfo.InvariantCulture));
}
text.Append(", TestErr ");
text.Append(network.TestingErrorStat.ArithAvg.ToString("E3", CultureInfo.InvariantCulture));
if (network.HasBinErrorStats)
{
text.Append("/" + network.TestingBinErrorStat.TotalErrStat.Sum.ToString(CultureInfo.InvariantCulture));
text.Append("/" + network.TestingBinErrorStat.BinValErrStat[1].Sum.ToString(CultureInfo.InvariantCulture));
}
}
else
{
text.Append("Training numerical error ");
text.Append(network.TrainingErrorStat.ArithAvg.ToString("E3", CultureInfo.InvariantCulture));
if (network.HasBinErrorStats)
{
text.Append(", total bad classifications " + network.TrainingBinErrorStat.TotalErrStat.Sum.ToString(CultureInfo.InvariantCulture));
text.Append(", false positive classifications " + network.TrainingBinErrorStat.BinValErrStat[1].Sum.ToString(CultureInfo.InvariantCulture));
}
text.Append(", Testing numerical error ");
text.Append(network.TestingErrorStat.ArithAvg.ToString("E3", CultureInfo.InvariantCulture));
if (network.HasBinErrorStats)
{
text.Append(", total incorrect classifications " + network.TestingBinErrorStat.TotalErrStat.Sum.ToString(CultureInfo.InvariantCulture));
text.Append(", false positive classifications " + network.TestingBinErrorStat.BinValErrStat[1].Sum.ToString(CultureInfo.InvariantCulture));
}
}
return text.ToString();
}
/// <inheritdoc/>
public string GetInfoText(int margin = 0, bool includeName = true)
{
//Build the progress text message
StringBuilder progressText = new StringBuilder();
progressText.Append(new string(' ', margin));
if (includeName)
{
progressText.Append("[");
progressText.Append(NetworkName);
progressText.Append("] ");
}
progressText.Append(GetBasicProgressInfoText(true));
progressText.Append(", ");
progressText.Append(GetSamplesInfoText(true));
progressText.Append(", BestNet-{");
progressText.Append(GetNetworkInfoText(BestNetwork, true));
progressText.Append("}, CurrNet-{");
progressText.Append(GetNetworkInfoText(CurrNetwork, true));
progressText.Append("}");
if (BestNetwork.TrainerInfoMessage.Length > 0)
{
progressText.Append(", BestParam-{");
progressText.Append(BestNetwork.TrainerInfoMessage);
progressText.Append("}");
}
return progressText.ToString();
}
}//BuildProgress
/// <summary>
/// Implements the holder of instructions for the network build process.
/// </summary>
public class BuildInstr
{
//Attribute properties
/// <summary>
/// Instructs whether to terminate the current regression attempt.
/// </summary>
public bool StopCurrentAttempt { get; set; } = false;
/// <summary>
/// Instructs whether to terminate the entire build process.
/// </summary>
public bool StopProcess { get; set; } = false;
/// <summary>
/// Informs the build process whether the current network is better than the best network so far.
/// </summary>
public bool CurrentIsBetter { get; set; } = false;
}//BuildInstr
}//TNRNetBuilder
}//Namespace