This repository was 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
/
Copy pathTNRNetClusterBuilder.cs
311 lines (283 loc) · 14.3 KB
/
TNRNetClusterBuilder.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
using RCNet.MiscTools;
using RCNet.Neural.Data;
using RCNet.Neural.Data.Filter;
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 networks cluster based on the cross-validation approach.
/// </summary>
public class TNRNetClusterBuilder
{
//Constants
private const int NetScopeDelimiterCoeff = 1000000;
//Events
/// <summary>
/// This informative event occurs each time the progress of the build process takes a step forward.
/// </summary>
public event ClusterBuildProgressChangedHandler ClusterBuildProgressChanged;
/// <summary>
/// The delegate of the ClusterBuildProgressChanged event handler.
/// </summary>
/// <param name="buildProgress">The current state of the build process.</param>
public delegate void ClusterBuildProgressChangedHandler(BuildProgress buildProgress);
//Attributes
private readonly string _clusterName;
private readonly CrossvalidationSettings _crossvalidationCfg;
private readonly ITNRNetClusterSettings _clusterCfg;
private readonly Random _rand;
private readonly TNRNetBuilder.BuildControllerDelegate _controller;
//Progress tracking attributes
private int _numOfFoldsPerRepetition;
private int _repetitionIdx;
private int _testingFoldIdx;
private int _netCfgIdx;
//Constructor
/// <summary>
/// Creates an initialized instance.
/// </summary>
/// <param name="clusterName">The name of the cluster to be built.</param>
/// <param name="crossvalidationCfg">The crossvalidation configuration.</param>
/// <param name="clusterCfg">The configuration of the cluster to be built.</param>
/// <param name="rand">The random generator to be used (optional).</param>
/// <param name="controller">The network build process controller (optional).</param>
public TNRNetClusterBuilder(string clusterName,
CrossvalidationSettings crossvalidationCfg,
ITNRNetClusterSettings clusterCfg,
Random rand = null,
TNRNetBuilder.BuildControllerDelegate controller = null
)
{
_clusterName = clusterName;
_crossvalidationCfg = crossvalidationCfg;
_clusterCfg = clusterCfg;
_rand = rand ?? new Random(0);
_controller = controller;
ResetProgressTracking();
return;
}
//Methods
private void ResetProgressTracking()
{
_numOfFoldsPerRepetition = 0;
_repetitionIdx = 0;
_testingFoldIdx = 0;
_netCfgIdx = 0;
return;
}
private void OnNetworkBuildProgressChanged(TNRNetBuilder.BuildProgress netBuildProgress)
{
//Prepare cluster version
BuildProgress buildProgress = new BuildProgress(_clusterName,
Math.Min(_repetitionIdx + 1, _crossvalidationCfg.Repetitions),
_crossvalidationCfg.Repetitions,
Math.Min(_testingFoldIdx + 1, _numOfFoldsPerRepetition),
_numOfFoldsPerRepetition,
Math.Min(_netCfgIdx + 1, _clusterCfg.ClusterNetConfigurations.Count),
_clusterCfg.ClusterNetConfigurations.Count,
netBuildProgress
);
//Raise event
ClusterBuildProgressChanged?.Invoke(buildProgress);
return;
}
/// <summary>
/// Builds the cluster.
/// </summary>
/// <param name="dataBundle">The data bundle for training.</param>
/// <param name="filters">The filters to be used to denormalize outputs.</param>
public TNRNetCluster Build(VectorBundle dataBundle, FeatureFilterBase[] filters)
{
VectorBundle localDataBundle = dataBundle.CreateShallowCopy();
//Cluster of trained networks
TNRNetCluster cluster = new TNRNetCluster(_clusterName,
_clusterCfg.Output,
_clusterCfg.TrainingGroupWeight,
_clusterCfg.TestingGroupWeight,
_clusterCfg.SamplesWeight,
_clusterCfg.NumericalPrecisionWeight,
_clusterCfg.MisrecognizedFalseWeight,
_clusterCfg.UnrecognizedTrueWeight
);
//Member's training
ResetProgressTracking();
for (_repetitionIdx = 0; _repetitionIdx < _crossvalidationCfg.Repetitions; _repetitionIdx++)
{
//Data split to folds
List<VectorBundle> foldCollection = localDataBundle.Folderize(_crossvalidationCfg.FoldDataRatio, _clusterCfg.Output == TNRNet.OutputType.Real ? double.NaN : cluster.OutputDataRange.Mid);
_numOfFoldsPerRepetition = Math.Min(_crossvalidationCfg.Folds <= 0 ? foldCollection.Count : _crossvalidationCfg.Folds, foldCollection.Count);
//Train the collection of networks for each processing fold.
for (_testingFoldIdx = 0; _testingFoldIdx < _numOfFoldsPerRepetition; _testingFoldIdx++)
{
//Prepare training data bundle
VectorBundle trainingData = new VectorBundle();
for (int foldIdx = 0; foldIdx < foldCollection.Count; foldIdx++)
{
if (foldIdx != _testingFoldIdx)
{
trainingData.Add(foldCollection[foldIdx]);
}
}
for (_netCfgIdx = 0; _netCfgIdx < _clusterCfg.ClusterNetConfigurations.Count; _netCfgIdx++)
{
TNRNetBuilder netBuilder = new TNRNetBuilder(_clusterName,
_clusterCfg.ClusterNetConfigurations[_netCfgIdx],
_clusterCfg.Output,
trainingData,
foldCollection[_testingFoldIdx],
_rand,
_controller
);
//Register notification
netBuilder.NetworkBuildProgressChanged += OnNetworkBuildProgressChanged;
//Build trained network. Trained network becomes to be the cluster member
TNRNet tn = netBuilder.Build();
//Build an unique network scope identifier
int netScopeID = _repetitionIdx * NetScopeDelimiterCoeff + _testingFoldIdx;
//Add trained network to a cluster
cluster.AddMember(tn, netScopeID, foldCollection[_testingFoldIdx], filters);
}//netCfgIdx
}//testingFoldIdx
if (_repetitionIdx < _crossvalidationCfg.Repetitions - 1)
{
//Reshuffle the data
localDataBundle.Shuffle(_rand);
}
}//repetitionIdx
//Make the cluster operable
cluster.FinalizeCluster();
//Return the built cluster
return cluster;
}
//Inner classes
/// <summary>
/// Implements the holder of the cluster build progress information.
/// </summary>
public class BuildProgress : IBuildProgress
{
//Attribute properties
/// <summary>
/// Name of the cluster.
/// </summary>
public string ClusterName { get; }
/// <summary>
/// Information about the folds processing repetitions progress.
/// </summary>
public ProgressTracker RepetitionsTracker { get; }
/// <summary>
/// Information about the folds processing progress.
/// </summary>
public ProgressTracker FoldsTracker { get; }
/// <summary>
/// Information about the fold networks processing progress.
/// </summary>
public ProgressTracker FoldNetworksTracker { get; }
/// <summary>
/// Information about the network build progress.
/// </summary>
public TNRNetBuilder.BuildProgress NetBuildProgress { get; }
/// <summary>
/// Creates an initialized instance.
/// </summary>
/// <param name="clusterName">Name of the cluster.</param>
/// <param name="repetitionNum">The current folds processing repetition number.</param>
/// <param name="maxNumOfRepetitions">The maximum number of folds processing repetitions.</param>
/// <param name="foldNum">The current fold number within the folds processing repetition.</param>
/// <param name="maxNumOfFolds">The maximum number of folds within the folds processing repetition.</param>
/// <param name="netNum">The current network number within the current fold processing.</param>
/// <param name="maxNumOfNets">The maximum number of networks within the current fold processing.</param>
/// <param name="netBuildProgress">The holder of the network build progress information.</param>
public BuildProgress(string clusterName,
int repetitionNum,
int maxNumOfRepetitions,
int foldNum,
int maxNumOfFolds,
int netNum,
int maxNumOfNets,
TNRNetBuilder.BuildProgress netBuildProgress
)
{
ClusterName = clusterName;
RepetitionsTracker = new ProgressTracker((uint)maxNumOfRepetitions, (uint)repetitionNum);
FoldsTracker = new ProgressTracker((uint)maxNumOfFolds, (uint)foldNum);
FoldNetworksTracker = new ProgressTracker((uint)maxNumOfNets, (uint)netNum);
NetBuildProgress = netBuildProgress;
return;
}
//Properties
/// <inheritdoc/>
public bool NewEndNetwork
{
get
{
return NetBuildProgress.NewEndNetwork;
}
}
/// <inheritdoc/>
public bool ShouldBeReported
{
get
{
return NetBuildProgress.ShouldBeReported;
}
}
/// <inheritdoc/>
public int EndNetworkEpochNum
{
get
{
return NetBuildProgress.EndNetworkEpochNum;
}
}
//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)
{
if (RepetitionsTracker.Target > 1)
{
text.Append($"Repetition {RepetitionsTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(RepetitionsTracker.Target.ToString(CultureInfo.InvariantCulture).Length)}");
text.Append($", ");
}
text.Append($"Fold {FoldsTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(FoldsTracker.Target.ToString(CultureInfo.InvariantCulture).Length)}");
if (FoldNetworksTracker.Target > 1)
{
text.Append($", Net {FoldNetworksTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(FoldNetworksTracker.Target.ToString(CultureInfo.InvariantCulture).Length)}");
}
}
else
{
text.Append($"Repetition {RepetitionsTracker}");
text.Append($", Fold {FoldsTracker}");
text.Append($", Net {FoldNetworksTracker}");
}
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(ClusterName);
progressText.Append("] ");
}
progressText.Append(GetBasicProgressInfoText(true));
progressText.Append(", ");
progressText.Append(NetBuildProgress.GetInfoText(0, false));
return progressText.ToString();
}
}//BuildProgress
}//TNRNetClusterBuilder
}//Namespace