-
Notifications
You must be signed in to change notification settings - Fork 10
/
Esempi.pas
2537 lines (2096 loc) · 91.9 KB
/
Esempi.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
unit Esempi;
{$REGION 'Licence'}
(*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************)
{$ENDREGION}
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,rtti, System.Math, System.Generics.Collections,
spring,
TF4D.Core.CApi,
Numpy,
Tensorflow,
TensorFlow.DApiBase,
TensorFlow.DApi,
Tensorflow.Utils,
TensorFlow.Ops,
TensorFlow.Core,
TensorFlow.Slice,
Keras.Core,
Keras.KerasApi,
keras.LayersApi,
keras.Models,
Keras.Layer,
TensorFlow.Variable,
TensorFlow.Tensor,
NumPy.NDArray,
Numpy.Axis;
type
LinearRegression = class
private
public
training_epochs : Integer;
learning_rate : Single;
display_step : Integer;
n_samples : Integer;
train_X, train_Y: NDArray;
constructor Create;
destructor Destroy; override;
procedure PrepareData;
function Run(mmo1: TMemo): Boolean;
end;
LinearRegressionEager = class
private
public
training_epochs : Integer;
training_steps : Integer;
learning_rate : Single;
display_step : Integer;
n_samples : Integer;
train_X, train_Y: TNDArray;
constructor Create;
destructor Destroy; override;
procedure PrepareData;
function Run(mmo1: TMemo): Boolean;
end;
EagerModeTestBase = class
constructor Create;
procedure TestInit;
function Equal(f1: Single; f2: Single): Boolean; overload;
function Equal(f1: TArray<Single>; f2: TArray<Single>): Boolean; overload;
function Equal(f1: TArray<Double>; f2: TArray<Double>): Boolean; overload;
procedure clip_by_global_norm;
procedure NeuralNetworkTest_l2_loss;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/top_k_categorical_accuracy
/// </summary>
procedure top_k_categorical_accuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/TopKCategoricalAccuracy
/// </summary>
procedure TopKCategoricalAccuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Recall
/// </summary>
procedure Recall;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Precision
/// </summary>
procedure Precision;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/BinaryAccuracy
/// </summary>
procedure BinaryAccuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/CategoricalAccuracy
/// </summary>
procedure CategoricalAccuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/CategoricalCrossentropy
/// </summary>
procedure CategoricalCrossentropy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Accuracy
/// </summary>
procedure Accuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/CosineSimilarity
/// </summary>
procedure CosineSimilarity;
/// <summary>
/// https://www.tensorflow.org/addons/api_docs/python/tfa/metrics/HammingLoss
/// </summary>
procedure HammingLoss;
/// <summary>
/// https://www.tensorflow.org/addons/api_docs/python/tfa/metrics/F1Score
/// </summary>
procedure F1Score;
/// <summary>
/// https://www.tensorflow.org/addons/api_docs/python/tfa/metrics/FBetaScore
/// </summary>
procedure FBetaScore;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/SparseCategoricalAccuracy
/// </summary>
procedure SparseCategoricalAccuracy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/SparseCategoricalCrossentropy
/// </summary>
procedure SparseCategoricalCrossentropy;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/SparseTopKCategoricalAccuracy
/// </summary>
procedure SparseTopKCategoricalAccuracy;
end;
PreprocessingTests = class(EagerModeTestBase)
private
texts : TArray<string>;
tokenized_texts : TArray<TArray<string>>;
processed_texts : TArray<string>;
OOV : string;
public
constructor Create;
destructor Destroy; override;
procedure TokenizeWithNoOOV;
procedure TokenizeWithNoOOV_Tkn;
procedure TokenizeWithOOV;
procedure TokenizeWithOOV_Tkn;
procedure TokenizeTextsToSequences;
procedure TokenizeTextsToSequences_Tkn;
procedure PadSequencesWithDefaults;
procedure TextToMatrixBinary;
procedure TextToMatrixFrequency;
end;
/// <summary>
/// https://www.tensorflow.org/versions/r2.3/api_docs/python/tf/keras/layers
/// </summary>
LayersTest = class(EagerModeTestBase)
public
procedure AveragePooling2D;
procedure InputLayer;
procedure Sequential;
procedure Functional;
/// <summary>
/// Custom layer test, used in Dueling DQN
/// </summary>
procedure TensorFlowOpLayer;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding
/// </summary>
procedure Embedding;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense
/// </summary>
procedure Dense;
procedure EinsumDense;
procedure SimpleRNN;
procedure Resizing;
procedure LayerNormalization;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/layers/Normalization
/// </summary>
procedure Normalization;
end;
ActivationFunctionTest = class(EagerModeTestBase)
public
a : TFTensor;
constructor Create;
procedure Sigmoid;
procedure ReLU;
procedure TanH;
end;
BitwiseApiTest = class(EagerModeTestBase)
public
constructor Create;
procedure BitwiseAnd;
procedure BitwiseOr;
procedure BitwiseXOR;
procedure Invert;
procedure LeftShift;
procedure RightShift;
end;
ConstantTest = class(EagerModeTestBase)
public
constructor Create;
procedure ScalarConst;
procedure ZerosConst;
procedure OnesConst;
procedure OnesToHalves;
procedure NDimConst;
procedure Multiply;
procedure Reshape;
end;
LinalgTest = class(EagerModeTestBase)
private
public
constructor Create;
procedure Einsum;
procedure EyeTest;
procedure GlobalNorm;
procedure LSTSQ;
procedure Tensordot;
end;
Keras_Layers_test = class(EagerModeTestBase)
public
constructor Create;
procedure ActivationTest_LeakyReLU;
procedure ActivationTest_ELU;
procedure ActivationTest_SELU;
procedure ActivationTest_Softmax;
procedure ActivationTest_Softplus;
procedure ActivationTest_Softsign;
procedure ActivationTest_Exponential;
procedure ActivationTest_HardSigmoid;
procedure ActivationTest_Swish;
/// <summary>
/// https://www.tensorflow.org/addons/api_docs/python/tfa/activations/mish
/// </summary>
procedure ActivationTest_Mish;
//
procedure Attention_BaseDenseAttention;
procedure Attention_Attention;
procedure Attention_MultiHeadAttention;
//
procedure BasicConv1D;
procedure BasicConv1D_ksize;
procedure BasicConv1D_ksize_same;
procedure BasicConv1D_ksize_strides;
procedure BasicConv1D_ksize_dilations;
procedure BasicConv1D_ksize_dilation_same;
//
procedure BasicConv2D;
procedure BasicConv2D_ksize;
procedure BasicConv2D_ksize_same;
procedure BasicConv2D_ksize_strides;
procedure BasicConv2D_ksize_dilations;
procedure BasicConv2D_ksize_dilation_same;
//
procedure Cropping1D;
procedure Cropping2D;
procedure Cropping3D;
//
procedure Concatenate;
//
procedure ZeroPadding2D;
procedure UpSampling2D;
procedure Reshape;
procedure Permute;
/// <summary>
/// https://www.tensorflow.org/api_docs/python/tf/keras/layers/CategoryEncoding
/// </summary>
procedure CategoryEncoding;
end;
Keras_Losses_test = class
public
// CosineSimilarity
y_true_float : TNDArray;
y_pred_float : TNDArray;
// Huber
y_true_float_H : TNDArray;
y_pred_float_H : TNDArray;
// LogCosh
y_true_float_L : TNDArray;
y_pred_float_L : TNDArray;
// MeanAbsoluteError
y_true_float_MAE : TNDArray;
y_pred_float_MAE : TNDArray;
constructor Create;
// https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy
procedure BinaryCrossentropy;
// https://keras.io/api/losses/regression_losses/
procedure CosineSimilarity_Default;
procedure CosineSimilarity_Sample_Weight;
procedure CosineSimilarity_SUM;
procedure CosineSimilarity_None;
// https://keras.io/api/losses/regression_losses/#meansquarederror-class
procedure Huber_Default;
procedure Huber_Sample_Weight;
procedure Huber_SUM;
procedure Huber_None;
// https://keras.io/api/losses/regression_losses/#meansquarederror-class
procedure LogCosh_Default;
procedure LogCosh_Sample_Weight;
procedure LogCosh_SUM;
procedure LogCosh_None;
// https://keras.io/api/losses/regression_losses/
procedure MeanAbsoluteError_Default;
procedure MeanAbsoluteError_Sample_Weight;
procedure MeanAbsoluteError_SUM;
procedure MeanAbsoluteError_None;
/// <summary>
/// https://www.tensorflow.org/addons/api_docs/python/tfa/losses/SigmoidFocalCrossEntropy
/// </summary>
procedure SigmoidFocalCrossEntropy;
end;
procedure On_Epoch_Begin(msg: string);
procedure On_Train_Batch_Begin(msg: string);
procedure On_End_Summary(msg: string);
procedure Earltstopping;
implementation
uses untMain,
DUnitX.TestFramework,
Keras.LossFunc,
Keras.Utils,
keras.Preprocessing,
keras.Callbacks,
Tensorflow.Proto;
procedure On_Epoch_Begin(msg: string);
begin
frmMain.mmo1.Lines.Add(msg);
frmMain.mmo1.Lines.Add('');
end;
procedure On_Train_Batch_Begin(msg: string);
begin
frmMain.mmo1.Lines[frmMain.mmo1.Lines.Count - 1] := msg;
end;
procedure On_End_Summary(msg: string);
begin
frmMain.mmo1.Lines.Add(msg)
end;
// Because loading the weight variable into the model has not yet been implemented,
// so you'd better not set patience too large, because the weights will equal to the last epoch's weights.
procedure Earltstopping;
var
lst_Layers : TList<ILayer>;
layers : ILayersApi;
input_shape: TFShape;
earlystop : ICallback;
begin
layers := tf.keras.layers;
lst_Layers := TList<ILayer>.Create;
try
input_shape := [32, 32, 3];
lst_Layers.Add( layers.Rescaling(1.0 / 255, 0 ,@input_shape ) );
lst_Layers.Add( layers.Conv2D(32, 3, 'relu', 'same' ) );
lst_Layers.Add( layers.MaxPooling2D );
lst_Layers.Add( layers.Flatten );
lst_Layers.Add( layers.Dense(128, tf.keras.activations.Relu) );
lst_Layers.Add( layers.Dense(10) );
var mModel := tf.keras.Sequential(lst_Layers);
mModel.OnEpochBegin := On_Epoch_Begin;
mModel.OnTrainBatchBegin := On_Train_Batch_Begin;
mModel.OnEndSummary := On_End_Summary;
mModel.summary;
mModel.compile(tf.keras.optimizers.RMSprop(1e-3), tf.keras.losses.SparseCategoricalCrossentropy('', '', true), [ 'acc' ]);
var num_epochs := 3;
var batch_size := 8;
var dp := KerasInterface(tf.keras).datasets.cifar10.load_data;
var x_train := dp.Train.Value1;
var y_train := dp.Train.Value2;
var x_test := dp.Test.Value1;
var y_test := dp.Test.Value2;
x_train := NDArray(x_train) / Single(255.0);
// define a CallbackParams first, the parameters you pass al least contain Model and Epochs.
var callback_parameters := CallbackParams.Create;
callback_parameters.mModel := mModel;
callback_parameters.Epochs := num_epochs;
// define your earlystop
earlystop := EarlyStopping.Create(callback_parameters, 'accuracy');
// define a callbcaklist, then add the earlystopping to it.
var callbacks := TList<ICallback>.Create;
callbacks.add(earlystop);
mModel.fit(x_train[[Slice.Create(0, 2000)]], y_train[[Slice.Create(0, 2000)]], batch_size, num_epochs,callbacks);
finally
lst_Layers.free;
end;
end;
{ LinearRegression }
constructor LinearRegression.Create;
begin
training_epochs := 1000;
// Parameters
learning_rate := 0.01;
display_step := 50;
end;
destructor LinearRegression.Destroy;
begin
inherited;
end;
procedure LinearRegression.PrepareData;
begin
train_X := np.np_array<Single>([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1]);
train_Y := np.np_array<Single>([1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3]);
n_samples := train_X.shape[0];
end;
function LinearRegression.Run(mmo1: TMemo): Boolean;
begin
tf.compat.v1.disable_eager_execution;
PrepareData;
// tf Graph Input
var X : TTensor := tf.placeholder(tf.float32_t);
var Y : TTensor := tf.placeholder(tf.float32_t);
// Set model weights
// We can set a fixed init value in order to debug
// var rnd1 = rng.randn<float>();
// var rnd2 = rng.randn<float>();
var W := tf.Variable(Single(-0.06), 'weight');
var b := tf.Variable(Single(-0.73), 'bias');
// Construct a linear model
var pred : TTensor := tf.add(tf.multiply(X, W), b);
//var pred1 := (X * W) + b; OK
// Mean squared error
var cost := TTensor(tf.reduce_sum(tf.pow(pred - Y, 2.0))) / (2.0 * n_samples) ;
// Gradient descent
// Note, minimize() knows to modify W and b because Variable objects are trainable=True by default
var optimizer := tf.train.GradientDescentOptimizer(learning_rate).minimize(cost);
// Initialize the variables (i.e. assign their default value)
var init := tf.global_variables_initializer;
// Start training
var sess := tf.Session;
// Run the initializer
sess.run(init);
// Fit all training data
var epoch: Integer ;
for epoch := 0 to training_epochs -1 do
begin
for var zItem in TUtils.zip<Single>(train_X, train_Y) do
begin
var v_x : Single := zItem.Value1 ;
var v_y : Single := zItem.Value2 ;
sess.run(optimizer, [ Tuple<TValue,TValue>.Create(X, v_x), Tuple<TValue,TValue>.Create(Y, v_y) ]);
end;
// Display logs per epoch step
if ((epoch + 1) mod display_step) = 0 then
begin
var fc : Single := NDArray(sess.run(cost, [ Tuple<TValue,TValue>.Create(X, train_X), Tuple<TValue,TValue>.Create(Y, train_Y) ]));
var fW : Single := NDArray(sess.run( TResourceVariable(W) ));
var fb : Single := NDArray(sess.run( TResourceVariable(b) ));
mmo1.Lines.Add( Format('Epoch: %d cost=%.9f + "W=%.9f b=%.9f"',[epoch + 1,fc, fW,fb]) );
end;
end;
mmo1.Lines.Add('Optimization Finished!');
var training_cost : Single := NDArray(sess.run(cost, [ Tuple<TValue,TValue>.Create(X, train_X), Tuple<TValue,TValue>.Create(Y, train_Y) ]));
var fW : Single := NDArray(sess.run( TResourceVariable(W) ));
var fb : Single := NDArray(sess.run( TResourceVariable(b) ));
mmo1.Lines.Add('');
mmo1.Lines.Add(Format('Training cost=%.9f W=%.9f b=%.9f',[training_cost, fW, fb]));
// Testing example
var test_X : NDArray := np.np_array( TArray<Single>.Create(6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1) );
var test_Y : NDArray := np.np_array( TArray<Single>.Create(1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03) );
mmo1.Lines.Add('Testing... (Mean square loss Comparison)');
var t_cost := TTensor(tf.reduce_sum(tf.pow(pred - Y, 2.0))) / (2.0 * test_X.shape[0]) ;
var testing_cost : Single := NDArray(sess.run(t_cost, [ Tuple<TValue,TValue>.Create(X, test_X), Tuple<TValue,TValue>.Create(Y, test_Y) ]));
mmo1.Lines.Add('');
mmo1.Lines.Add( Format('Testing cost=%.9f',[testing_cost]) );
var diff := Abs( training_cost - testing_cost);
mmo1.Lines.Add( Format('Absolute mean square loss difference: %.9f',[diff]) );
mmo1.Lines.Add('');
Result := diff < 0.01;
end;
{ EagerModeTestBase }
function EagerModeTestBase.Equal(f1, f2: TArray<Single>): Boolean;
begin
var ret: Boolean := false;
var tolerance : Single := 000001;
for var i := 0 to Length(f1) - 1 do
begin
ret := Abs(f1[i] - f2[i]) <= tolerance;
if not ret then
break;
end;
Result := ret;
end;
function EagerModeTestBase.Equal(f1, f2: Single): Boolean;
begin
var tolerance : Single := 000001;
Result := Abs(f1 - f2) <= tolerance;
end;
procedure EagerModeTestBase.clip_by_global_norm;
begin
var t_list := TFTensors.Create( [ tf.constant( TArray<Single>.Create( 1, 2, 3, 4 ) ), tf.constant( TArray<Single>.Create( 5, 6, 7, 8 ) ) ] );
var clip_norm : Single := 0.8;
var tNorm := tf.clip_by_global_norm(t_list.ToArray, clip_norm);
var res := tNorm.Value1;
var norm := tNorm.Value2;
var expected : TArray<Single> := [ 0.0560112074, 0.112022415, 0.16803363, 0.22404483 ];
var actual := res[0].ToArray<Single>;
Assert.IsTrue(Equal(expected, actual));
expected := [ 0.28005603, 0.336067259, 0.392078459, 0.448089659 ];
actual := res[1].ToArray<Single>;
Assert.IsTrue(Equal(expected, actual));
var nNorm : NDArray := norm.numpy;
Assert.AreEqual<Single>( nNorm, 14.282857);
end;
procedure EagerModeTestBase.NeuralNetworkTest_l2_loss;
begin
var vA : TArray< TArray<Single> > := [[1, 2, 3, 4],[5, 6, 7, 8]];
var x := tf.Variable(np.np_array(vA), '',tf.float32_t);
var l2 := tf.nn.l2_loss(x.totensor);
var l2_numpy : NDArray := l2.numpy;
Assert.AreEqual<Single>(l2_numpy, 102);
end;
constructor EagerModeTestBase.Create;
begin
TestInit;
end;
function EagerModeTestBase.Equal(f1, f2: TArray<Double>): Boolean;
begin
var ret: Boolean := false;
var tolerance : Single := 000000000000001;
for var i := 0 to Length(f1) - 1 do
begin
ret := Abs(f1[i] - f2[i]) <= tolerance;
if not ret then
break;
end;
Result := ret;
end;
procedure EagerModeTestBase.TestInit;
begin
if not tf.executing_eagerly then
tf.enable_eager_execution;
tf.Context.ensure_initialized;
end;
procedure EagerModeTestBase.top_k_categorical_accuracy;
begin
var y_true := np.np_array< TArray<Integer>>([[ 0, 0, 1 ], [ 0, 1, 0 ]]);
var y_pred := np.np_array< TArray<Single>>([[ 0.1, 0.9, 0.8 ], [ 0.05, 0.95, 0 ]]);
var m := tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, 3);
var expected : TArray<Single> := [ 1, 1 ];
var actual := m.numpy.ToArray<Single>;
Assert.IsTrue(TUtils.SequenceEqual<Single>(expected, actual));
end;
procedure EagerModeTestBase.TopKCategoricalAccuracy;
begin
var y_true := np.np_array< TArray<Integer>>([[ 0, 0, 1 ], [ 0, 1, 0 ]]);
var y_pred := np.np_array< TArray<Single>>([[ 0.1, 0.9, 0.8 ], [ 0.05, 0.95, 0 ]]);
var m := tf.keras.metrics.TopKCategoricalAccuracy(1);
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.5);
m.reset_states;
var weights := np.np_array< Single >([ 0.7, 0.3]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.3);
end;
procedure EagerModeTestBase.Recall;
begin
var y_true := np.np_array< Integer >([ 0, 1, 1, 1 ]);
var y_pred := np.np_array< Integer >([ 1, 0, 1, 1 ]);
var m := tf.keras.metrics.Recall;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.6666667);
m.reset_states;
var weights := np.np_array< Single >([ 0, 0, 1, 0 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 1);
end;
procedure EagerModeTestBase.Precision;
begin
var y_true := np.np_array< Integer >([ 0, 1, 1, 1 ]);
var y_pred := np.np_array< Integer >([ 1, 0, 1, 1 ]);
var m := tf.keras.metrics.Precision;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.6666667);
m.reset_states;
var weights := np.np_array< Single >([ 0, 0, 1, 0 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 1);
// With top_k=2, it will calculate precision over y_true[:2]
// and y_pred[:2]
y_true := np.np_array< Integer >([ 0, 0, 1, 1 ]);
y_pred := np.np_array< Integer >([ 1, 1, 1, 1 ]);
m := tf.keras.metrics.Precision(0.5, 2);
m.update_state(y_true, y_pred);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0);
// With top_k=4, it will calculate precision over y_true[:4]
// and y_pred[:4]
y_true := np.np_array< Integer >([ 0, 0, 1, 1 ]);
y_pred := np.np_array< Integer >([ 1, 1, 1, 1 ]);
m := tf.keras.metrics.Precision(0.5, 4);
m.update_state(y_true, y_pred);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.5);
end;
procedure EagerModeTestBase.BinaryAccuracy;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 1 ], [ 1 ],[ 0 ], [ 0 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [0.98 ], [ 1 ], [ 0 ], [ 0.6 ] ]);
var m := tf.keras.metrics.BinaryAccuracy;
var weights := np.np_array< Single >([ 1, 0, 0, 1 ]);
m.update_state(y_true, y_pred, weights);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.5);
end;
procedure EagerModeTestBase.CategoricalAccuracy;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 0, 0, 1 ], [ 0, 1, 0 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.1, 0.9, 0.8 ], [ 0.05, 0.95, 0 ] ]);
var m := tf.keras.metrics.CategoricalAccuracy;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.5);
m.reset_states;
var weights := np.np_array< Single >([ 0.7, 0.3 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.3);
end;
procedure EagerModeTestBase.CategoricalCrossentropy;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 0, 1, 0 ], [ 0, 0, 1 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.05, 0.95, 0 ], [ 0.1, 0.8, 0.1 ] ]);
var m := tf.keras.metrics.CategoricalCrossentropy;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,1.1769392);
m.reset_states;
var weights := np.np_array< Single >([ 0.3, 0.7 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 1.6271976);
end;
procedure EagerModeTestBase.Accuracy;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0 ], [ 2 ], [ 3 ], [ 4 ] ]);
var m := tf.keras.metrics.Accuracy;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.75);
m.reset_states;
var weights := np.np_array< Single >([ 1, 1, 0, 0 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.5);
end;
procedure EagerModeTestBase.CosineSimilarity;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 0, 1 ], [ 1, 1 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 1, 0 ], [ 1, 1 ] ]);
var asse : TAxis := 1;
var m := tf.keras.metrics.CosineSimilarity('cosine_similarity', TF_FLOAT, @asse);
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.49999997);
m.reset_states;
var weights := np.np_array< Single >([ 0.3, 0.7 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.6999999);
end;
procedure EagerModeTestBase.SparseCategoricalAccuracy;
begin
var y_true := np.np_array< Integer >([ 2, 1 ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.1, 0.6, 0.3 ], [ 0.05, 0.95, 0 ] ]);
var m := tf.keras.metrics.SparseCategoricalAccuracy;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.5);
m.reset_states;
var weights := np.np_array< Single >([ 0.7, 0.3 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.3);
end;
procedure EagerModeTestBase.SparseCategoricalCrossentropy;
begin
var y_true := np.np_array< Integer >([ 1, 2 ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.05, 0.95, 0 ], [ 0.1, 0.8, 0.1 ] ]);
var m := tf.keras.metrics.SparseCategoricalCrossentropy;
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,1.1769392);
end;
procedure EagerModeTestBase.SparseTopKCategoricalAccuracy;
begin
var y_true := np.np_array< Integer >([ 2, 1 ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.1, 0.9, 0.8 ], [ 0.05, 0.95, 0 ] ]);
var m := tf.keras.metrics.SparseTopKCategoricalAccuracy(1);
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.5);
m.reset_states;
var weights := np.np_array< Single >([ 0.7, 0.3 ]);
m.update_state(y_true, y_pred, weights);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r, 0.3);
end;
procedure EagerModeTestBase.HammingLoss;
begin
// multi-class hamming loss
var y_true := np.np_array< TArray<Integer> >([
[ 1, 0, 0, 0 ],
[ 0, 0, 1, 0 ],
[ 0, 0, 0, 1 ],
[ 0, 1, 0, 0 ] ]);
var y_pred := np.np_array< TArray<Single> >([
[ 0.8, 0.1, 0.1, 0.0 ],
[ 0.2, 0.0, 0.8, 0.0 ],
[ 0.05, 0.05, 0.1, 0.8 ],
[ 1.0, 0.0, 0.0, 0.0 ]]);
var threshold : Single := 0.6;
var m := tf.keras.metrics.HammingLoss('multiclass',@threshold);
m.update_state(y_true, y_pred);
var r : NDArray := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.25);
// multi-label hamming loss
y_true := np.np_array< TArray<Integer> >([
[ 1, 0, 1, 0 ],
[ 0, 1, 0, 1 ],
[ 0, 0, 0, 1 ] ]);
y_pred := np.np_array< TArray<Single> >([
[ 0.82, 0.5, 0.9, 0.0 ],
[ 0, 1, 0.4, 0.98 ],
[ 0.89, 0.79, 0, 0.3 ]]);
threshold := 0.8;
m := tf.keras.metrics.HammingLoss('multilabel',@threshold);
m.update_state(y_true, y_pred);
r := m.R_result.numpy;
Assert.AreEqual<Single>(r,0.16666667);
end;
procedure EagerModeTestBase.F1Score;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 1, 1, 1 ], [ 1, 0, 0 ], [ 1, 1, 0 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.2, 0.6, 0.7 ], [ 0.2, 0.6, 0.6 ], [ 0.6, 0.8, 0 ] ]);
var threshold : Single := 0.5;
var m := tf.keras.metrics.F1Score(3,'',@threshold);
m.update_state(y_true, y_pred);
var r := m.R_result.numpy.ToArray<Single>;
var a : TArray<Single> := [ 0.5, 0.8, 0.6666667 ];
Assert.IsTrue( TUtils.SequenceEqual<Single>(r,a) );
end;
procedure EagerModeTestBase.FBetaScore;
begin
var y_true := np.np_array< TArray<Integer> >([ [ 1, 1, 1 ], [ 1, 0, 0 ], [ 1, 1, 0 ] ]);
var y_pred := np.np_array< TArray<Single> >([ [ 0.2, 0.6, 0.7 ], [ 0.2, 0.6, 0.6 ], [ 0.6, 0.8, 0 ] ]);
var threshold : Single := 0.5;
var m := tf.keras.metrics.FBetaScore(3,'',2.0, @threshold);
m.update_state(y_true, y_pred);
var r := m.R_result.numpy.ToArray<Single>;
var a : TArray<Single> := [ 0.3846154, 0.90909094, 0.8333334 ];
Assert.IsTrue( TUtils.SequenceEqual<Single>(r,a) );
end;
{ ActivationFunctionTest }
constructor ActivationFunctionTest.Create;
begin
a := tf.constant( TArray<Single>.Create( 1.0, -0.5, 3.4, -2.1, 0.0, -6.5 ) );
TestInit;
end;
procedure ActivationFunctionTest.Sigmoid;
begin
var b := tf.nn.sigmoid(a, 'sigmoid');
var expected : TArray<Single> := [ 0.7310586, 0.37754068, 0.9677046, 0.10909683, 0.5, 0.00150118 ];
var actual := b.ToArray<Single>;
Assert.IsTrue( Equal(expected, actual) );
end;
procedure ActivationFunctionTest.ReLU;
begin
var b := tf.nn.relu(a, 'ReLU');
var expected : TArray<Single> := [ 1, 0, 3.4, 0, 0, 0 ];
var actual := b.ToArray<Single>;
Assert.IsTrue(Equal(expected, actual));
end;
procedure ActivationFunctionTest.TanH;
begin
var b := tf.nn.tanh(a, 'TanH');
var expected : TArray<Single> := [ 0.7615942, -0.46211717, 0.9977749, -0.970452, 0, -0.99999547 ];
var actual := b.ToArray<Single>;
Assert.IsTrue(Equal(expected, actual));
end;
{ BitwiseApiTest }
constructor BitwiseApiTest.Create;
begin
TestInit;
end;
procedure BitwiseApiTest.BitwiseAnd;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( 0, 5, 3, 14 ) );
var rhs : TFTensor := tf.constant( TArray<Integer>.Create( 5, 0, 7, 11 ) );
var bitwise_and_result := tf.bitwise.bitwise_and(lhs, rhs);
var expected : TArray<Integer> := [ 0, 0, 3, 10 ];
var actual := bitwise_and_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
procedure BitwiseApiTest.BitwiseOr;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( 0, 5, 3, 14 ) );
var rhs : TFTensor := tf.constant( TArray<Integer>.Create( 5, 0, 7, 11 ) );
var bitwise_or_result := tf.bitwise.bitwise_or(lhs, rhs);
var expected : TArray<Integer> := [ 5, 5, 7, 15 ];
var actual := bitwise_or_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
procedure BitwiseApiTest.BitwiseXOR;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( 0, 5, 3, 14 ) );
var rhs : TFTensor := tf.constant( TArray<Integer>.Create( 5, 0, 7, 11 ) );
var bitwise_xor_result := tf.bitwise.bitwise_xor(lhs, rhs);
var expected : TArray<Integer> := [ 5, 5, 4, 5 ];
var actual := bitwise_xor_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
procedure BitwiseApiTest.Invert;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( 0, 1, -3, integer.MaxValue ) );
var invert_result := tf.bitwise.invert(lhs);
var expected : TArray<Integer> := [ -1, -2, 2, Integer.MinValue ];
var actual := invert_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
procedure BitwiseApiTest.LeftShift;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( -1, -5, -3, -14 ) );
var rhs : TFTensor := tf.constant( TArray<Integer>.Create(5, 0, 7, 11 ));
var left_shift_result := tf.bitwise.left_shift(lhs, rhs);
var expected : TArray<Integer> := [ -32, -5, -384, -28672 ];
var actual := left_shift_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
procedure BitwiseApiTest.RightShift;
begin
var lhs : TFTensor := tf.constant( TArray<Integer>.Create( -2, 64, 101, 32 ) );
var rhs : TFTensor := tf.constant( TArray<Integer>.Create( -1, -5, -3, -14 ) );
var right_shift_result := tf.bitwise.right_shift(lhs, rhs);
var expected : TArray<Integer> := [ -2, 64, 101, 32 ];
var actual := right_shift_result.ToArray<Integer>;
Assert.IsTrue(TUtils.SequenceEqual<Integer>(expected, actual));
end;
{ ConstantTest }
constructor ConstantTest.Create;
begin
TestInit;
end;
procedure ConstantTest.Multiply;
begin
var a : TTensor := tf.constant(Double(3.0));
var b : TTensor := tf.constant(Double(2.0));
var c : TTensor := a * b;
Assert.AreEqual<Double>(6.0, Double(c));
end;
procedure ConstantTest.NDimConst;
begin
var a : TArray<TArray<Integer>>:= [[3,1,1],[2,1,3]];
var nd := np.np_array(a);
var tensor := tf.constant(nd);