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
/
Copy pathTNRNetClusterChainBuilder.cs
368 lines (339 loc) · 18.4 KB
/
TNRNetClusterChainBuilder.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
using RCNet.Extensions;
using RCNet.MiscTools;
using RCNet.Neural.Data;
using RCNet.Neural.Data.Filter;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RCNet.Neural.Network.NonRecurrent
{
/// <summary>
/// Implements the builder of the chain of cooperating non-recurrent network clusters.
/// </summary>
public class TNRNetClusterChainBuilder
{
//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 ChainBuildProgressChangedHandler ChainBuildProgressChanged;
/// <summary>
/// The delegate of the ChainBuildProgressChanged event handler.
/// </summary>
/// <param name="buildProgress">The current state of the build process.</param>
public delegate void ChainBuildProgressChangedHandler(BuildProgress buildProgress);
//Attributes
private readonly string _chainName;
private readonly ITNRNetClusterChainSettings _clusterChainCfg;
private readonly Random _rand;
private readonly TNRNetBuilder.BuildControllerDelegate _controller;
//Progress tracking attributes
private int _repetitionIdx;
private int _clusterIdx;
private int _numOfFoldsPerRepetition;
private int _testingFoldIdx;
private int _netCfgIdx;
//Constructor
/// <summary>
/// Creates an initialized instance.
/// </summary>
/// <param name="chainName">The name of the cluster chain.</param>
/// <param name="clusterChainCfg">The configuration of the cluster chain.</param>
/// <param name="rand">The random generator to be used (optional).</param>
/// <param name="controller">The network build process controller (optional).</param>
public TNRNetClusterChainBuilder(string chainName,
ITNRNetClusterChainSettings clusterChainCfg,
Random rand = null,
TNRNetBuilder.BuildControllerDelegate controller = null
)
{
_chainName = chainName;
_clusterChainCfg = clusterChainCfg;
_rand = rand ?? new Random(0);
_controller = controller;
ResetProgressTracking();
return;
}
//Methods
private void ResetProgressTracking()
{
_repetitionIdx = 0;
_clusterIdx = 0;
_numOfFoldsPerRepetition = 0;
_testingFoldIdx = 0;
_netCfgIdx = 0;
return;
}
private void OnNetworkBuildProgressChanged(TNRNetBuilder.BuildProgress netBuildProgress)
{
//Prepare chain version
BuildProgress buildProgress = new BuildProgress(_chainName,
Math.Min(_repetitionIdx + 1, _clusterChainCfg.CrossvalidationCfg.Repetitions),
_clusterChainCfg.CrossvalidationCfg.Repetitions,
Math.Min(_clusterIdx + 1, _clusterChainCfg.ClusterCfgCollection.Count),
_clusterChainCfg.ClusterCfgCollection.Count,
Math.Min(_testingFoldIdx + 1, _numOfFoldsPerRepetition),
_numOfFoldsPerRepetition,
Math.Min(_netCfgIdx + 1, _clusterChainCfg.ClusterCfgCollection[_clusterIdx].ClusterNetConfigurations.Count),
_clusterChainCfg.ClusterCfgCollection[_clusterIdx].ClusterNetConfigurations.Count,
netBuildProgress
);
//Raise event
ChainBuildProgressChanged?.Invoke(buildProgress);
return;
}
private List<VectorBundle> CopyFolds(List<VectorBundle> sourceFolds)
{
List<VectorBundle> copyFolds = new List<VectorBundle>(sourceFolds.Count);
foreach (VectorBundle fold in sourceFolds)
{
copyFolds.Add(fold.CreateShallowCopy());
}
return copyFolds;
}
/// <summary>
/// Builds the cluster chain.
/// </summary>
/// <param name="dataBundle">The data bundle for training.</param>
/// <param name="filters">The filters to be used to denormalize outputs.</param>
public TNRNetClusterChain Build(VectorBundle dataBundle, FeatureFilterBase[] filters)
{
//The chain to be built
TNRNetClusterChain chain = new TNRNetClusterChain(_chainName, _clusterChainCfg.Output);
//Instantiate chained clusters
List<TNRNetCluster> chainClusters = new List<TNRNetCluster>(_clusterChainCfg.ClusterCfgCollection.Count);
for (int clusterIdx = 0; clusterIdx < _clusterChainCfg.ClusterCfgCollection.Count; clusterIdx++)
{
//Cluster
chainClusters.Add(new TNRNetCluster(_chainName,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].Output,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].TrainingGroupWeight,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].TestingGroupWeight,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].SamplesWeight,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].NumericalPrecisionWeight,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].MisrecognizedFalseWeight,
_clusterChainCfg.ClusterCfgCollection[clusterIdx].UnrecognizedTrueWeight
)
);
}
//Common crossvalidation configuration
double boolBorder = _clusterChainCfg.Output == TNRNet.OutputType.Real ? double.NaN : chain.OutputDataRange.Mid;
VectorBundle localDataBundle = dataBundle.CreateShallowCopy();
//Member's training
ResetProgressTracking();
for (_repetitionIdx = 0; _repetitionIdx < _clusterChainCfg.CrossvalidationCfg.Repetitions; _repetitionIdx++)
{
//Split data to folds
List<VectorBundle> foldCollection = localDataBundle.Folderize(_clusterChainCfg.CrossvalidationCfg.FoldDataRatio, boolBorder);
_numOfFoldsPerRepetition = Math.Min(_clusterChainCfg.CrossvalidationCfg.Folds <= 0 ? foldCollection.Count : _clusterChainCfg.CrossvalidationCfg.Folds, foldCollection.Count);
List<VectorBundle> currentClusterFoldCollection = CopyFolds(foldCollection);
List<VectorBundle> nextClusterFoldCollection = new List<VectorBundle>(foldCollection.Count);
//For each cluster
for (_clusterIdx = 0; _clusterIdx < chainClusters.Count; _clusterIdx++)
{
//Train networks for each testing fold.
for (_testingFoldIdx = 0; _testingFoldIdx < _numOfFoldsPerRepetition; _testingFoldIdx++)
{
//Prepare training data bundle
VectorBundle trainingData = new VectorBundle();
for (int foldIdx = 0; foldIdx < currentClusterFoldCollection.Count; foldIdx++)
{
if (foldIdx != _testingFoldIdx)
{
trainingData.Add(currentClusterFoldCollection[foldIdx]);
}
}
VectorBundle nextClusterUpdatedDataFold = foldCollection[_testingFoldIdx].CreateShallowCopy();
for (_netCfgIdx = 0; _netCfgIdx < _clusterChainCfg.ClusterCfgCollection[_clusterIdx].ClusterNetConfigurations.Count; _netCfgIdx++)
{
TNRNetBuilder netBuilder = new TNRNetBuilder(_chainName,
_clusterChainCfg.ClusterCfgCollection[_clusterIdx].ClusterNetConfigurations[_netCfgIdx],
_clusterChainCfg.ClusterCfgCollection[_clusterIdx].Output,
trainingData,
currentClusterFoldCollection[_testingFoldIdx],
_rand,
_controller
);
//Register notification
netBuilder.NetworkBuildProgressChanged += OnNetworkBuildProgressChanged;
//Build trained network. Trained network becomes to be the cluster member
TNRNet tn = netBuilder.Build();
int netScopeID = _repetitionIdx * NetScopeDelimiterCoeff + _testingFoldIdx;
chainClusters[_clusterIdx].AddMember(tn, netScopeID, currentClusterFoldCollection[_testingFoldIdx], filters);
//Update input data in the data fold for the next cluster
for (int sampleIdx = 0; sampleIdx < currentClusterFoldCollection[_testingFoldIdx].InputVectorCollection.Count; sampleIdx++)
{
double[] computedNetData = tn.Network.Compute(currentClusterFoldCollection[_testingFoldIdx].InputVectorCollection[sampleIdx]);
nextClusterUpdatedDataFold.InputVectorCollection[sampleIdx] = nextClusterUpdatedDataFold.InputVectorCollection[sampleIdx].Concat(computedNetData);
}
}//netCfgIdx
//Add updated data fold for the next cluster
nextClusterFoldCollection.Add(nextClusterUpdatedDataFold);
}//testingFoldIdx
//Switch fold collection
currentClusterFoldCollection = nextClusterFoldCollection;
nextClusterFoldCollection = new List<VectorBundle>(currentClusterFoldCollection.Count);
}//clusterIdx
if (_repetitionIdx < _clusterChainCfg.CrossvalidationCfg.Repetitions - 1)
{
//Reshuffle the data
localDataBundle.Shuffle(_rand);
}
}//repetitionIdx
//Make the clusters operable and add them into the chain
for (int clusterIdx = 0; clusterIdx < chainClusters.Count; clusterIdx++)
{
chainClusters[clusterIdx].FinalizeCluster();
chain.AddCluster(chainClusters[clusterIdx]);
}
//Return the built chain
return chain;
}
//Inner classes
/// <summary>
/// Implements the holder of the cluster chain build progress information.
/// </summary>
public class BuildProgress : IBuildProgress
{
//Attribute properties
/// <summary>
/// Name of the cluster chain.
/// </summary>
public string ChainName { get; }
/// <summary>
/// Information about the folds processing repetitions progress.
/// </summary>
public ProgressTracker RepetitionsTracker { get; }
/// <summary>
/// Information about the clusters processing progress.
/// </summary>
public ProgressTracker ClustersTracker { 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="chainName">Name of the cluster chain.</param>
/// <param name="repetitionNum">The current folds processing repetition number.</param>
/// <param name="maxNumOfRepetitions">The maximum number of folds processing repetitions.</param>
/// <param name="clusterNum">The current cluster number within the repetition.</param>
/// <param name="maxNumOfClusters">The maximum number of clusters within the repetition.</param>
/// <param name="foldNum">The current fold number within the cluster processing.</param>
/// <param name="maxNumOfFolds">The maximum number of folds within the cluster processing.</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 chainName,
int repetitionNum,
int maxNumOfRepetitions,
int clusterNum,
int maxNumOfClusters,
int foldNum,
int maxNumOfFolds,
int netNum,
int maxNumOfNets,
TNRNetBuilder.BuildProgress netBuildProgress
)
{
ChainName = chainName;
RepetitionsTracker = new ProgressTracker((uint)maxNumOfRepetitions, (uint)repetitionNum);
ClustersTracker = new ProgressTracker((uint)maxNumOfClusters, (uint)clusterNum);
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($", ");
}
if (ClustersTracker.Target > 1)
{
text.Append($"Cluster {ClustersTracker.Current.ToString(CultureInfo.InvariantCulture).PadLeft(ClustersTracker.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($", Cluster {ClustersTracker}");
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(ChainName);
progressText.Append("] ");
}
progressText.Append(GetBasicProgressInfoText(true));
progressText.Append(", ");
progressText.Append(NetBuildProgress.GetInfoText(0, false));
return progressText.ToString();
}
}//BuildProgress
}//TNRNetClusterChainBuilder
}//Namespace