-
Notifications
You must be signed in to change notification settings - Fork 1
/
NewDann.Network.pas
1949 lines (1748 loc) · 51.4 KB
/
NewDann.Network.pas
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NewDann - Project
// Author : Jens Biermann, Linsburg
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
unit NewDann.Network;
interface
{.$DEFINE USEOPENCL }
uses
System.Generics.Collections, System.SysUtils, System.Generics.Defaults, System.Types, System.Classes, System.Math,
NewDann.Formula,
{$IFDEF USEOPENCL}
NewDann.OpenCL,
{$ENDIF}
Xml.XMLDoc, Xml.XMLIntf;
const
cDeltaMinimum = 1E-6;
type
TTrainType = (RPROP, BackpropOnline, BackpropBatch);
TStopType = (stopNo, stopUserBreak, stopErrorAccomplished, stopNoErrorDifference);
TStopTypeHelper = record helper for TStopType
public
function ToText: string;
end;
TPointHelper = record helper for TPoint
public
function ToText: string;
procedure FromText(S: string);
end;
TRPROP = record
private
FDeltaMax: Single;
FDeltaMin: Single;
FDeltaDown: Single;
FDeltaUp: Single;
public
procedure SetStandard;
property DeltaMax: Single read FDeltaMax write FDeltaMax;
property DeltaMin: Single read FDeltaMin write FDeltaMin;
property DeltaUp: Single read FDeltaUp write FDeltaUp;
property DeltaDown: Single read FDeltaDown write FDeltaDown;
end;
TNeuron = class
strict private
FDelta: Single;
FInValue: Single;
FOutValue: Single;
FDeriveValue: Single;
FIsBias: Boolean;
FIsDropOut: Boolean;
FActFunc: TThresholdType;
FActSteepness: Single;
FPos: TPoint;
function GetOutValue: Single;
procedure SetInValue(const Value: Single);
function GetLayerIndx: Integer;
function GetDelta: Single;
public
constructor Create(Num_Layer, Num_Neuron: Integer; IsBias: Boolean = False);
{$IFDEF USEOPENCL}
procedure SetValue(const InValue, OutValue, DeriveValue: Single); overload;
{$ENDIF}
procedure SetValue(const InValue: Single); overload;
procedure NewPosX(const X: Integer);
// TPoint in Pos :
// X -> NeuronIndex
// Y -> LayerIndex
property LayerIndx: Integer read GetLayerIndx;
property IsBias: Boolean read FIsBias;
property IsDropOut: Boolean read FIsDropOut write FIsDropOut;
property InValue: Single read FInValue write SetInValue;
property OutValue: Single read FOutValue;
property DeriveValue: Single read FDeriveValue;
property ActSteepness: Single read FActSteepness write FActSteepness;
property ActFunc: TThresholdType read FActFunc write FActFunc;
property Delta: Single read GetDelta write FDelta;
property Pos: TPoint read FPos;
end;
TNeuronList = class(TObjectList<TNeuron>)
strict private
{$IFDEF USEOPENCL}
FThresholdCL: TThresholdCL;
{$ENDIF}
function GetLayerNeurons(LayerIndx: Integer): TArray<TNeuron>;
function GetNeuronCount(LayerIndx: Integer): Integer;
function GetLayerCounts: TArray<Integer>;
function GetLayerCount: Integer;
function GetNeuronCountMax: Integer;
function GetCountInput: Integer;
function GetCountOutput: Integer;
function GetNeuronsInput: TArray<TNeuron>;
function GetNeuronsOutput: TArray<TNeuron>;
function GetCountHidden: Integer;
function GetNeuronsHidden: TArray<TNeuron>;
function GetNeuron(Pos: TPoint): TNeuron;
function GetOutValues: TArray<Single>;
function GetOutput: TArray<Single>;
procedure DropOut(LayerIndx: Integer; Rate: Single);
procedure DropOutReset;
public
procedure Sort;
procedure CleanAndSort;
procedure CleanPositions;
procedure InsertNeurons(N: TArray<TNeuron>);
procedure DataToNeurons(LayerIndx: Integer; InputData: TArray<Single>);
{$IFDEF USEOPENCL}
procedure DataToNeuronsCL(LayerIndx: Integer; InputData: TArray<Single>; ThresholdData: TArray<Integer>);
{$ENDIF}
procedure DefActFunction(LayerIndx: Integer; F: TThresholdType);
function NeuronOfPos(Pos: TPoint): TNeuron;
function BetaByNguyenWidrow: Single;
procedure DroppingOut(DropOutRateOfHiddenLayer: TArray<Single>);
property Output: TArray<Single> read GetOutput;
property NeuronsInput: TArray<TNeuron> read GetNeuronsInput;
property NeuronsOutput: TArray<TNeuron> read GetNeuronsOutput;
property NeuronsHidden: TArray<TNeuron> read GetNeuronsHidden;
property OutValues: TArray<Single> read GetOutValues;
property CountInput: Integer read GetCountInput;
property CountOutput: Integer read GetCountOutput;
property CountHidden: Integer read GetCountHidden;
property LayerNeurons[LayerIndx: Integer]: TArray<TNeuron> read GetLayerNeurons;
property NeuronCount[LayerIndx: Integer]: Integer read GetNeuronCount;
property NeuronCountMax: Integer read GetNeuronCountMax;
property LayerCount: Integer read GetLayerCount;
property LayerCounts: TArray<Integer> read GetLayerCounts;
property Neuron[Pos: TPoint]: TNeuron read GetNeuron;
{$IFDEF USEOPENCL}
property ThresholdCL: TThresholdCL read FThresholdCL write FThresholdCL;
{$ENDIF}
end;
TConnection = class
strict private
FFromNeuron: TNeuron;
FToNeuron: TNeuron;
FWeight: Single;
FSumGradient: Single;
// BackPROP
FMomentum: Single;
// RPROP
FGradient: Single;
FDelta: Single;
function calcGradient: Single;
procedure AddWeight_BackPROP(Gradient, Epsilon, MomentumFaktor: Single);
public
procedure SumGradient;
procedure AddWeight_BackPROP_Online(Epsilon, MomentumFaktor: Single);
procedure AddWeight_BackPROP_Batch(Epsilon, MomentumFaktor: Single);
procedure AddWeight_RPROP(RPROP: TRPROP);
procedure Clear;
procedure Clear_Epoch;
property FromNeuron: TNeuron read FFromNeuron write FFromNeuron;
property ToNeuron: TNeuron read FToNeuron write FToNeuron;
property Weight: Single read FWeight write FWeight;
// BackPROP
property Momentum: Single read FMomentum write FMomentum;
end;
TConList = class(TObjectList<TConnection>)
strict private
function GetNeuron(Pos: TPoint): TNeuron;
function GetLayerCount: Integer;
function GetInConsOfNeuron(Pos: TPoint): TArray<TConnection>;
function GetOutConsOfNeuron(Pos: TPoint): TArray<TConnection>;
function GetWeightMax: Single;
function GetWeightMin: Single;
function GetWeights: TArray<Single>;
function IsNeuronsPerLayerValid(NeuronsPerLayer: TArray<Integer>): Boolean;
public
procedure CreateNetwork(NeuronsPerLayer: TArray<Integer>);
procedure Reset;
procedure Clear_Epoch;
function DeltaOfNeuron(Pos: TPoint): Single;
function SumValueXWeights(Pos: TPoint): Single;
function ToNeurons: TArray<TNeuron>;
function ConsOfNeurons(N1, N2: TNeuron): TConnection;
function SumSqrWeights(N: TNeuron): Single;
procedure SumGradient;
procedure AddWeights_BackPROP_Online(Epsilon, MomentumFaktor: Single);
procedure AddWeights_BackPROP_Batch(Epsilon, MomentumFaktor: Single);
procedure AddWeights_RPROP(RPROP: TRPROP);
procedure RandomWeights(MinWeight, MaxWeight: Single);
procedure SetWeightsByNguyenWidrow(N: TNeuron; beta: Single);
procedure CleanSmallWeights(const Epsilon: Single = 0);
property Weights: TArray<Single> read GetWeights;
property InConsOfNeuron[Pos: TPoint]: TArray<TConnection> read GetInConsOfNeuron;
property OutConsOfNeuron[Pos: TPoint]: TArray<TConnection> read GetOutConsOfNeuron;
// property Neuron[Pos: TPoint]: TNeuron read GetNeuron;
property LayerCount: Integer read GetLayerCount;
property WeightMin: Single read GetWeightMin;
property WeightMax: Single read GetWeightMax;
end;
TNeuralNetLoader = class
strict private
FNeurons: TNeuronList;
FConList: TConList;
procedure SetXML(XML: string);
function GetXML: string;
public
constructor Create(Neurons: TNeuronList; ConList: TConList);
procedure SaveStructure(Filename: string);
procedure LoadStructure(Filename: string);
property XML: string read GetXML write SetXML;
end;
TMSEDifference = class
strict private
FMSEdifferenceQueue: TQueue<Single>;
FDifferenceCount: Integer;
FinternMSEdifferenceCount: Integer;
FDifference: Single;
FinternMSEdifference: Single;
function _MeanAndStdDev: Boolean;
private
function GetDifference: Single;
public
constructor Create;
destructor Destroy; override;
procedure Start(ExpectedMSE: Single);
function IsDifference(MSE: Single): Boolean;
property Difference: Single read GetDifference write FDifference;
property DifferenceCount: Integer read FDifferenceCount write FDifferenceCount;
end;
TRunData = reference to procedure(Const Indx, Count: Integer; var Res: TArray<Single>; var IsBreak: Boolean);
TNeuralNetRunner = class
strict private
FOwnsObjects: Boolean;
FNeurons: TNeuronList;
FConList: TConList;
private
function GetIsValid: Boolean;
public
constructor Create; overload;
constructor Create(ConList: TConList; Neurons: TNeuronList); overload;
destructor Destroy; override;
procedure Run(InputData: TArray<Single>); overload;
procedure Run(Input: TRunData; OutPut: TProc < Integer, TArray < Single >> ); overload;
function Output: TArray<Single>;
procedure LoadStructureFromFile(Filename: string);
procedure LoadStructureFromXML(XML: string);
property IsValid: Boolean read GetIsValid;
property Con: TConList read FConList;
property Neurons: TNeuronList read FNeurons;
end;
TMSEEvent = procedure(Sender: TObject; M: Single; Epoche: Integer; var Stop: Boolean) of object;
TDataEvent = procedure(Sender: TObject; Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>) of object;
TNeuralNet = class
strict private
FLossFunc: TErrorFunc;
FWeightErrorFunc: TWeightErrorFunc;
FWeightErrorLambda: Single;
FNeurons: TNeuronList;
FConList: TConList;
FOnMSE: TMSEEvent;
FOnTrainData: TDataEvent;
FOnValidData: TDataEvent;
FOnTestData: TDataEvent;
FOnCreateStructure: TNotifyEvent;
FMomentumFaktor: Single;
FEpsilon: Single;
FRPROP: TRPROP;
FLastEpochIndx: Integer;
FStopType: TStopType;
FRunner: TNeuralNetRunner;
FMSEDifference: TMSEDifference;
FDropOutRateOfHiddenLayer: TArray<Single>;
{$IFDEF USEOPENCL}
FThresholdCL: TThresholdCL;
{$ENDIF}
procedure learnRun(InputData: TArray<Single>);
function GetNeuron(Pos: TPoint): TNeuron;
function GetConnection(N1, N2: TNeuron): TConnection;
function MSEcalc(Output: TArray<Single>): Single;
function MSE(CountData: Integer; DataEvent: TDataEvent): Single;
procedure DoMSE(MSE: Single; Epoche: Integer; var Stop: Boolean);
procedure Calc_Delta(Input, Output: TArray<Single>);
function GetOutputValues: TArray<Single>;
procedure Train_Basic(CountData: Integer; P: TFunc<Integer, Integer, TStopType>);
procedure DoData(DataEvent: TDataEvent; Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
procedure DoTrainData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
procedure DoTrainDataOut(Indx, OutCount: Integer; var OutData: TArray<Single>);
procedure DoValidData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
procedure DoTestData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
function GetInCount: Integer;
function GetOutCount: Integer;
procedure DoCreateStructure;
function GetMSEdifference: Single;
function GetMSEdifferenceCount: Integer;
procedure SetMSEdifference(const Value: Single);
procedure SetMSEdifferenceCount(const Value: Integer);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure CreateNetwork(NeuronsPerLayer: TArray<Integer>);
procedure Run(InputData: TArray<Single>);
procedure RandomWeights(MinWeight, MaxWeight: Single);
procedure RandomWeightsByNguyenWidrow(MinWeight, MaxWeight: Single);
procedure Train_BackPROP_Online(CountTrainData, CountValidData: Integer; MSE: Single);
procedure Train_BackPROP_Batch(CountTrainData, CountValidData: Integer; MSE: Single);
procedure Train_RPROP(CountTrainData, CountValidData: Integer; MSE: Single);
function ErrorOfTestData(CountTestData: Integer): Single;
function ErrorOfValidData(CountValidData: Integer): Single;
function ToNeurons: TArray<TNeuron>;
function ToConnections: TArray<TConnection>;
procedure CleanNeurons;
procedure CleanSmallWeights(const Epsilon: Single = 0);
procedure DefActFunction(LayerIndx: Integer; F: TThresholdType);
procedure SaveStructure(Filename: string);
procedure LoadStructure(Filename: string);
procedure RemoveConnection(C: TConnection);
procedure RemoveNeuron(N: TNeuron);
property InCount: Integer read GetInCount;
property OutCount: Integer read GetOutCount;
property MomentumFaktor: Single read FMomentumFaktor write FMomentumFaktor;
property Epsilon: Single read FEpsilon write FEpsilon;
property RPROP: TRPROP read FRPROP write FRPROP;
property Neuron[Pos: TPoint]: TNeuron read GetNeuron;
property OutputValues: TArray<Single> read GetOutputValues;
property Connection[N1, N2: TNeuron]: TConnection read GetConnection;
property Con: TConList read FConList;
property Neurons: TNeuronList read FNeurons;
property MSEdifference: Single read GetMSEdifference write SetMSEdifference;
property MSEdifferenceCount: Integer read GetMSEdifferenceCount write SetMSEdifferenceCount;
property LastEpochIndx: Integer read FLastEpochIndx;
property StopType: TStopType read FStopType;
property OnMSE: TMSEEvent read FOnMSE write FOnMSE;
property OnTrainData: TDataEvent read FOnTrainData write FOnTrainData;
property OnValidData: TDataEvent read FOnValidData write FOnValidData;
property OnTestData: TDataEvent read FOnTestData write FOnTestData;
property OnCreateStructure: TNotifyEvent read FOnCreateStructure write FOnCreateStructure;
property LossFunc: TErrorFunc read FLossFunc write FLossFunc;
property WeightErrorFunc: TWeightErrorFunc read FWeightErrorFunc write FWeightErrorFunc;
property WeightErrorLambda: Single read FWeightErrorLambda write FWeightErrorLambda;
property DropOutRateOfHiddenLayer: TArray<Single> read FDropOutRateOfHiddenLayer write FDropOutRateOfHiddenLayer;
end;
function ThresholdTypeOfNeurons(Neurons: TArray<TNeuron>): TArray<TThresholdType>;
implementation
function ThresholdTypeOfNeurons(Neurons: TArray<TNeuron>): TArray<TThresholdType>;
var
L: TList<TThresholdType>;
iNeuron: TNeuron;
begin
L := TList<TThresholdType>.Create;
try
for iNeuron in Neurons do
L.Add(iNeuron.ActFunc);
Result := L.ToArray;
finally
L.Free;
end;
end;
{ TNeuralNet }
constructor TNeuralNet.Create;
begin
inherited;
FConList := TConList.Create;
FNeurons := TNeuronList.Create;
FRunner := TNeuralNetRunner.Create(FConList, FNeurons);
FMSEDifference := TMSEDifference.Create;
FMomentumFaktor := 0.25;
FEpsilon := 0.1;
FRPROP.SetStandard;
FLossFunc := loss_MSE;
FWeightErrorFunc := nil;
FWeightErrorLambda := 0.000001;
FLastEpochIndx := 0;
{$IFDEF USEOPENCL}
FThresholdCL := TThresholdCL.Create;
FNeurons.ThresholdCL := FThresholdCL;
{$ENDIF}
end;
destructor TNeuralNet.Destroy;
begin
{$IFDEF USEOPENCL}
FThresholdCL.Free;
{$ENDIF}
FMSEDifference.Free;
FRunner.Free;
FNeurons.Free;
FConList.Free;
inherited;
end;
procedure TNeuralNet.CleanNeurons;
var
LC, C: Integer;
Cons: TArray<TConnection>;
i: Integer;
iCon: TConnection;
begin
LC := FNeurons.LayerCount;
repeat
C := FNeurons.Count;
for i := C - 1 downto 0 do
begin
if FNeurons[i].Pos.Y < LC - 1 then
begin
Cons := FConList.OutConsOfNeuron[FNeurons[i].Pos];
if Length(Cons) = 0 then
begin
for iCon in FConList.InConsOfNeuron[FNeurons[i].Pos] do
FConList.Remove(iCOn);
FNeurons.Delete(i);
FNeurons.CleanPositions;
end;
end;
if (FNeurons[i].Pos.Y > 0) and not FNeurons[i].IsBias then
begin
Cons := FConList.InConsOfNeuron[FNeurons[i].Pos];
if Length(Cons) = 0 then
begin
for iCon in FConList.OutConsOfNeuron[FNeurons[i].Pos] do
FConList.Remove(iCOn);
FNeurons.Delete(i);
FNeurons.CleanPositions;
end;
end;
end;
until FNeurons.Count = C;
end;
procedure TNeuralNet.CleanSmallWeights(const Epsilon: Single);
begin
FConList.CleanSmallWeights(Epsilon);
CleanNeurons;
end;
procedure TNeuralNet.Clear;
begin
FNeurons.Clear;
FConList.Clear;
end;
procedure TNeuralNet.DefActFunction(LayerIndx: Integer; F: TThresholdType);
begin
FNeurons.DefActFunction(LayerIndx, F);
end;
function TNeuralNet.ErrorOfTestData(CountTestData: Integer): Single;
var
tmp: TWeightErrorFunc;
begin
tmp := FWeightErrorFunc;
try
FWeightErrorFunc := nil;
Result := MSE(CountTestData, FOnTestData);
finally
FWeightErrorFunc := tmp;
end;
end;
function TNeuralNet.ErrorOfValidData(CountValidData: Integer): Single;
begin
Result := MSE(CountValidData, FOnValidData);
end;
procedure TNeuralNet.DoData(DataEvent: TDataEvent; Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
begin
SetLength(InData, InCount);
SetLength(OutData, OutCount);
DataEvent(Self, Indx, InCount, OutCount, InData, OutData);
end;
procedure TNeuralNet.DoValidData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
begin
DoData(FOnValidData, Indx, InCount, OutCount, InData, OutData);
end;
procedure TNeuralNet.DoTestData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
begin
DoData(FOnTestData, Indx, InCount, OutCount, InData, OutData);
end;
procedure TNeuralNet.DoTrainData(Indx, InCount, OutCount: Integer; var InData, OutData: TArray<Single>);
begin
DoData(FOnTrainData, Indx, InCount, OutCount, InData, OutData);
end;
procedure TNeuralNet.DoTrainDataOut(Indx, OutCount: Integer; var OutData: TArray<Single>);
var
InData: TArray<Single>;
begin
SetLength(InData, 0);
SetLength(OutData, OutCount);
FOnTrainData(Self, Indx, 0, OutCount, InData, OutData);
end;
procedure TNeuralNet.DoMSE(MSE: Single; Epoche: Integer; Var Stop: Boolean);
begin
Stop := False;
if Assigned(FOnMSE) then
FOnMSE(Self, MSE, Epoche, Stop);
end;
function TNeuralNet.GetConnection(N1, N2: TNeuron): TConnection;
begin
Result := FConList.ConsOfNeurons(N1, N2);
end;
function TNeuralNet.GetInCount: Integer;
begin
if Neurons.LayerCount > 1 then
Result := FNeurons.CountInput
else
Result := 0;
end;
function TNeuralNet.GetMSEdifference: Single;
begin
Result := FMSEDifference.Difference;
end;
function TNeuralNet.GetMSEdifferenceCount: Integer;
begin
Result := FMSEDifference.DifferenceCount;
end;
function TNeuralNet.GetOutCount: Integer;
var
c: Integer;
begin
c := Neurons.LayerCount;
if c > 1 then
Result := FNeurons.CountOutput
else
Result := 0;
end;
function TNeuralNet.GetNeuron(Pos: TPoint): TNeuron;
begin
Result := FNeurons.Neuron[Pos];
end;
function TNeuralNet.GetOutputValues: TArray<Single>;
begin
Result := FNeurons.Output;
end;
{$IFDEF USEOPENCL}
procedure TNeuralNet.learnRun(InputData: TArray<Single>);
var
iNeuron: TNeuron;
iLayer: Integer;
DataIn: TArray<Single>;
DataThreshold: TArray<Integer>;
NN: TArray<TNeuron>;
i, c: Integer;
begin
for iNeuron in FNeurons.LayerNeurons[0] do
iNeuron.SetValue(InputData[iNeuron.Pos.X]);
for iLayer := 1 to FConList.LayerCount - 1 do
begin
NN := FNeurons.LayerNeurons[iLayer];
c := Length(NN);
SetLength(DataIn, c);
SetLength(DataThreshold, c);
for i := 0 to c - 1 do
if NN[i].IsBias then
begin
DataIn[i] := 0;
DataThreshold[i] := 1;
end
else
begin
DataIn[i] := FConList.SumValueXWeights(NN[i].Pos);
DataThreshold[i] := Ord(NN[i].ActFunc);
end;
FNeurons.DataToNeuronsCL(iLayer, DataIn, DataThreshold);
end;
end;
{$ELSE}
procedure TNeuralNet.learnRun(InputData: TArray<Single>);
var
iNeuron: TNeuron;
iLayer: Integer;
begin
for iNeuron in FNeurons.LayerNeurons[0] do
iNeuron.SetValue(InputData[iNeuron.Pos.X]);
for iLayer := 1 to FNeurons.LayerCount - 1 do
for iNeuron in FNeurons.LayerNeurons[iLayer] do
iNeuron.SetValue(FConList.SumValueXWeights(iNeuron.Pos));
end;
{$ENDIF}
function TNeuralNet.MSE(CountData: Integer; DataEvent: TDataEvent): Single;
var
i, Cin, Cout: Integer;
_Input, _Output: TArray<Single>;
begin
if not Assigned(DataEvent) then
DataEvent := FOnValidData;
Cin := FNeurons.CountInput;
Cout := FNeurons.CountOutput;
Result := 0;
for i := 0 to CountData - 1 do
begin
DoData(DataEvent, i, Cin, Cout, _Input, _Output);
Run(_Input);
Result := Result + MSEcalc(_Output);
end;
Result := Result / CountData;
end;
function TNeuralNet.MSEcalc(Output: TArray<Single>): Single;
begin
Result := FLossFunc(FNeurons.OutValues, Output);
if Assigned(FWeightErrorFunc) then
Result := Result + FWeightErrorLambda * FWeightErrorFunc(FConList.Weights);
end;
procedure TNeuralNet.RandomWeights(MinWeight, MaxWeight: Single);
begin
FConList.RandomWeights(MinWeight, MaxWeight);
end;
procedure TNeuralNet.RandomWeightsByNguyenWidrow(MinWeight, MaxWeight: Single);
var
beta: Single;
iNeuron: TNeuron;
begin
FConList.RandomWeights(MinWeight, MaxWeight);
if FNeurons.CountHidden > 0 then
begin
beta := FNeurons.BetaByNguyenWidrow;
for iNeuron in FNeurons.NeuronsHidden do
FConList.SetWeightsByNguyenWidrow(iNeuron, beta);
for iNeuron in FNeurons.NeuronsOutput do
FConList.SetWeightsByNguyenWidrow(iNeuron, beta);
end;
end;
procedure TNeuralNet.RemoveConnection(C: TConnection);
begin
FConList.Remove(C);
CleanNeurons;
end;
procedure TNeuralNet.RemoveNeuron(N: TNeuron);
begin
if (N.Pos.Y > 0) and (N.Pos.Y < FNeurons.LayerCount - 1) then
begin
FNeurons.Remove(N);
FNeurons.CleanPositions;
CleanNeurons;
end;
end;
procedure TNeuralNet.DoCreateStructure;
begin
if Assigned(FOnCreateStructure) then
FOnCreateStructure(Self);
end;
procedure TNeuralNet.Run(InputData: TArray<Single>);
begin
FRunner.Run(InputData);
end;
procedure TNeuralNet.SaveStructure(Filename: string);
var
Loader: TNeuralNetLoader;
begin
Loader := TNeuralNetLoader.Create(FNeurons, FConList);
try
Loader.SaveStructure(Filename);
finally
Loader.Free;
end;
end;
procedure TNeuralNet.SetMSEdifference(const Value: Single);
begin
FMSEDifference.Difference := Value;
end;
procedure TNeuralNet.SetMSEdifferenceCount(const Value: Integer);
begin
FMSEDifference.DifferenceCount := Value;
end;
procedure TNeuralNet.LoadStructure(Filename: string);
var
Loader: TNeuralNetLoader;
begin
Loader := TNeuralNetLoader.Create(FNeurons, FConList);
try
Loader.LoadStructure(Filename);
finally
Loader.Free;
end;
DoCreateStructure;
end;
function TNeuralNet.ToConnections: TArray<TConnection>;
begin
Result := FConList.ToArray;
end;
procedure TNeuralNet.Calc_Delta(Input, Output: TArray<Single>);
var
c: Integer;
iLayer: Integer;
iNeuron: TNeuron;
begin
learnRun(Input);
c := FConList.LayerCount;
iLayer := c - 1;
for iNeuron in FNeurons.LayerNeurons[iLayer] do
iNeuron.Delta := iNeuron.DeriveValue * (Output[iNeuron.Pos.X] - iNeuron.OutValue);
for iLayer := c - 2 downto 1 do
for iNeuron in FNeurons.LayerNeurons[iLayer] do
iNeuron.Delta := iNeuron.DeriveValue * FConList.DeltaOfNeuron(iNeuron.Pos);
end;
function TNeuralNet.ToNeurons: TArray<TNeuron>;
begin
Result := FNeurons.ToArray;
end;
procedure TNeuralNet.Train_Basic(CountData: Integer; P: TFunc<Integer, Integer, TStopType>);
var
Cin, Cout: Integer;
_Input, _Output: TArray<Single>;
i, epochIndx: Integer;
Stop: TStopType;
begin
Cin := FNeurons.CountInput;
Cout := FNeurons.CountOutput;
FConList.Reset;
epochIndx := 0;
Stop := stopNo;
repeat
FConList.Clear_Epoch;
FNeurons.DroppingOut(FDropOutRateOfHiddenLayer);
i := 0;
repeat
DoTrainData(i, Cin, Cout, _Input, _Output);
Calc_Delta(_Input, _Output);
Stop := P(i, epochIndx);
Inc(i);
until (Stop <> stopNo) or (i > CountData - 1);
Inc(epochIndx);
until (Stop <> stopNo);
FStopType := Stop;
FLastEpochIndx := epochIndx - 1;
end;
procedure TNeuralNet.Train_BackPROP_Batch(CountTrainData, CountValidData: Integer; MSE: Single);
begin
FMSEDifference.Start(MSE);
Train_Basic(CountTrainData,
function(Indx, EpochIndx: Integer): TStopType
var
epochMSE: Single;
IsUserStop: Boolean;
begin
FConList.SumGradient;
if (Indx mod (CountTrainData - 1) = 0) and (Indx > 0) then
begin
FConList.AddWeights_BackPROP_Batch(FEpsilon, FMomentumFaktor);
epochMSE := Self.MSE(CountValidData, FOnValidData);
DoMSE(epochMSE, EpochIndx, IsUserStop);
if IsUserStop then
Result := stopUserBreak
else if Abs(epochMSE) < MSE then
Result := stopErrorAccomplished
else if FMSEDifference.IsDifference(epochMSE) then
Result := stopNoErrorDifference
else
Result := stopNo;
end
else
Result := stopNo;
end);
end;
procedure TNeuralNet.Train_BackPROP_Online(CountTrainData, CountValidData: Integer; MSE: Single);
var
epochMSE: Single;
Cout: Integer;
begin
Cout := FNeurons.CountOutput;
FMSEDifference.Start(MSE);
epochMSE := 0;
Train_Basic(CountTrainData,
function(Indx, EpochIndx: Integer): TStopType
var
_Output: TArray<Single>;
IsUserStop: Boolean;
begin
FConList.AddWeights_BackPROP_Online(FEpsilon, FMomentumFaktor);
DoTrainDataOut(Indx, Cout, _Output);
epochMSE := epochMSE + MSEcalc(_Output);
if (Indx mod (CountTrainData - 1) = 0) and (Indx > 0) then
begin
epochMSE := epochMSE / CountTrainData;
DoMSE(epochMSE, EpochIndx, IsUserStop);
if IsUserStop then
Result := stopUserBreak
else if Abs(epochMSE) < MSE then
Result := stopErrorAccomplished
else if FMSEDifference.IsDifference(epochMSE) then
Result := stopNoErrorDifference
else
Result := stopNo;
end
else
Result := stopNo;
end);
end;
procedure TNeuralNet.Train_RPROP(CountTrainData, CountValidData: Integer; MSE: Single);
begin
FMSEDifference.Start(MSE);
Train_Basic(CountTrainData,
function(Indx, EpochIndx: Integer): TStopType
var
epochMSE: Single;
IsUserStop: Boolean;
begin
FConList.SumGradient;
if (Indx mod (CountTrainData - 1) = 0) and (Indx > 0) then
begin
FConList.AddWeights_RPROP(FRPROP);
epochMSE := Self.MSE(CountValidData, FOnValidData);
DoMSE(epochMSE, EpochIndx, IsUserStop);
if IsUserStop then
Result := stopUserBreak
else if Abs(epochMSE) < MSE then
Result := stopErrorAccomplished
else if FMSEDifference.IsDifference(epochMSE) then
Result := stopNoErrorDifference
else
Result := stopNo;
end
else
Result := stopNo;
end);
end;
procedure TNeuralNet.CreateNetwork(NeuronsPerLayer: TArray<Integer>);
begin
FConList.CreateNetwork(NeuronsPerLayer);
FNeurons.InsertNeurons(FConList.ToNeurons);
DoCreateStructure;
end;
{ TConList }
procedure TConList.AddWeights_BackPROP_Batch(Epsilon, MomentumFaktor: Single);
var
iCon: TConnection;
begin
for iCon in Self do
iCon.AddWeight_BackPROP_Batch(Epsilon, MomentumFaktor);
end;
procedure TConList.AddWeights_BackPROP_Online(Epsilon, MomentumFaktor: Single);
var
iCon: TConnection;
begin
for iCon in Self do
iCon.AddWeight_BackPROP_Online(Epsilon, MomentumFaktor);
end;
procedure TConList.SetWeightsByNguyenWidrow(N: TNeuron; beta: Single);
var
iCon: TConnection;
EuclideanNorm: Single;
begin
EuclideanNorm := Sqrt(SumSqrWeights(N));
for iCon in GetInConsOfNeuron(N.Pos) do
iCon.Weight := (beta * iCon.Weight) / EuclideanNorm;
end;
procedure TConList.SumGradient;
var
iCon: TConnection;
begin
for iCon in Self do
iCon.SumGradient;
end;
function TConList.SumSqrWeights(N: TNeuron): Single;
var
iCon: TConnection;
begin
Result := 0;
for iCon in GetInConsOfNeuron(N.Pos) do
Result := Result + iCon.Weight * iCon.Weight;
end;
procedure TConList.AddWeights_RPROP(RPROP: TRPROP);
var
iCon: TConnection;
begin
for iCon in Self do
iCon.AddWeight_RPROP(RPROP);
end;
procedure TConList.Reset;
var
iCon: TConnection;
begin
for iCon in Self do
iCon.Clear;
end;
procedure TConList.CleanSmallWeights(const Epsilon: Single);
var
i: Integer;
begin
for i := Count - 1 downto 0 do
if IsZero(Self[i].Weight, Epsilon) then
Delete(i);
end;
procedure TConList.Clear_Epoch;
var
iCon: TConnection;
begin
for iCon in Self do
iCon.Clear_Epoch;
end;
function TConList.ConsOfNeurons(N1, N2: TNeuron): TConnection;
var
iCon: TConnection;
begin
for iCon in Self do
if (iCon.FromNeuron = N1) and (iCon.ToNeuron = N2) or (iCon.FromNeuron = N2) and (iCon.ToNeuron = N1) then
Exit(iCon);
Result := nil;
end;
procedure TConList.CreateNetwork(NeuronsPerLayer: TArray<Integer>);
var
i, ii: Integer;
iLayer: Integer;
con: TConnection;
iNeuron: TNeuron;
begin
Clear;
if IsNeuronsPerLayerValid(NeuronsPerLayer) then
begin
for iLayer := 0 to Length(NeuronsPerLayer) - 2 do
begin
for i := 0 to NeuronsPerLayer[iLayer] do
begin
if (i = NeuronsPerLayer[iLayer]) then
iNeuron := TNeuron.Create(iLayer, i, True)
else if (iLayer = 0) then
iNeuron := TNeuron.Create(iLayer, i)
else
iNeuron := GetNeuron(TPoint.Create(i, iLayer));
for ii := 0 to NeuronsPerLayer[iLayer + 1] - 1 do
begin
con := TConnection.Create;
con.FromNeuron := iNeuron;