-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathUtil.cs
More file actions
1464 lines (1290 loc) · 60.6 KB
/
Util.cs
File metadata and controls
1464 lines (1290 loc) · 60.6 KB
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
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Linq;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace DeepLearningWithCNTK {
#if USES_WPF
static class WPFUtil {
static public System.Windows.Media.Imaging.BitmapImage BitmapToImageSource(System.Drawing.Bitmap bitmap) {
using (var memory = new System.IO.MemoryStream()) {
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
memory.Position = 0;
var bitmapimage = new System.Windows.Media.Imaging.BitmapImage();
bitmapimage.BeginInit();
bitmapimage.StreamSource = memory;
bitmapimage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
bitmapimage.EndInit();
return bitmapimage;
}
}
static public System.Drawing.Bitmap createBitmap(float[] src, int gridIndex, int width, int height, bool adjustColorRange) {
int numChannels = 3;
var colorScaleFactor = 1.0;
var numPixels = width * height;
if (adjustColorRange) {
var maxValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Max();
var minValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Min();
colorScaleFactor = (float)(254.0 / maxValue);
}
var bitmap = new System.Drawing.Bitmap(width, height);
var srcStart = gridIndex * numPixels;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
var pos = srcStart + row * width + col;
var b = (int)(colorScaleFactor * src[pos]);
var g = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + numPixels]);
var r = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + 2 * numPixels]);
bitmap.SetPixel(col, row, System.Drawing.Color.FromArgb(r, g, b));
}
}
return bitmap;
}
}
class PlotWindowBitMap : System.Windows.Window {
public PlotWindowBitMap(string title, float[] images, int width, int height, int numChannels) {
var numPixels = width * height;
var gridLength = (int)Math.Sqrt(images.Length / numPixels);
var grid = new System.Windows.Controls.Grid();
for (int row = 0; row < gridLength; row++) {
grid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition());
for (int column = 0; column < gridLength; column++) {
if (row == 0) { grid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition()); }
var gridIndex = (row * gridLength + column);
var bitmap = WPFUtil.createBitmap(images, gridIndex, width, height, adjustColorRange: false);
var image = new System.Windows.Controls.Image();
image.Source = WPFUtil.BitmapToImageSource(bitmap);
image.Stretch = System.Windows.Media.Stretch.Fill;
grid.Children.Add(image);
System.Windows.Controls.Grid.SetRow(image, row);
System.Windows.Controls.Grid.SetColumn(image, column);
}
}
this.Title = title;
this.Content = grid;
SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
}
}
#endif
static public class CPPUtil {
const string CPPUtilDll = "CPPUtil.dll";
[DllImport(CPPUtilDll)]
public static extern double version();
[DllImport(CPPUtilDll)]
public static extern void compute_image([In, Out]float[] image, [MarshalAs(UnmanagedType.LPWStr)]string pathToVGG16model, int filterIndex);
[DllImport(CPPUtilDll)]
public static extern void load_image([MarshalAs(UnmanagedType.LPWStr)]string imagePath, [In, Out]float[] image);
[DllImport(CPPUtilDll)]
public static extern void evaluate_vgg16([MarshalAs(UnmanagedType.LPWStr)]string pathToVGG16model, [MarshalAs(UnmanagedType.LPWStr)]string imagePath, [In, Out]float[] predictions, int num_classes);
[DllImport(CPPUtilDll)]
public static extern void visualize_heatmap(
[MarshalAs(UnmanagedType.LPWStr)]string pathToVGG16model,
[MarshalAs(UnmanagedType.LPWStr)]string imagePath,
[MarshalAs(UnmanagedType.LPWStr)]string layerName,
int predictionIndex,
[In, Out]float[] imageWithOverlayedHitmap);
}
static class VGG19 {
static readonly string vgg19_filename = "VGG19_ImageNet_Caffe.model";
static readonly string downlink_url = "https://www.cntk.ai/Models/Caffe_Converted/VGG19_ImageNet_Caffe.model";
static string fullpath = null;
static string download_model_if_needed() {
fullpath = Util.download_model_if_needed(fullpath, vgg19_filename, downlink_url);
return fullpath;
}
#if (!NO_CNTK)
static public CNTK.Function get_model(CNTK.Variable features_node, CNTK.DeviceDescriptor computeDevice, bool include_top=false, bool freeze=false, bool use_finetuning=false) {
var cloningMethod = freeze ? CNTK.ParameterCloningMethod.Freeze : CNTK.ParameterCloningMethod.Clone;
// load the original VGG19 model
download_model_if_needed();
var model = CNTK.Function.Load(fullpath, computeDevice);
if ( include_top ) { return model; }
var pool5_node = model.FindByName("pool5");
CNTK.Function cloned_model = null;
if (features_node == null) {
cloned_model = CNTK.Function.Combine(new CNTK.Variable[] { pool5_node }).Clone(cloningMethod);
return cloned_model;
}
System.Diagnostics.Debug.Assert(use_finetuning == false);
System.Diagnostics.Debug.Assert(model.Arguments.Count == 1);
var replacements = new Dictionary<CNTK.Variable, CNTK.Variable>() { {model.Arguments[0], features_node } };
cloned_model = CNTK.Function.Combine(new CNTK.Variable[] { pool5_node }).Clone(cloningMethod, replacements);
return cloned_model;
}
#endif
/*
@staticmethod
def get_model(features_node, include_top=False, use_finetuning=False):
assert use_finetuning is False
cloned_model = cntk.ops.combine(pool5_node).clone(cntk.ops.CloneMethod.freeze, substitutions={data_node: features_node})
return cloned_model
*/
}
static class VGG16 {
static readonly string vgg16_filename = "VGG16_ImageNet_Caffe.model";
static readonly string downlink_url = "https://www.cntk.ai/Models/Caffe_Converted/VGG16_ImageNet_Caffe.model";
static string fullpath = null;
static public string download_model_if_needed() {
fullpath = Util.download_model_if_needed(fullpath, vgg16_filename, downlink_url);
return fullpath;
}
#if (!NO_CNTK)
static public CNTK.Function get_model(CNTK.Variable features, CNTK.DeviceDescriptor computeDevice, bool allow_block5_finetuning=false) {
// load the original VGG16 model
download_model_if_needed();
var model = CNTK.Function.Load(fullpath, computeDevice);
// get the last VGG16 layer before the first fully connected layer
var last_frozen_layer = model.FindByName(allow_block5_finetuning ? "pool4" : "pool5");
// get the first layer, and the "data" input variable
var conv1_1_layer = model.FindByName("conv1_1");
var data = conv1_1_layer.Inputs.First((v) => v.Name == "data");
// the data should be a 224x224x3 input tensor
if (!data.Shape.Dimensions.SequenceEqual(new int[] { 224, 224, 3 })) {
System.Console.WriteLine("There's a problem here. Please email");
System.Environment.Exit(2);
}
// allow different dimensions for input (e.g., 150x150x3)
var replacements = new Dictionary<CNTK.Variable, CNTK.Variable>() { { data, features } };
// clone the original VGG16 model up to the pool_node, freeze all weights, and use a custom input tensor
var frozen_model = CNTK.CNTKLib
.Combine(new CNTK.VariableVector() { last_frozen_layer.Output }, "frozen_output")
.Clone(CNTK.ParameterCloningMethod.Freeze, replacements);
if ( !allow_block5_finetuning ) { return frozen_model; }
var pool5_layer = model.FindByName("pool5");
replacements = new Dictionary<CNTK.Variable, CNTK.Variable>() { { last_frozen_layer.Output, frozen_model.Output} };
var model_with_finetuning = CNTK.CNTKLib
.Combine(new CNTK.VariableVector() { pool5_layer.Output }, "finetuning_output")
.Clone(CNTK.ParameterCloningMethod.Clone, replacements);
return model_with_finetuning;
}
#endif
}
static class Util {
public static byte[] convert_from_channels_first(float[] img, float[] offsets=null, float scaling=1.0f, bool invertOrder=false) {
if ( offsets==null ) { offsets = new float[3]; }
var img_data = new byte[img.Length];
var image_size = img.Length / 3;
for (int i = 0; i < img_data.Length; i += 3) {
img_data[i + 1] = (byte)Math.Max(0, Math.Min(scaling * img[i / 3 + image_size] + offsets[1], 255));
if (invertOrder) {
img_data[i + 2] = (byte)Math.Max(0, Math.Min(scaling * img[i / 3] + offsets[0], 255));
img_data[i] = (byte)Math.Max(0, Math.Min(scaling * img[i / 3 + 2 * image_size] + offsets[2], 255));
}
else {
img_data[i] = (byte)Math.Max(0, Math.Min(scaling * img[i / 3] + offsets[0], 255));
img_data[i + 2] = (byte)Math.Max(0, Math.Min(scaling * img[i / 3 + 2 * image_size] + offsets[2], 255));
}
}
return img_data;
}
public static string get_the_path_of_the_elephant_image() {
var cwd = System.IO.Directory.GetCurrentDirectory();
var pos = cwd.LastIndexOf("DeepLearning\\");
var base_path = cwd.Substring(0, pos);
var image_path = System.IO.Path.Combine(base_path, "DeepLearning", "Ch_05_Class_Activation_Heatmaps", "creative_commons_elephant.jpg");
return image_path;
}
public static string download_model_if_needed(string fullpath, string dstFilename, string downlink_url) {
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
if (fullpath == null) {
fullpath = Util.fullpathForDownloadedFile(dstDir: "DownloadedModels", dstFilename: dstFilename);
}
if (System.IO.File.Exists(fullpath)) {
return fullpath;
}
var success = FromStackOverflow.FileDownloader.DownloadFile(downlink_url, fullpath, timeoutInMilliSec: 3600000);
if (!success) {
System.Console.WriteLine("There was a problem with the download of the caffe model");
System.Environment.Exit(1);
}
return fullpath;
}
public static string fullpathForDownloadedFile(string dstDir, string dstFilename) {
var fullpath = string.Empty;
var path = System.IO.Directory.GetCurrentDirectory();
var modelsPath = System.IO.Path.Combine("DeepLearning", dstDir);
var pos = path.LastIndexOf("DeepLearning");
if (pos >= 0) {
fullpath = System.IO.Path.Combine(path.Substring(0, pos), modelsPath);
}
if (!System.IO.Directory.Exists(fullpath)) {
try {
System.IO.Directory.CreateDirectory(fullpath);
}
catch (Exception e) {
System.Console.WriteLine("Could not create directory " + fullpath + "," + e.Message);
fullpath = System.IO.Directory.GetCurrentDirectory();
}
}
fullpath = System.IO.Path.Combine(fullpath, dstFilename);
return fullpath;
}
public static void print<T>(IList<T> v, string prefix = null) {
if (prefix != null) {
Console.Write(prefix);
}
Console.Write("{");
for (int column = 0; column < v.Count; column++) {
Console.Write(v[column]);
if (column != (v.Count - 1)) { Console.Write(", "); }
}
Console.WriteLine("}");
}
public static void print<T>(T[,,] values) {
for (int i = 0; i < values.GetLength(0); i++) {
Console.Write("{\n");
for (int j = 0; j < values.GetLength(1); j++) {
Console.Write("\t{");
for (int k = 0; k < values.GetLength(2); k++) {
Console.Write(values[i, j, k]);
if (k != (values.GetLength(2) - 1)) { Console.Write(", "); }
}
Console.WriteLine("}");
}
Console.WriteLine("}");
}
Console.WriteLine();
}
public static void save_binary_file(float[][] src, string filepath) {
Console.WriteLine("Saving " + filepath);
var buffer = new byte[sizeof(float) * src[0].Length];
using (var writer = new System.IO.BinaryWriter(System.IO.File.OpenWrite(filepath))) {
for (int row = 0; row < src.Length; row++) {
System.Buffer.BlockCopy(src[row], 0, buffer, 0, buffer.Length);
writer.Write(buffer, 0, buffer.Length);
}
}
}
public static float[][] load_binary_file(string filepath, int numRows, int numColumns) {
Console.WriteLine("Loading " + filepath);
var buffer = new byte[sizeof(float) * numRows * numColumns];
using (var reader = new System.IO.BinaryReader(System.IO.File.OpenRead(filepath))) {
reader.Read(buffer, 0, buffer.Length);
}
var dst = new float[numRows][];
for (int row = 0; row < dst.Length; row++) {
dst[row] = new float[numColumns];
System.Buffer.BlockCopy(buffer, row * numColumns * sizeof(float), dst[row], 0, numColumns * sizeof(float));
}
return dst;
}
// https://github.com/dotnet/roslyn/issues/3208#issuecomment-210134781
public static int SizeOf<T>() where T : struct {
return Marshal.SizeOf(default(T));
}
public static T[] convert_jagged_array_to_single_dimensional_array<T>(T[][] src) where T : struct {
var numRows = src.Length;
var numColumns = src[0].Length;
var numBytesInRow = numColumns * SizeOf<T>();
var dst = new T[numRows * numColumns];
var dstOffset = 0;
for (int row=0; row<numRows; row++) {
System.Diagnostics.Debug.Assert(src[row].Length == numColumns);
System.Buffer.BlockCopy(src[row], 0, dst, dstOffset, numBytesInRow);
dstOffset += numBytesInRow;
}
return dst;
}
public static float[] load_binary_file(string filepath, int N) {
Console.WriteLine("Loading " + filepath);
var buffer = new byte[sizeof(float) * N];
using (var reader = new System.IO.BinaryReader(System.IO.File.OpenRead(filepath))) {
reader.Read(buffer, 0, buffer.Length);
}
var dst = new float[N];
System.Buffer.BlockCopy(buffer, 0, dst, 0, buffer.Length);
return dst;
}
public static void swap<T>(T[] array, int n, int k) {
var temp = array[n];
array[n] = array[k];
array[k] = temp;
}
public static void shuffle<T>(T[] array) {
// https://stackoverflow.com/a/110570
var rng = new Random();
var n = array.Length;
while (n > 1) {
var k = rng.Next(n--);
swap(array, n, k);
}
}
public static void shuffle<T1, T2>(T1[] array1, T2[] array2) {
System.Diagnostics.Debug.Assert(array1.Length == array2.Length);
var rng = new Random();
var n = array1.Length;
while (n > 1) {
var k = rng.Next(n--);
swap(array1, n, k);
swap(array2, n, k);
}
}
public static int[] shuffled_indices(int N) {
var array = new int[N];
for (int i = 0; i < N; i++) { array[i] = i; }
shuffle(array);
return array;
}
#if (!NO_CNTK)
static CNTK.NDArrayView[] get_minibatch_data_CPU(CNTK.NDShape shape, float[][] src, int indices_begin, int indices_end) {
var num_indices = indices_end - indices_begin;
var result = new CNTK.NDArrayView[num_indices];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
var dataBuffer = src[index];
var ndArrayView = new CNTK.NDArrayView(shape, dataBuffer, CNTK.DeviceDescriptor.CPUDevice, true);
result[row_index++] = ndArrayView;
}
return result;
}
static float[] get_minibatch_data_CPU(CNTK.NDShape shape, float[] src, int indices_begin, int indices_end) {
// it would be nice if we avoid the copy here
var result = new float[indices_end - indices_begin];
Array.Copy(src, indices_begin, result, 0, result.Length);
return result;
}
static float[] get_minibatch_data_CPU(CNTK.NDShape shape, float[] src, int[] indices, int indices_begin, int indices_end) {
var num_indices = indices_end - indices_begin;
var row_length = shape.TotalSize;
var result = new float[num_indices];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
result[row_index++] = src[indices[index]];
}
return result;
}
static CNTK.NDArrayView[] get_minibatch_data_CPU(CNTK.NDShape shape, float[][] src, int[] indices, int indices_begin, int indices_end) {
var num_indices = indices_end - indices_begin;
var row_length = shape.TotalSize;
var result = new CNTK.NDArrayView[num_indices];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
var dataBuffer = src[indices[index]];
var ndArrayView = new CNTK.NDArrayView(shape, dataBuffer, CNTK.DeviceDescriptor.CPUDevice, true);
result[row_index++] = ndArrayView;
}
return result;
}
static float[][] get_minibatch_data_CPU_sequence(int sequence_length, CNTK.NDShape shape, float[][] src, int[] indices, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
System.Diagnostics.Debug.Assert(src[0].Length == sequence_length);
var num_indices = indices_end - indices_begin;
var result = new float[num_indices][];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
result[row_index] = new float[sequence_length];
System.Buffer.BlockCopy(src[indices[index]], 0, result[row_index], 0, sequence_length*sizeof(float));
row_index++;
}
return result;
}
static float[] get_minibatch_data_CPU_sequence_blob(int sequence_length, CNTK.NDShape shape, float[][] src, int[] indices, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
System.Diagnostics.Debug.Assert(src[0].Length == sequence_length);
var num_indices = indices_end - indices_begin;
var result = new float[num_indices * sequence_length];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
System.Buffer.BlockCopy(src[indices[index]], 0, result, row_index*sequence_length*sizeof(float), sequence_length * sizeof(float));
row_index++;
}
return result;
}
static float[] get_minibatch_data_CPU_sequence_blob(int sequence_length, CNTK.NDShape shape, float[][] src, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
System.Diagnostics.Debug.Assert(src[0].Length == sequence_length);
var num_indices = indices_end - indices_begin;
var result = new float[num_indices * sequence_length];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
System.Buffer.BlockCopy(src[index], 0, result, row_index*sequence_length*sizeof(float), sequence_length * sizeof(float));
row_index++;
}
return result;
}
static float[][] get_minibatch_data_CPU_sequence(int sequence_length, CNTK.NDShape shape, float[][] src, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
System.Diagnostics.Debug.Assert(src[0].Length == sequence_length);
var num_indices = indices_end - indices_begin;
var result = new float[num_indices][];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
result[row_index] = new float[sequence_length];
System.Buffer.BlockCopy(src[index], 0, result[row_index], 0, sequence_length * sizeof(float));
row_index++;
}
return result;
}
static float[][] get_minibatch_data_CPU_sequence(int sequence_length, CNTK.NDShape shape, float[] src, int[] indices, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
var num_indices = indices_end - indices_begin;
var result = new float[num_indices][];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
result[row_index] = new float[sequence_length];
result[row_index][sequence_length - 1] = src[indices[index]];
row_index++;
}
return result;
}
static float[][] get_minibatch_data_CPU_sequence(int sequence_length, CNTK.NDShape shape, float[] src, int indices_begin, int indices_end) {
System.Diagnostics.Debug.Assert((shape.Dimensions.Count == 0) || ((shape.Dimensions.Count == 1) && (shape.Dimensions[0] == 1)));
var num_indices = indices_end - indices_begin;
var result = new float[num_indices][];
var row_index = 0;
for (var index = indices_begin; index != indices_end; index++) {
result[row_index] = new float[sequence_length];
result[row_index][sequence_length - 1] = src[index];
row_index++;
}
return result;
}
public static CNTK.Value get_tensors(CNTK.NDShape shape, float[][] src, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU(shape, src, indices_begin, indices_end);
var result = CNTK.Value.Create(shape, cpu_tensors, device, true);
return result;
}
static readonly bool USE_CREATE_BATCH_OF_SEQUENCES = false;
public static CNTK.Value get_tensors_sequence(int sequence_length, CNTK.NDShape shape, float[][] src, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
CNTK.Value result = null;
if (USE_CREATE_BATCH_OF_SEQUENCES) {
var cpu_tensors = Util.get_minibatch_data_CPU_sequence(sequence_length, shape, src, indices_begin, indices_end);
result = CNTK.Value.CreateBatchOfSequences(shape, cpu_tensors, device, true);
}
else {
var cpu_blob = Util.get_minibatch_data_CPU_sequence_blob(sequence_length, shape, src, indices_begin, indices_end);
var blob_shape = shape.AppendShape(new int[] { sequence_length, indices_end - indices_begin });
var ndArrayView = new CNTK.NDArrayView(blob_shape, cpu_blob, device);
result = new CNTK.Value(ndArrayView);
}
return result;
}
public static CNTK.Value get_tensors(CNTK.NDShape shape, float[][] src, int[] indices, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU(shape, src, indices, indices_begin, indices_end);
var result = CNTK.Value.Create(shape, cpu_tensors, device, true);
return result;
}
public static CNTK.Value get_tensors_sequence(int sequence_length, CNTK.NDShape shape, float[][] src, int[] indices, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
CNTK.Value result = null;
if (USE_CREATE_BATCH_OF_SEQUENCES) {
var cpu_tensors = Util.get_minibatch_data_CPU_sequence(sequence_length, shape, src, indices, indices_begin, indices_end);
result = CNTK.Value.CreateBatchOfSequences(shape, cpu_tensors, device, true);
}
else {
var cpu_blob = Util.get_minibatch_data_CPU_sequence_blob(sequence_length, shape, src, indices, indices_begin, indices_end);
var blob_shape = shape.AppendShape(new int[] { sequence_length, indices_end - indices_begin });
var ndArrayView = new CNTK.NDArrayView(blob_shape, cpu_blob, device);
result = new CNTK.Value(ndArrayView);
}
return result;
}
public static CNTK.Value get_tensors(CNTK.NDShape shape, float[] src, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU(shape, src, indices_begin, indices_end);
var result = CNTK.Value.CreateBatch(shape, cpu_tensors, device, true);
return result;
}
public static CNTK.Value get_tensors_sequence(int sequence_length, CNTK.NDShape shape, float[] src, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU_sequence(sequence_length, shape, src, indices_begin, indices_end);
var result = CNTK.Value.CreateBatchOfSequences(shape, cpu_tensors, device, true);
return result;
}
public static CNTK.Value get_tensors(CNTK.NDShape shape, float[] src, int[] indices, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU(shape, src, indices, indices_begin, indices_end);
var result = CNTK.Value.CreateBatch(shape, cpu_tensors, device, true);
return result;
}
public static CNTK.Value get_tensors_sequence(int sequence_length, CNTK.NDShape shape, float[] src, int[] indices, int indices_begin, int indices_end, CNTK.DeviceDescriptor device) {
var cpu_tensors = Util.get_minibatch_data_CPU_sequence(sequence_length, shape, src, indices, indices_begin, indices_end);
var result = CNTK.Value.CreateBatchOfSequences(shape, cpu_tensors, device, true);
return result;
}
static public CNTK.DeviceDescriptor get_compute_device() {
foreach (var gpuDevice in CNTK.DeviceDescriptor.AllDevices()) {
if (gpuDevice.Type == CNTK.DeviceKind.GPU) { return gpuDevice; }
}
return CNTK.DeviceDescriptor.CPUDevice;
}
static readonly string equalSigns = "=============================================================================";
static readonly string underscores = "_____________________________________________________________________________";
static void summary(CNTK.Function rootFunction, List<string> entries, ISet<string> visited) {
if (visited == null) {
visited = new HashSet<string>();
}
if (rootFunction.IsComposite) {
summary(rootFunction.RootFunction, entries, visited);
return;
}
if ( visited.Contains(rootFunction.Uid)) {
return;
}
visited.Add(rootFunction.Uid);
var numParameters = 0;
foreach (var rootInput in rootFunction.Inputs) {
if (rootInput.IsParameter && !rootInput.IsConstant) {
numParameters += rootInput.Shape.TotalSize;
}
if ((rootInput.Owner == null) || visited.Contains(rootInput.Owner.Uid) ) { continue; }
summary(rootInput.Owner, entries, visited);
}
for (int i = 0; i < rootFunction.Outputs.Count; i++) {
var line = $"{rootFunction.Name,-29}{rootFunction.Outputs[i].Shape.AsString(),-26}{numParameters}";
entries.Add(line);
}
entries.Add(underscores);
}
public static string shape_desc(CNTK.Variable node) {
var static_shape = node.Shape.AsString();
var dyn_axes = node.DynamicAxes;
var dyn_axes_description = (dyn_axes.Count == 1) ? "[#]" : "[*, #]";
return $"({static_shape}, {dyn_axes_description})";
}
public static IList<CNTK.Function> find_function_with_input(CNTK.Function root, CNTK.Function inputFunction) {
var list = new List<CNTK.Function>();
root = root.RootFunction;
inputFunction = inputFunction.RootFunction;
var root_uid = root.Uid;
var stack = new Stack<object>();
stack.Push(root);
var visited_uids = new HashSet<string>();
while (stack.Count > 0) {
var popped = stack.Pop();
if (popped is CNTK.Variable) {
var v = (CNTK.Variable)popped;
if (v.IsOutput) {
stack.Push(v.Owner);
}
continue;
}
if (popped is IList<CNTK.Variable>) {
foreach (var pv in (IList<CNTK.Variable>)popped) {
stack.Push(pv);
}
continue;
}
var node = (CNTK.Function)popped;
if (visited_uids.Contains(node.Uid)) { continue; }
node = node.RootFunction;
stack.Push(node.RootFunction.Inputs);
for (int i = 0; i < node.Inputs.Count; i++) {
var input = node.Inputs[i];
if (input.Uid==inputFunction.Output.Uid) {
list.Add(node);
}
}
visited_uids.Add(node.Uid);
}
return list;
}
public static List<string> detailed_summary(CNTK.Function root, bool print=true) {
// This is based on the cntk.logging.graph.plot, but without the actual plotting part
// Walks through every node of the graph starting at ``root``, creates a network graph, and returns a network description
var model = new List<string>();
root = root.RootFunction;
var root_uid = root.Uid;
var stack = new Stack<object>();
stack.Push(root);
var visited_uids = new HashSet<string>();
while (stack.Count>0) {
var popped = stack.Pop();
if (popped is CNTK.Variable) {
var v = (CNTK.Variable)popped;
if (v.IsOutput) {
stack.Push(v.Owner);
}
else if (v.IsInput) {
model.Add(v.AsString());
}
continue;
}
if ( popped is IList<CNTK.Variable> ) {
foreach(var pv in (IList<CNTK.Variable>)popped ) {
stack.Push(pv);
}
continue;
}
var node = (CNTK.Function)popped;
if (visited_uids.Contains(node.Uid)) { continue; }
node = node.RootFunction;
stack.Push(node.RootFunction.Inputs);
var line = new System.Text.StringBuilder($"{node.Name} : {node.OpName} ({node.Uid}) :");
line.Append("(");
for (int i=0; i<node.Inputs.Count; i++) {
var input = node.Inputs[i];
if (node.IsBlock && input.IsConstant) { continue; }
line.Append(input.Uid);
if ( i!=(node.Inputs.Count-1)) {
line.Append(", ");
}
}
line.Append(") -> ");
foreach(var v in node.Outputs) {
model.Add(line.ToString() + "\t" + shape_desc(v));
}
visited_uids.Add(node.Uid);
}
model.Reverse();
if (print) {
for (int i=0; i<model.Count; i++) {
Console.WriteLine(model[i]);
}
}
return model;
}
public static void summary(CNTK.Function rootFunction) {
var entries = new List<string>();
entries.Add(underscores);
entries.Add("Layer (type) Output Shape Trainable Parameters #");
entries.Add(equalSigns);
summary(rootFunction, entries, null);
foreach(var v in entries) {
Console.WriteLine(v);
}
}
static public void log_number_of_parameters(CNTK.Function model) {
Console.WriteLine("\nModel Summary");
Console.WriteLine("\tInput = " + model.Arguments[0].Shape.AsString());
for (int i = 0; i < model.Outputs.Count; i++) {
Console.WriteLine("\tOutput = " + model.Outputs[i].Shape.AsString());
}
Console.WriteLine("");
var numParameters = 0;
foreach (var x in model.Parameters()) {
var shape = x.Shape;
var p = shape.TotalSize;
Console.WriteLine(string.Format("\tFilter Shape:{0,-30} Param #:{1}", shape.AsString(), p));
numParameters += p;
}
Console.WriteLine(string.Format("\nTotal Number of Parameters: {0:N0}", numParameters));
Console.WriteLine("---\n");
}
static public CNTK.Function Dense(CNTK.Variable input, int outputDim, CNTK.DeviceDescriptor device, string outputName = "") {
var shape = CNTK.NDShape.CreateNDShape(new int[] { outputDim, CNTK.NDShape.InferredDimension });
var timesParam = new CNTK.Parameter(shape, CNTK.DataType.Float, CNTK.CNTKLib.GlorotUniformInitializer(CNTK.CNTKLib.DefaultParamInitScale, CNTK.CNTKLib.SentinelValueForInferParamInitRank, CNTK.CNTKLib.SentinelValueForInferParamInitRank, 1), device, "timesParam_"+outputName);
var timesFunction = CNTK.CNTKLib.Times(timesParam, input, 1 /* output dimension */, 0 /* CNTK should infer the input dimensions */);
var plusParam = new CNTK.Parameter(CNTK.NDShape.CreateNDShape(new int[] { CNTK.NDShape.InferredDimension }), 0.0f, device, "plusParam_"+outputName);
var result = CNTK.CNTKLib.Plus(plusParam, timesFunction, outputName);
return result;
}
static public CNTK.Function Embedding(CNTK.Variable x, int shape, CNTK.DeviceDescriptor computeDevice, float[][] weights=null, string name = "") {
CNTK.Function result;
// based on the Embedding defined in https://github.com/Microsoft/CNTK/blob/master/bindings/python/cntk/layers/layers.py
if (weights == null) {
var weight_shape = new int[] { shape, CNTK.NDShape.InferredDimension };
var E = new CNTK.Parameter(
weight_shape,
CNTK.DataType.Float,
CNTK.CNTKLib.GlorotUniformInitializer(),
computeDevice, name: "embedding_" + name);
result = CNTK.CNTKLib.Times(E, x);
}
else {
var weight_shape = new int[] { shape, x.Shape.Dimensions[0] };
System.Diagnostics.Debug.Assert(shape == weights[0].Length);
System.Diagnostics.Debug.Assert(weight_shape[1] == weights.Length);
var w = convert_jagged_array_to_single_dimensional_array(weights);
var ndArrayView = new CNTK.NDArrayView(weight_shape, w, computeDevice, readOnly: true);
var E = new CNTK.Constant(ndArrayView, name: "fixed_embedding_"+name);
result = CNTK.CNTKLib.Times(E, x);
}
return result;
}
static T[] concat<T>(params T[][] arguments) where T: struct {
var list = new List<T>();
for (int i=0; i<arguments.Length; i++) {
list.AddRange(arguments[i]);
}
return list.ToArray();
}
static int[] make_ones(int numOnes) {
var ones = new int[numOnes];
for (int i=0; i<numOnes; i++) { ones[i] = 1; }
return ones;
}
static T[] pad_to_shape<T>(int[] filter_shape, T value) where T: struct {
var result = new T[filter_shape.Length];
for (int i=0; i<result.Length; i++) { result[i] = value; }
return result;
}
static public CNTK.Function ConvolutionTranspose(
CNTK.Variable x,
CNTK.DeviceDescriptor computeDevice,
int[] filter_shape,
int num_filters,
Func<CNTK.Variable, CNTK.Function> activation = null,
bool use_padding = true,
int[] strides = null,
bool use_bias = true,
int[] output_shape = null,
uint reduction_rank = 1,
int[] dilation = null,
uint max_temp_mem_size_in_samples = 0,
string name = ""
) {
if (strides == null) { strides = new int[] { 1 }; }
var sharing = pad_to_shape(filter_shape, true);
var padding = pad_to_shape(filter_shape, use_padding);
if ( reduction_rank!=1 ) { throw new NotSupportedException("reduction_rank should be 1"); }
padding = concat(padding, new bool[] { false });
if ( dilation==null ) {
dilation = pad_to_shape(filter_shape, 1);
}
var output_channels_shape = new int[] { num_filters };
var kernel_shape = concat(filter_shape, output_channels_shape, new int[] { CNTK.NDShape.InferredDimension });
var output_full_shape = output_shape;
if (output_full_shape != null) {
output_full_shape = concat(output_shape, output_channels_shape);
}
var filter_rank = filter_shape.Length;
var init = CNTK.CNTKLib.GlorotUniformInitializer(CNTK.CNTKLib.DefaultParamInitScale, CNTK.CNTKLib.SentinelValueForInferParamInitRank, CNTK.CNTKLib.SentinelValueForInferParamInitRank, 1);
var W = new CNTK.Parameter(kernel_shape, CNTK.DataType.Float, init, computeDevice, name = "W");
var r = CNTK.CNTKLib.ConvolutionTranspose(
convolutionMap: W,
operand: x,
strides: strides,
sharing: new CNTK.BoolVector(sharing),
autoPadding: new CNTK.BoolVector(padding),
outputShape: output_full_shape,
dilation: dilation,
reductionRank: reduction_rank,
maxTempMemSizeInSamples: max_temp_mem_size_in_samples);
if (use_bias) {
var b_shape = concat(make_ones(filter_shape.Length), output_channels_shape);
var b = new CNTK.Parameter(b_shape, 0.0f, computeDevice, "B");
r = CNTK.CNTKLib.Plus(r, b);
}
if (activation != null) {
r = activation(r);
}
return r;
}
static public CNTK.Function Convolution1DWithReLU(
CNTK.Variable input,
int num_output_channels,
int filter_shape,
CNTK.DeviceDescriptor device,
bool use_padding = false,
bool use_bias = true,
int[] strides = null,
string outputName = "") {
var convolution_map_size = new int[] { filter_shape, CNTK.NDShape.InferredDimension, num_output_channels };
if (strides == null) { strides = new int[] { 1 }; }
var rtrn = Convolution(convolution_map_size, input, device, use_padding, use_bias, strides, CNTK.CNTKLib.ReLU, outputName);
return rtrn;
}
static public CNTK.Function Convolution2DWithReLU(
CNTK.Variable input,
int num_output_channels,
int[] filter_shape,
CNTK.DeviceDescriptor device,
bool use_padding = false,
bool use_bias = true,
int[] strides = null,
string outputName = "",
bool leaky=false) {
var convolution_map_size = new int[] { filter_shape[0], filter_shape[1], CNTK.NDShape.InferredDimension, num_output_channels };
if ( strides==null ) { strides = new int[] { 1 }; }
var activation = leaky ? (Func<CNTK.Variable, string, CNTK.Function>)CNTK.CNTKLib.LeakyReLU : CNTK.CNTKLib.ReLU;
var rtrn = Convolution(convolution_map_size, input, device, use_padding, use_bias, strides, activation, outputName);
return rtrn;
}
static public CNTK.Function Convolution2D(
CNTK.Variable input,
int num_output_channels,
int[] filter_shape,
CNTK.DeviceDescriptor device,
bool use_padding = false,
bool use_bias = true,
int[] strides = null,
Func<CNTK.Variable, string, CNTK.Function> activation = null,
string outputName = "") {
var convolution_map_size = new int[] { filter_shape[0], filter_shape[1], CNTK.NDShape.InferredDimension, num_output_channels };
if (strides == null) { strides = new int[] { 1 }; }
var rtrn = Convolution(convolution_map_size, input, device, use_padding, use_bias, strides, activation, outputName);
return rtrn;
}
static CNTK.Function Convolution(
int[] convolution_map_size,
CNTK.Variable input,
CNTK.DeviceDescriptor device,
bool use_padding,
bool use_bias,
int[] strides,
Func<CNTK.Variable, string, CNTK.Function> activation=null,
string outputName="") {
var W = new CNTK.Parameter(
CNTK.NDShape.CreateNDShape(convolution_map_size),
CNTK.DataType.Float,
CNTK.CNTKLib.GlorotUniformInitializer(CNTK.CNTKLib.DefaultParamInitScale, CNTK.CNTKLib.SentinelValueForInferParamInitRank, CNTK.CNTKLib.SentinelValueForInferParamInitRank, 1),
device, outputName + "_W");
var result = CNTK.CNTKLib.Convolution(W, input, strides, new CNTK.BoolVector(new bool[] { true }) /* sharing */, new CNTK.BoolVector(new bool[] { use_padding }));
if ( use_bias ) {
var num_output_channels = convolution_map_size[convolution_map_size.Length - 1];
var b_shape = concat(make_ones(convolution_map_size.Length - 2), new int[] { num_output_channels });
var b = new CNTK.Parameter(b_shape, 0.0f, device, outputName + "_b");
result = CNTK.CNTKLib.Plus(result, b);
}
if (activation != null) {
result = activation(result, outputName);
}
return result;
}
static public CNTK.Function BinaryAccuracy(CNTK.Variable prediction, CNTK.Variable labels) {
var round_predictions = CNTK.CNTKLib.Round(prediction);
var equal_elements = CNTK.CNTKLib.Equal(round_predictions, labels);
var result = CNTK.CNTKLib.ReduceMean(equal_elements, CNTK.Axis.AllStaticAxes());
return result;
}
static public CNTK.Function MeanSquaredError(CNTK.Variable prediction, CNTK.Variable labels) {
var squared_errors = CNTK.CNTKLib.Square(CNTK.CNTKLib.Minus(prediction, labels));
var result = CNTK.CNTKLib.ReduceMean(squared_errors, new CNTK.Axis(0)); // TODO -- allStaticAxes?
return result;
}
static public CNTK.Function MeanAbsoluteError(CNTK.Variable prediction, CNTK.Variable labels) {
var absolute_errors = CNTK.CNTKLib.Abs(CNTK.CNTKLib.Minus(prediction, labels));
var result = CNTK.CNTKLib.ReduceMean(absolute_errors, new CNTK.Axis(0)); // TODO -- allStaticAxes?
return result;
}
#endif
}
#if (!NO_CNTK)
class ReduceLROnPlateau {
readonly CNTK.Learner learner;
double lr = 0;
double best_metric = 1e-5;
int slot_since_last_update = 0;
public ReduceLROnPlateau(CNTK.Learner learner, double lr) {
this.learner = learner;
this.lr = lr;
}
public bool update(double current_metric) {
bool should_stop = false;
if (current_metric < best_metric) {
best_metric = current_metric;
slot_since_last_update = 0;
return should_stop;
}
slot_since_last_update++;
if (slot_since_last_update > 10) {
lr *= 0.75;
learner.ResetLearningRate(new CNTK.TrainingParameterScheduleDouble(lr));
Console.WriteLine($"Learning rate set to {lr}");
slot_since_last_update = 0;
should_stop = (lr < 1e-6);
}
return should_stop;
}
}
abstract class TrainingEngine {
public enum LossFunctionType { BinaryCrossEntropy, MSE, CrossEntropyWithSoftmax, CrossEntropyWithSoftmaxWithOneHotEncodedLabel, Custom };
public enum AccuracyFunctionType { BinaryAccuracy, SameAsLoss};
public enum MetricType { Loss, Accuracy }
public LossFunctionType lossFunctionType = LossFunctionType.BinaryCrossEntropy;
public AccuracyFunctionType accuracyFunctionType = AccuracyFunctionType.BinaryAccuracy;
public MetricType metricType = MetricType.Accuracy;
public double lr = 0.1;
public int num_epochs { get; set; }
public int batch_size { get; set; }