forked from TensorStack-AI/TensorStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensorExtensions.cs
More file actions
923 lines (798 loc) · 36.5 KB
/
TensorExtensions.cs
File metadata and controls
923 lines (798 loc) · 36.5 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
// Copyright (c) TensorStack. All rights reserved.
// Licensed under the Apache 2.0 License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TensorStack.Common.Tensor;
using TensorStack.Common.Vision;
using TensorPrimitives = System.Numerics.Tensors.TensorPrimitives;
namespace TensorStack.Common
{
/// <summary>
/// Helper extensions for Tensor and TensorSpan, Math, Copy etc.
/// </summary>
public static class TensorExtensions
{
/// <summary>
/// Divides the specified value from all tensor values.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Divide(this TensorSpan<float> tensor, float value)
{
TensorPrimitives.Divide(tensor.Span, value, tensor.Span);
return tensor;
}
/// <summary>
/// Multiplies each Tensor value by the specified value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Multiply(this TensorSpan<float> tensor, float value)
{
TensorPrimitives.Multiply(tensor.Span, value, tensor.Span);
return tensor;
}
/// <summary>
/// Adds TensorB to tensorA
/// </summary>
/// <param name="tensorA">The tensor a.</param>
/// <param name="tensorB">The tensor b.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Add(this TensorSpan<float> tensorA, TensorSpan<float> tensorB)
{
TensorPrimitives.Add(tensorA.Span, tensorB.Span, tensorA.Span);
return tensorA;
}
/// <summary>
/// Adds the specified value to each Tensor value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Add(this TensorSpan<float> tensor, float value)
{
TensorPrimitives.Add(tensor.Span, value, tensor.Span);
return tensor;
}
/// <summary>
/// Subtracts TensorB from TensorA
/// </summary>
/// <param name="tensorA">The tensor a.</param>
/// <param name="tensorB">The tensor b.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Subtract(this TensorSpan<float> tensorA, TensorSpan<float> tensorB)
{
TensorPrimitives.Subtract(tensorA.Span, tensorB.Span, tensorA.Span);
return tensorA;
}
/// <summary>
/// Subtracts the specified value from each Tensor value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <returns>TensorSpan<System.Single>.</returns>
public static TensorSpan<float> Subtract(this TensorSpan<float> tensor, float value)
{
TensorPrimitives.Subtract(tensor.Span, value, tensor.Span);
return tensor;
}
/// <summary>
/// Divides the specified value from all tensor values.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Divide(this Tensor<float> tensor, float value, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensor.Dimensions) : tensor;
TensorPrimitives.Divide(tensor.Span, value, result.Memory.Span);
return result;
}
/// <summary>
/// Multiplies each Tensor value by the specified value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Multiply(this Tensor<float> tensor, float value, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensor.Dimensions) : tensor;
TensorPrimitives.Multiply(tensor.Span, value, result.Memory.Span);
return result;
}
/// <summary>
/// Adds TensorB to tensorA
/// </summary>
/// <param name="tensorA">The tensor a.</param>
/// <param name="tensorB">The tensor b.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Add(this Tensor<float> tensorA, Tensor<float> tensorB, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensorA.Dimensions) : tensorA;
TensorPrimitives.Add(tensorA.Span, tensorB.Span, result.Memory.Span);
return result;
}
/// <summary>
/// Adds the specified value to each Tensor value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Add(this Tensor<float> tensor, float value, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensor.Dimensions) : tensor;
TensorPrimitives.Add(tensor.Span, value, result.Memory.Span);
return result;
}
/// <summary>
/// Subtracts TensorB from TensorA
/// </summary>
/// <param name="tensorA">The tensor a.</param>
/// <param name="tensorB">The tensor b.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Subtract(this Tensor<float> tensorA, Tensor<float> tensorB, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensorA.Dimensions) : tensorA;
TensorPrimitives.Subtract(tensorA.Span, tensorB.Span, result.Memory.Span);
return result;
}
/// <summary>
/// Subtracts the specified value from each Tensor value.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="value">The value.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Subtract(this Tensor<float> tensor, float value, bool isCopy = false)
{
var result = isCopy ? new Tensor<float>(tensor.Dimensions) : tensor;
TensorPrimitives.Subtract(tensor.Span, value, result.Memory.Span);
return result;
}
/// <summary>
/// Reshapes the Tensor with the specified dimensions.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="dimensions">The dimensions.</param>
/// <param name="isCopy">if set to <c>true</c> copy result to new tensor, othewise tensor is mutated</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> Reshape(this Tensor<float> tensor, ReadOnlySpan<int> dimensions, bool isCopy = false)
{
if (isCopy)
return new Tensor<float>(tensor.Memory.ToArray(), dimensions);
tensor.ReshapeTensor(dimensions);
return tensor;
}
/// <summary>
/// Copy TensorSpan to Tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <returns>Tensor<T>.</returns>
public static Tensor<T> ToTensor<T>(this TensorSpan<T> tensor)
{
return new Tensor<T>(tensor.Span.ToArray(), tensor.Dimensions);
}
/// <summary>
/// Copy Tensor to TensorSpan.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <returns>TensorSpan<T>.</returns>
public static TensorSpan<T> ToTensorSpan<T>(this Tensor<T> tensor)
{
return new TensorSpan<T>(tensor.Memory.Span.ToArray(), tensor.Dimensions);
}
/// <summary>
/// Copy TensorSpan to TensorSpan.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <returns>TensorSpan<T>.</returns>
public static TensorSpan<T> ToTensorSpan<T>(this TensorSpan<T> tensor)
{
return new TensorSpan<T>(tensor.Span.ToArray(), tensor.Dimensions);
}
/// <summary>
/// TensorSpan view of the ImageTensor.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <returns>ImageTensor.</returns>
public static ImageTensor ToImageTensor(this TensorSpan<float> tensor)
{
return tensor.ToTensor().AsImageTensor();
}
/// <summary>
/// VideoTensor view of the TensorSpan.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="framerate">The framerate.</param>
/// <returns>VideoTensor.</returns>
public static VideoTensor ToVideoTensor(this TensorSpan<float> tensor, float framerate)
{
return tensor.ToTensor().AsVideoTensor(framerate);
}
/// <summary>
/// TensorSpan view of the Tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <returns>TensorSpan<T>.</returns>
public static TensorSpan<T> AsTensorSpan<T>(this Tensor<T> tensor)
{
return new TensorSpan<T>(tensor.Memory.Span, tensor.Dimensions);
}
/// <summary>
/// ImageTensor view of the Tensor.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <returns>ImageTensor.</returns>
public static ImageTensor AsImageTensor(this Tensor<float> tensor)
{
return new ImageTensor(tensor);
}
/// <summary>
/// VideoTensor view of the Tensor.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="framerate">The framerate.</param>
/// <returns>VideoTensor.</returns>
public static VideoTensor AsVideoTensor(this Tensor<float> tensor, float framerate)
{
return new VideoTensor(tensor, framerate);
}
/// <summary>
/// Repeats the specified Tensor across axis 0.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <param name="count">The count.</param>
/// <param name="axis">The axis.</param>
/// <returns>Tensor<T>.</returns>
/// <exception cref="NotImplementedException">Only axis 0 is supported</exception>
public static Tensor<T> Repeat<T>(this Tensor<T> tensor, int count, int axis = 0)
{
if (count == 1)
return tensor;
if (axis != 0)
throw new NotImplementedException("Only axis 0 is supported");
var dimensions = tensor.Dimensions.ToArray();
dimensions[0] *= count;
var length = (int)tensor.Length;
var totalLength = length * count;
var buffer = new T[totalLength].AsMemory();
for (int i = 0; i < count; i++)
{
tensor.Memory.CopyTo(buffer[(i * length)..]);
}
return new Tensor<T>(buffer, dimensions);
}
/// <summary>
/// Permutes the specified Tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor">The tensor.</param>
/// <param name="permutation">The permutation.</param>
/// <returns>Tensor<T>.</returns>
public static Tensor<T> Permute<T>(this Tensor<T> tensor, int[] permutation)
{
var dimensions = tensor.Dimensions.ToArray();
var newDimensions = permutation.Select(i => dimensions[i]).ToArray();
var resultTensor = new Tensor<T>(newDimensions);
var originalIndex = new int[dimensions.Length];
var permutedIndex = new int[newDimensions.Length];
for (int i = 0; i < tensor.Length; i++)
{
int remaining = i;
for (int j = dimensions.Length - 1; j >= 0; j--)
{
originalIndex[j] = remaining % dimensions[j];
remaining /= dimensions[j];
}
for (int j = 0; j < newDimensions.Length; j++)
{
permutedIndex[j] = originalIndex[permutation[j]];
}
var multiplier = 1;
var permutedFlatIndex = 0;
for (int j = newDimensions.Length - 1; j >= 0; j--)
{
permutedFlatIndex += permutedIndex[j] * multiplier;
multiplier *= newDimensions[j];
}
resultTensor.Memory.Span[permutedFlatIndex] = tensor.Memory.Span[i];
}
return resultTensor;
}
/// <summary>
/// Splits the specified Tensors across axis 0.
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <param name="axis">The axis.</param>
/// <returns>IEnumerable<Tensor<System.Single>>.</returns>
/// <exception cref="NotImplementedException">Only axis 0 is supported</exception>
public static IEnumerable<Tensor<float>> Split(this Tensor<float> tensor, int axis = 0)
{
if (axis != 0)
throw new NotImplementedException("Only axis 0 is supported");
var count = tensor.Dimensions[0];
var dimensions = tensor.Dimensions.ToArray();
dimensions[0] = 1;
var newLength = (int)tensor.Length / count;
for (int i = 0; i < count; i++)
{
var start = i * newLength;
yield return new Tensor<float>(tensor.Memory.Slice(start, newLength), dimensions);
}
}
/// <summary>
/// Joins the specified Tensors across axis 0.
/// </summary>
/// <param name="tensors">The tensors.</param>
/// <param name="axis">The axis.</param>
/// <returns>Tensor<System.Single>.</returns>
/// <exception cref="NotImplementedException">Only axis 0 is supported</exception>
public static Tensor<float> Join(this IEnumerable<Tensor<float>> tensors, int axis = 0)
{
if (axis != 0)
throw new NotImplementedException("Only axis 0 is supported");
var count = tensors.Count();
var tensor = tensors.First();
var dimensions = tensor.Dimensions.ToArray();
dimensions[0] *= count;
var newLength = (int)tensor.Length;
var buffer = new float[newLength * count].AsMemory();
var index = 0;
foreach (var item in tensors)
{
var start = index * newLength;
item.Memory.CopyTo(buffer[start..]);
index++;
}
return new Tensor<float>(buffer, dimensions);
}
/// <summary>
/// Generates the next random tensor
/// </summary>
/// <param name="random">The random.</param>
/// <param name="dimensions">The dimensions.</param>
/// <param name="initNoiseSigma">The initialize noise sigma.</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> NextTensor(this Random random, ReadOnlySpan<int> dimensions, float initNoiseSigma = 1f)
{
var latents = new Tensor<float>(dimensions);
for (int i = 0; i < latents.Length; i++)
{
var u1 = random.NextSingle();
var u2 = random.NextSingle();
var radius = MathF.Sqrt(-2.0f * MathF.Log(u1));
var theta = 2.0f * MathF.PI * u2;
var standardNormalRand = radius * MathF.Cos(theta);
latents.SetValue(i, standardNormalRand * initNoiseSigma);
}
return latents;
}
/// <summary>
/// Gets the total product for the specified dimensions.
/// </summary>
/// <param name="dimensions">The dimensions.</param>
/// <param name="startIndex">The start index.</param>
/// <returns>System.Int64.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static long GetProduct(this ReadOnlySpan<int> dimensions, int startIndex = 0)
{
long product = 1;
for (int i = startIndex; i < dimensions.Length; i++)
{
if (dimensions[i] < 0)
throw new ArgumentOutOfRangeException($"{nameof(dimensions)}[{i}]");
product *= dimensions[i];
}
return product;
}
/// <summary>
/// Gets the strides for the specified dimensions.
/// </summary>
/// <param name="dimensions">The dimensions.</param>
/// <returns>System.Int32[].</returns>
public static int[] GetStrides(this ReadOnlySpan<int> dimensions)
{
var strides = new int[dimensions.Length];
if (dimensions.Length == 0)
return strides;
int stride = 1;
for (int i = strides.Length - 1; i >= 0; i--)
{
strides[i] = stride;
stride *= dimensions[i];
}
return strides;
}
/// <summary>
/// Gets the tensor index with the specified indices and strides.
/// </summary>
/// <param name="indices">The indices.</param>
/// <param name="strides">The strides.</param>
/// <param name="startFromDimension">The start from dimension.</param>
/// <returns>System.Int32.</returns>
public static int GetIndex(this ReadOnlySpan<int> indices, ReadOnlySpan<int> strides, int startFromDimension = 0)
{
int index = 0;
for (int i = startFromDimension; i < indices.Length; i++)
{
index += strides[i] * indices[i];
}
return index;
}
/// <summary>
/// Normalizes the values from range -1 to 1 to 0 to 1.
/// </summary>
/// <param name="span">The span.</param>
public static void NormalizeOneOneToZeroOne(this Span<float> span)
{
for (int i = 0; i < span.Length; i++)
{
span[i] = Math.Clamp(span[i] / 2f + 0.5f, 0f, 1f);
}
}
/// <summary>
/// Normalizes the values from range 0 to 1 to -1 to 1.
/// </summary>
/// <param name="span">The span.</param>
public static void NormalizeZeroOneToOneOne(this Span<float> span)
{
for (int i = 0; i < span.Length; i++)
{
span[i] = Math.Clamp(2f * span[i] - 1f, -1f, 1f);
}
}
/// <summary>
/// Min/Max normalizaton to zero to one.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>Span<System.Single>.</returns>
public static Span<float> NormalizeMinMaxToZeroToOne(this Span<float> values)
{
float min = float.PositiveInfinity;
float max = float.NegativeInfinity;
for (int i = 0; i < values.Length; i++)
{
float value = values[i];
if (value < min) min = value;
if (value > max) max = value;
}
float range = max - min;
for (int i = 0; i < values.Length; i++)
{
values[i] = Math.Clamp((values[i] - min) / range, 0f, 1f);
}
return values;
}
/// <summary>
/// Min/Max normalizaton to one to one.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>Span<System.Single>.</returns>
public static Span<float> NormalizeMinMaxToOneToOne(this Span<float> values)
{
float min = float.PositiveInfinity;
float max = float.NegativeInfinity;
for (int i = 0; i < values.Length; i++)
{
float value = values[i];
if (value < min)
min = value;
if (value > max)
max = value;
}
float range = max - min;
for (int i = 0; i < values.Length; i++)
{
values[i] = Math.Clamp(2 * (values[i] - min) / range - 1, -1f, 1f);
}
return values;
}
/// <summary>
/// Normalizes the tensor values from range 1 to 1 to 0 to 1.
/// </summary>
/// <param name="tensor">The tensor.</param>
public static void NormalizeOneOneToZeroOne(this Tensor<float> tensor)
{
tensor.Memory.Span.NormalizeOneOneToZeroOne();
}
/// <summary>
/// Normalizes the tensor values from range 0 to 1 to -1 to 1.
/// </summary>
/// <param name="tensor">The tensor.</param>
public static void NormalizeZeroOneToOneOne(this Tensor<float> tensor)
{
tensor.Memory.Span.NormalizeZeroOneToOneOne();
}
/// <summary>
/// Concatenates the specified tensors along the specified axis.
/// </summary>
/// <param name="tensor1">The tensor1.</param>
/// <param name="tensor2">The tensor2.</param>
/// <param name="axis">The axis.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException">Only axis 0,1,2 is supported</exception>
public static Tensor<T> Concatenate<T>(this Tensor<T> tensor1, Tensor<T> tensor2, int axis = 0)
{
if (tensor1 == null)
return tensor2.Clone();
return axis switch
{
0 => ConcatenateAxis0(tensor1, tensor2),
1 => ConcatenateAxis1(tensor1, tensor2),
2 => ConcatenateAxis2(tensor1, tensor2),
_ => throw new NotImplementedException("Only axis 0, 1, 2 is supported")
};
}
/// <summary>
/// Concatenates Axis 0.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor1">The tensor1.</param>
/// <param name="tensor2">The tensor2.</param>
/// <returns>Tensor<T>.</returns>
private static Tensor<T> ConcatenateAxis0<T>(this Tensor<T> tensor1, Tensor<T> tensor2)
{
var dimensions = tensor1.Dimensions.ToArray();
dimensions[0] += tensor2.Dimensions[0];
var buffer = new Tensor<T>(dimensions);
tensor1.Memory.Span.CopyTo(buffer.Memory.Span[..(int)tensor1.Length]);
tensor2.Memory.Span.CopyTo(buffer.Memory.Span[(int)tensor1.Length..]);
return buffer;
}
/// <summary>
/// Concatenates Axis 1.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor1">The tensor1.</param>
/// <param name="tensor2">The tensor2.</param>
/// <returns>Tensor<T>.</returns>
/// <exception cref="System.ArgumentException">Length 2, 3 or 4 currently supported</exception>
private static Tensor<T> ConcatenateAxis1<T>(Tensor<T> tensor1, Tensor<T> tensor2)
{
var dimensions = tensor1.Dimensions.ToArray();
dimensions[1] += tensor2.Dimensions[1];
var concatenatedTensor = new Tensor<T>(dimensions);
if (tensor1.Dimensions.Length == 2)
{
for (int i = 0; i < tensor1.Dimensions[0]; i++)
for (int j = 0; j < tensor1.Dimensions[1]; j++)
concatenatedTensor[i, j] = tensor1[i, j];
for (int i = 0; i < tensor1.Dimensions[0]; i++)
for (int j = 0; j < tensor2.Dimensions[1]; j++)
concatenatedTensor[i, j + tensor1.Dimensions[1]] = tensor2[i, j];
}
else if (tensor1.Dimensions.Length == 3)
{
for (int i = 0; i < tensor1.Dimensions[0]; i++)
for (int j = 0; j < tensor1.Dimensions[1]; j++)
for (int k = 0; k < tensor1.Dimensions[2]; k++)
concatenatedTensor[i, j, k] = tensor1[i, j, k];
for (int i = 0; i < tensor2.Dimensions[0]; i++)
for (int j = 0; j < tensor2.Dimensions[1]; j++)
for (int k = 0; k < tensor2.Dimensions[2]; k++)
concatenatedTensor[i, j + tensor1.Dimensions[1], k] = tensor2[i, j, k];
}
else if (tensor1.Dimensions.Length == 4)
{
for (int i = 0; i < tensor1.Dimensions[0]; i++)
for (int j = 0; j < tensor1.Dimensions[1]; j++)
for (int k = 0; k < tensor1.Dimensions[2]; k++)
for (int l = 0; l < tensor1.Dimensions[3]; l++)
concatenatedTensor[i, j, k, l] = tensor1[i, j, k, l];
for (int i = 0; i < tensor2.Dimensions[0]; i++)
for (int j = 0; j < tensor2.Dimensions[1]; j++)
for (int k = 0; k < tensor2.Dimensions[2]; k++)
for (int l = 0; l < tensor2.Dimensions[3]; l++)
concatenatedTensor[i, j + tensor1.Dimensions[1], k, l] = tensor2[i, j, k, l];
}
else
{
throw new ArgumentException("Length 2, 3 or 4 currently supported");
}
return concatenatedTensor;
}
/// <summary>
/// Concatenates Axis 2.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tensor1">The tensor1.</param>
/// <param name="tensor2">The tensor2.</param>
/// <returns>Tensor<T>.</returns>
private static Tensor<T> ConcatenateAxis2<T>(Tensor<T> tensor1, Tensor<T> tensor2)
{
var dimensions = tensor1.Dimensions.ToArray();
dimensions[2] += tensor2.Dimensions[2];
var concatenatedTensor = new Tensor<T>(dimensions);
for (int i = 0; i < dimensions[0]; i++)
for (int j = 0; j < dimensions[1]; j++)
for (int k = 0; k < tensor1.Dimensions[2]; k++)
concatenatedTensor[i, j, k] = tensor1[i, j, k];
for (int i = 0; i < dimensions[0]; i++)
for (int j = 0; j < dimensions[1]; j++)
for (int k = 0; k < tensor2.Dimensions[2]; k++)
concatenatedTensor[i, j, k + tensor1.Dimensions[2]] = tensor2[i, j, k];
return concatenatedTensor;
}
/// <summary>
/// Computes the softmax function over the specified tensor
/// </summary>
/// <param name="tensor">The tensor.</param>
/// <returns>Tensor<System.Single>.</returns>
public static Tensor<float> SoftMax(this Tensor<float> tensor)
{
TensorPrimitives.SoftMax(tensor.Memory.Span, tensor.Memory.Span);
return tensor;
}
/// <summary>
/// Resizes the specified ImageTensor
/// </summary>
/// <param name="sourceImage">The source image.</param>
/// <param name="targetWidth">Width of the target.</param>
/// <param name="targetHeight">Height of the target.</param>
/// <param name="resizeMode">The resize mode.</param>
/// <param name="resizeMethod">The resize method.</param>
/// <returns>ImageTensor.</returns>
public static ImageTensor ResizeImage(this ImageTensor sourceImage, int targetWidth, int targetHeight, ResizeMode resizeMode = ResizeMode.Stretch, ResizeMethod resizeMethod = ResizeMethod.Bicubic)
{
return resizeMethod switch
{
ResizeMethod.Bicubic => ResizeImageBicubic(sourceImage, targetWidth, targetHeight, resizeMode),
_ => ResizeImageBilinear(sourceImage, targetWidth, targetHeight, resizeMode),
};
}
/// <summary>
/// Resizes the specified ImageTensor (Bilinear)
/// </summary>
/// <param name="sourceImage">The input.</param>
/// <param name="targetWidth">Width of the target.</param>
/// <param name="targetHeight">Height of the target.</param>
/// <returns>ImageTensor.</returns>
private static ImageTensor ResizeImageBilinear(ImageTensor sourceImage, int targetWidth, int targetHeight, ResizeMode resizeMode)
{
var channels = sourceImage.Dimensions[1];
var sourceHeight = sourceImage.Dimensions[2];
var sourceWidth = sourceImage.Dimensions[3];
var cropSize = GetCropCoordinates(sourceHeight, sourceWidth, targetHeight, targetWidth, resizeMode);
var destination = new ImageTensor(new[] { 1, channels, targetHeight, targetWidth });
Parallel.For(0, channels, c =>
{
for (int h = 0; h < cropSize.MaxY; h++)
{
for (int w = 0; w < cropSize.MaxX; w++)
{
var y = h * (float)(sourceHeight - 1) / (cropSize.MaxY - 1);
var x = w * (float)(sourceWidth - 1) / (cropSize.MaxX - 1);
var y0 = (int)Math.Floor(y);
var x0 = (int)Math.Floor(x);
var y1 = Math.Min(y0 + 1, sourceHeight - 1);
var x1 = Math.Min(x0 + 1, sourceWidth - 1);
var dy = y - y0;
var dx = x - x0;
var topLeft = sourceImage[0, c, y0, x0];
var topRight = sourceImage[0, c, y0, x1];
var bottomLeft = sourceImage[0, c, y1, x0];
var bottomRight = sourceImage[0, c, y1, x1];
var targetY = h - cropSize.MinY;
var targetX = w - cropSize.MinX;
if (targetX >= 0 && targetY >= 0 && targetY < destination.Height && targetX < destination.Width)
{
destination[0, c, targetY, targetX] =
topLeft * (1 - dx) * (1 - dy) +
topRight * dx * (1 - dy) +
bottomLeft * (1 - dx) * dy +
bottomRight * dx * dy;
}
}
}
});
return destination;
}
/// <summary>
/// Resizes the specified ImageTensor (ResizeImageBicubic)
/// </summary>
/// <param name="sourceImage">The input.</param>
/// <param name="targetWidth">Width of the target.</param>
/// <param name="targetHeight">Height of the target.</param>
/// <returns>ImageTensor.</returns>
private static ImageTensor ResizeImageBicubic(ImageTensor sourceImage, int targetWidth, int targetHeight, ResizeMode resizeMode = ResizeMode.Stretch)
{
var channels = sourceImage.Dimensions[1];
var sourceHeight = sourceImage.Dimensions[2];
var sourceWidth = sourceImage.Dimensions[3];
var cropSize = GetCropCoordinates(sourceHeight, sourceWidth, targetHeight, targetWidth, resizeMode);
var destination = new ImageTensor(new[] { 1, channels, targetHeight, targetWidth });
Parallel.For(0, channels, c =>
{
for (int h = 0; h < cropSize.MaxY; h++)
{
for (int w = 0; w < cropSize.MaxX; w++)
{
float y = h * (float)(sourceHeight - 1) / (cropSize.MaxY - 1);
float x = w * (float)(sourceWidth - 1) / (cropSize.MaxX - 1);
int yInt = (int)Math.Floor(y);
int xInt = (int)Math.Floor(x);
float yFrac = y - yInt;
float xFrac = x - xInt;
float[] colVals = new float[4];
for (int i = -1; i <= 2; i++)
{
int yi = Math.Clamp(yInt + i, 0, sourceHeight - 1);
float[] rowVals = new float[4];
for (int j = -1; j <= 2; j++)
{
int xi = Math.Clamp(xInt + j, 0, sourceWidth - 1);
rowVals[j + 1] = sourceImage[0, c, yi, xi];
}
colVals[i + 1] = CubicInterpolate(rowVals[0], rowVals[1], rowVals[2], rowVals[3], xFrac);
}
var targetY = h - cropSize.MinY;
var targetX = w - cropSize.MinX;
if (targetX >= 0 && targetY >= 0 && targetY < targetHeight && targetX < targetWidth)
{
destination[0, c, h, w] = CubicInterpolate(colVals[0], colVals[1], colVals[2], colVals[3], yFrac);
}
}
}
});
return destination;
}
/// <summary>
/// Cubic interpolate.
/// </summary>
/// <param name="v0">The v0.</param>
/// <param name="v1">The v1.</param>
/// <param name="v2">The v2.</param>
/// <param name="v3">The v3.</param>
/// <param name="fraction">The fraction.</param>
/// <returns>System.Single.</returns>
private static float CubicInterpolate(float v0, float v1, float v2, float v3, float fraction)
{
float A = (-0.5f * v0) + (1.5f * v1) - (1.5f * v2) + (0.5f * v3);
float B = (v0 * -1.0f) + (v1 * 2.5f) - (v2 * 2.0f) + (v3 * 0.5f);
float C = (-0.5f * v0) + (0.5f * v2);
float D = v1;
return A * (fraction * fraction * fraction) + B * (fraction * fraction) + C * fraction + D;
}
/// <summary>
/// Gets the crop coordinates.
/// </summary>
/// <param name="sourceHeight">Height of the source.</param>
/// <param name="sourceWidth">Width of the source.</param>
/// <param name="targetHeight">Height of the target.</param>
/// <param name="targetWidth">Width of the target.</param>
/// <param name="resizeMode">The resize mode.</param>
/// <returns>CoordinateBox<System.Int32>.</returns>
private static CoordinateBox<int> GetCropCoordinates(int sourceHeight, int sourceWidth, int targetHeight, int targetWidth, ResizeMode resizeMode)
{
var cropX = 0;
var cropY = 0;
var croppedWidth = targetWidth;
var croppedHeight = targetHeight;
if (resizeMode == ResizeMode.Crop)
{
var scaleX = (float)targetWidth / sourceWidth;
var scaleY = (float)targetHeight / sourceHeight;
var scaleFactor = Math.Max(scaleX, scaleY);
croppedWidth = (int)(sourceWidth * scaleFactor);
croppedHeight = (int)(sourceHeight * scaleFactor);
cropX = Math.Abs(Math.Max((croppedWidth - targetWidth) / 2, 0));
cropY = Math.Abs(Math.Max((croppedHeight - targetHeight) / 2, 0));
}
return new CoordinateBox<int>(cropX, cropY, croppedWidth, croppedHeight);
}
}
}