forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_ops.cs
More file actions
1143 lines (1022 loc) · 49.4 KB
/
array_ops.cs
File metadata and controls
1143 lines (1022 loc) · 49.4 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
/*****************************************************************************
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.
******************************************************************************/
using Tensorflow.NumPy;
using System;
using System.Collections.Generic;
using System.Linq;
using Tensorflow.Contexts;
using Tensorflow.Eager;
using Tensorflow.Framework;
using static Tensorflow.Binding;
using System.Diagnostics;
namespace Tensorflow
{
public class array_ops
{
public static Tensor placeholder_with_default(Tensor input, int[] shape, string name = null)
=> gen_array_ops.placeholder_with_default(input, shape, name);
/// <summary>
/// An identity op that triggers an error if a gradient is requested.
/// </summary>
/// <param name="input">
/// any tensor.
/// </param>
/// <param name="name">
/// If specified, the created operation in the graph will be this one, otherwise it will be named 'PreventGradient'.
/// </param>
/// <param name="message">
/// Will be printed in the error when anyone tries to differentiate
/// this operation.
/// </param>
/// <returns>
/// the same input tensor.
/// The Operation can be fetched from the resulting Tensor, by fetching the Operation property from the result.
/// </returns>
/// <remarks>
/// When executed in a graph, this op outputs its input tensor as-is.
///
/// When building ops to compute gradients, the TensorFlow gradient system
/// will return an error when trying to lookup the gradient of this op,
/// because no gradient must ever be registered for this function. This
/// op exists to prevent subtle bugs from silently returning unimplemented
/// gradients in some corner cases.
/// </remarks>
public static Tensor prevent_gradient(Tensor input, string message = "", string name = null)
=> tf.Context.ExecuteOp("PreventGradient", name, new ExecuteOpArgs(input)
.SetAttributes(new { message }));
internal static Tensor constant(object value,
TF_DataType dtype = TF_DataType.DtInvalid,
int[] shape = null,
string name = "Const",
bool verify_shape = false) => constant_op.constant(value,
dtype: dtype,
shape: shape,
name: name,
verify_shape: verify_shape,
allow_broadcast: false);
public static Tensor zeros(Shape shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
{
dtype = dtype.as_base_dtype();
if (tf.executing_eagerly())
{
return tf_with(ops.name_scope(name, "zeros", shape), scope =>
{
name = scope;
// var shape_tensor = constant_op._tensor_shape_tensor_conversion_function(shape);
Tensor zeros = dtype switch
{
TF_DataType.TF_BOOL => constant(false),
TF_DataType.TF_DOUBLE => constant(0d),
TF_DataType.TF_FLOAT => constant(0f),
TF_DataType.TF_INT64 => constant(0L),
TF_DataType.TF_UINT64 => constant((ulong)0),
TF_DataType.TF_INT32 => constant(0),
TF_DataType.TF_UINT32 => constant((uint)0),
TF_DataType.TF_INT8 => constant((sbyte)0),
TF_DataType.TF_UINT8 => constant((byte)0),
_ => constant(0)
};
return fill(shape, zeros, name: name);
});
}
else
{
return tf_with(ops.name_scope(name, "zeros", shape), scope =>
{
name = scope;
switch (dtype)
{
case TF_DataType.TF_BOOL:
return _constant_if_small(false, shape, dtype, name);
case TF_DataType.TF_DOUBLE:
return _constant_if_small(0.0D, shape, dtype, name);
case TF_DataType.TF_FLOAT:
return _constant_if_small(0.0F, shape, dtype, name);
case TF_DataType.TF_INT64:
return _constant_if_small(0L, shape, dtype, name);
case TF_DataType.TF_UINT64:
return _constant_if_small<ulong>(0, shape, dtype, name);
case TF_DataType.TF_INT32:
return _constant_if_small(0, shape, dtype, name);
case TF_DataType.TF_UINT32:
return _constant_if_small<uint>(0, shape, dtype, name);
case TF_DataType.TF_INT8:
return _constant_if_small<sbyte>(0, shape, dtype, name);
case TF_DataType.TF_UINT8:
return _constant_if_small<byte>(0, shape, dtype, name);
default:
throw new TypeError("can't find type for zeros");
}
});
}
}
public static Tensor zeros(Tensors shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
{
dtype = dtype.as_base_dtype();
Tensor shapeTensor;
if(shape.Length > 1)
{
shapeTensor = ops.convert_to_tensor(shape, dtypes.int32);
if (shapeTensor.ndim > 1)
{
shapeTensor = array_ops.reshape(shapeTensor, new Shape(-1));
}
}
else
{
shapeTensor = shape[0];
}
var output = fill(shapeTensor, array_ops.constant(0, dtype), name);
Debug.Assert(output.dtype.as_base_dtype() == dtype);
return output;
}
public static Tensor boolean_mask<T1, T2>(T1 tensor, T2 mask, string name = "boolean_mask", int axis = 0)
{
return tf_with(ops.name_scope(name, values: new { tensor, mask }), delegate
{
var tensor_tensor = ops.convert_to_tensor(tensor, name: "tensor");
var mask_tensor = ops.convert_to_tensor(mask, name: "mask");
var shape_mask = mask_tensor.shape;
var ndims_mask = shape_mask.ndim;
var shape_tensor = tensor_tensor.shape;
if (ndims_mask < 1)
throw new ValueError("mask cannot be scalar.");
var leading_size = gen_math_ops.prod(shape(tensor_tensor)[$"{axis}:{axis + ndims_mask}"], ops.convert_to_tensor(new[] { 0 }));
var shape1 = concat(new[]
{
shape(tensor_tensor)[$":{axis}"],
leading_size,
shape(tensor_tensor)[$"{axis + ndims_mask}:"]
}, 0);
tensor_tensor = reshape(tensor_tensor, shape1);
var first_dim = shape_tensor.dims.Skip(axis).Take(ndims_mask).First();
var s1 = new Shape(shape_tensor.dims.Take(axis).ToArray());
var s2 = s1.concatenate(new[] { first_dim }).concatenate(shape_tensor.dims.Skip(axis + ndims_mask).ToArray());
tensor_tensor.shape = s2;
mask_tensor = reshape(mask_tensor, new[] { -1 });
return _apply_mask_1d(tensor_tensor, mask_tensor, axis);
});
}
private static Tensor _apply_mask_1d(Tensor reshaped_tensor, Tensor mask, int axis = 0)
{
var indices = squeeze(where(mask), axis: new[] { 1 });
return gather(reshaped_tensor, indices, axis: ops.convert_to_tensor(axis));
}
public static Tensor zeros(Tensor shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
{
dtype = dtype.as_base_dtype();
return tf_with(ops.name_scope(name, "zeros", shape), scope =>
{
name = scope;
switch (dtype)
{
case TF_DataType.TF_BOOL:
return gen_array_ops.fill(shape, tf.constant(false, dtype: dtype), name: name);
case TF_DataType.TF_DOUBLE:
return gen_array_ops.fill(shape, tf.constant(0.0D, dtype: dtype), name: name);
case TF_DataType.TF_FLOAT:
return gen_array_ops.fill(shape, tf.constant(0.0F, dtype: dtype), name: name);
case TF_DataType.TF_INT32:
return gen_array_ops.fill(shape, tf.constant(0, dtype: dtype), name: name);
default:
throw new TypeError("can't find type for zeros");
}
});
}
private static Tensor _constant_if_small(int value, Tensor shape)
{
if (shape.dtype == TF_DataType.TF_INT64)
return shape < 1000L;
else
return shape < 1000;
}
private static Tensor _constant_if_small<T>(T value, Shape shape, TF_DataType dtype, string name)
{
if (shape.size < 1000)
{
return constant_op.constant(value, shape: shape, dtype: dtype, name: name);
}
else
{
var shape_t = constant_op._tensor_shape_tensor_conversion_function(shape);
var c = constant_op.constant(0, dtype: dtype);
return gen_array_ops.fill(shape_t, c, name: name);
}
}
public static Tensor _autopacking_conversion_function(IEnumerable<object> v, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool as_ref = false)
{
var inferred_dtype = _get_dtype_from_nested_lists(v);
if (dtype == TF_DataType.DtInvalid)
dtype = inferred_dtype;
return _autopacking_helper(v, dtype, name == null ? "packed" : name);
}
private static TF_DataType _get_dtype_from_nested_lists<T>(IEnumerable<T> list_or_tuple)
{
TF_DataType dtype = TF_DataType.DtInvalid;
foreach (var obj in list_or_tuple)
{
switch (obj)
{
case Tensor t:
dtype = t.dtype.as_base_dtype();
break;
case int t:
dtype = TF_DataType.TF_INT32;
break;
}
if (dtype != TF_DataType.DtInvalid)
break;
}
return dtype;
}
/// <summary>
/// Converts the given list or tuple to a tensor by packing.
/// </summary>
/// <param name="list_or_tuple">A (possibly nested) list or tuple containing a tensor.</param>
/// <param name="dtype"></param>
/// <param name="name"></param>
/// <returns>A `tf.Tensor` with value equivalent to `list_or_tuple`.</returns>
public static Tensor _autopacking_helper(IEnumerable<object> list_or_tuple, TF_DataType dtype, string name)
{
var must_pack = false;
var converted_elems = new List<object>();
bool switch_to_graph = tf.Context.switched_to_graph(list_or_tuple.ToArray());
var result = tf_with(ops.name_scope(name), scope =>
{
foreach (var (i, elem) in enumerate(list_or_tuple))
{
converted_elems.Add(elem);
must_pack = true;
}
if (must_pack)
{
var elems_as_tensors = new List<Tensor>();
foreach (var (i, elem) in enumerate(converted_elems))
{
if (elem is EagerTensor eager_tensor)
{
if (switch_to_graph)
elems_as_tensors.Add(constant_op.constant(eager_tensor.numpy(), dtype: dtype, name: i.ToString()));
else
elems_as_tensors.Add(eager_tensor);
}
else if (elem is Tensor tensor)
{
elems_as_tensors.Add(tensor);
}
else if (elem is KerasTensor kt)
{
elems_as_tensors.Add(kt);
}
else
{
var elem_tensor = constant_op.constant(elem, dtype: dtype, name: i.ToString());
elems_as_tensors.Add(elem_tensor);
}
}
return gen_array_ops.pack(elems_as_tensors.ToArray(), name: scope);
}
else
{
return tf.constant(np.array(new float[0]));
}
});
if (switch_to_graph)
tf.Context.restore_mode();
return result;
}
public static Tensor expand_dims(Tensor input, int axis = -1, string name = null)
=> gen_array_ops.expand_dims(input, ops.convert_to_tensor(axis), name);
/// <summary>
/// Creates a tensor filled with a scalar value.
/// This operation creates a tensor of shape `dims` and fills it with `value`.
/// </summary>
/// <param name="dims">A 1-D sequence of non-negative numbers.</param>
/// <param name="value">A value to fill the returned `tf.Tensor`.</param>
/// <param name="name">Optional string. The name of the output `tf.Tensor`.</param>
/// <returns>A `tf.Tensor` with shape `dims` and the same dtype as `value`.</returns>
public static Tensor fill<T>(Shape dims, T value, string name = null)
=> gen_array_ops.fill(dims, ops.convert_to_tensor(value), name: name);
public static Tensor fill<T>(Tensor dims, T value, string name = null)
=> gen_array_ops.fill(dims, ops.convert_to_tensor(value), name: name);
/// <summary>
/// Returns the rank of a tensor.
/// </summary>
/// <param name="input"></param>
/// <param name="name"></param>
/// <returns></returns>
public static Tensor rank(Tensor input, string name = null)
=> rank_internal(input, name, optimize: true);
public static Tensor rank_internal(Tensor input, string name = null, bool optimize = true)
{
return tf_with(ops.name_scope(name, "Rank", new List<Tensor> { input }), scope =>
{
name = scope;
var input_shape = input.shape;
if (optimize && input_shape.ndim > 0)
return constant_op.constant(input_shape.ndim, dtype: tf.int32, name: name);
else
return gen_array_ops.rank(input, name);
});
}
/// <summary>
/// Creates a tensor with all elements set to 1.
/// </summary>
/// <param name="tensor"></param>
/// <param name="dtype"></param>
/// <param name="name"></param>
/// <param name="optimize"></param>
/// <returns></returns>
public static Tensor ones_like(Tensor tensor, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool optimize = true)
{
return tf_with(ops.name_scope(name, "ones_like", new Tensor[] { tensor }), scope =>
{
name = scope;
tensor = ops.convert_to_tensor(tensor, name: "tensor");
// is_fully_defined return unexpected value.
if (optimize && tensor.shape.IsFullyDefined && dtype != TF_DataType.TF_VARIANT)
{
}
if (dtype != TF_DataType.DtInvalid && dtype != tensor.dtype && dtype != TF_DataType.TF_VARIANT)
{
throw new NotImplementedException("ones_like");
// return ones(shape_internal(tensor, optimize: optimize), dtype: dtype, name: name);
}
else
{
return gen_array_ops.ones_like(tensor, name: name);
}
});
}
public static Tensor reshape(Tensor tensor, Tensor shape, string name = null)
=> gen_array_ops.reshape(tensor, shape, name: name);
public static Tensor reshape(Tensor tensor, Shape shape, string name = null)
=> gen_array_ops.reshape(tensor, shape, name: name);
public static Tensor reshape(Tensor tensor, object[] shape, string name = null)
{
var dims = shape_utils.from_object_array(shape);
return gen_array_ops.reshape(tensor, dims, name: name);
}
public static Tensor reverse(Tensor tensor, Tensor axis, string name = null)
=> tf.Context.ExecuteOp("ReverseV2", name, new ExecuteOpArgs(tensor, axis)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
Tidx = op.get_attr<TF_DataType>("Tidx")
}
});
private static Tensor ones_like_impl<T>(T tensor, TF_DataType dtype, string name, bool optimize = true)
{
return tf_with(ops.name_scope(name, "ones_like", new { tensor }), scope =>
{
name = scope;
var tensor1 = ops.convert_to_tensor(tensor, name: "tensor");
var ones_shape = shape_internal(tensor1, optimize: optimize);
if (dtype == TF_DataType.DtInvalid)
dtype = tensor1.dtype;
var ret = ones(ones_shape, dtype: dtype, name: name);
return ret;
});
}
public static Tensor ones(Tensor shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
{
return tf_with(ops.name_scope(name, "ones", new { shape }), scope =>
{
name = scope;
if (shape._shape_tuple().Length == 0)
{
shape = reshape(shape, new Shape(-1));
}
var output = gen_array_ops.fill(shape, constant_op.constant(1.0f, dtype: dtype), name: name);
return output;
});
}
public static Tensor ones(Tensor[] shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
{
dtype = dtype.as_base_dtype();
return tf_with(ops.name_scope(name, "ones", new { shape }), scope =>
{
name = scope;
var output = _constant_if_small(1, shape[0]);
var shape1 = ops.convert_to_tensor(shape, dtype: TF_DataType.TF_INT32);
output = gen_array_ops.fill(shape1, constant_op.constant(1, dtype: dtype), name: name);
return output;
});
}
public static Tensor ones(Shape shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
=> tf_with(ops.name_scope(name, "ones", shape), scope =>
{
dtype = dtype.as_base_dtype();
name = scope;
Tensor ones = dtype switch
{
TF_DataType.TF_DOUBLE => constant(1.0d),
TF_DataType.TF_FLOAT => constant(1.0f),
_ => constant(1, dtype)
};
if (shape.ndim == 0)
return ones;
// var shape_tensor = constant_op._tensor_shape_tensor_conversion_function(shape);
return fill(shape, ones, name: name);
});
public static Tensor one_hot(Tensor indices, Tensor depth,
Tensor on_value = null,
Tensor off_value = null,
TF_DataType dtype = TF_DataType.DtInvalid,
int axis = -1,
string name = null)
{
return tf_with(ops.name_scope(name, "one_hot", new { indices, depth, dtype }), scope =>
{
name = scope;
var on_exists = false;
var off_exists = false;
var on_dtype = TF_DataType.DtInvalid;
var off_dtype = TF_DataType.DtInvalid;
if (dtype == TF_DataType.DtInvalid)
dtype = TF_DataType.TF_FLOAT;
if (!on_exists)
{
on_value = ops.convert_to_tensor(1, dtype, name: "on_value");
on_dtype = dtype;
}
if (!off_exists)
{
off_value = ops.convert_to_tensor(0, dtype, name = "off_value");
off_dtype = dtype;
}
return gen_array_ops.one_hot(indices, depth,
on_value: on_value,
off_value: off_value,
axis: axis,
name: name);
});
}
public static (Tensor, Tensor) unique(Tensor x, TF_DataType out_idx = TF_DataType.TF_INT32, string name = null)
{
var res = gen_array_ops.unique(x, out_idx: out_idx, name: name);
Debug.Assert(res.Length == 2);
return (res[0], res[1]);
}
public static Tensor stack(Tensor[] values, int axis = 0, string name = "stack")
{
if (axis == 0)
{
return ops.convert_to_tensor(values, name: name);
}
return gen_array_ops.pack(values, axis: axis, name: name);
}
public static Tensor[] unstack(Tensor value, int? num = null, int axis = 0, string name = "unstack")
{
num = num ?? value.shape.as_int_list()[axis];
return gen_array_ops.unpack(value, num: num.Value, axis: axis, name: name);
}
public static Tensor where(Tensor condition, object x = null, object y = null, string name = null)
{
if (x == null && y == null)
{
return tf_with(ops.name_scope(name, "Where", new { condition }), scope =>
{
name = scope;
condition = ops.convert_to_tensor(condition, preferred_dtype: dtypes.@bool, name: "condition");
return gen_array_ops.where(condition, name: name);
});
}
else if (x != null && y != null)
{
return gen_math_ops.select(condition, ops.convert_to_tensor(x), ops.convert_to_tensor(y), name);
}
else
{
throw new ValueError("x and y must both be non-None or both be None.");
}
}
public static Tensor where_v2(Tensor condition, object x = null, object y = null, string name = null)
{
if (x == null && y == null)
{
return tf_with(ops.name_scope(name, "Where", new { condition }), scope =>
{
name = scope;
condition = ops.convert_to_tensor(condition, preferred_dtype: dtypes.@bool, name: "condition");
return gen_array_ops.where(condition, name: name);
});
}
else if (x != null && y != null)
{
return gen_math_ops.select_v2(condition, ops.convert_to_tensor(x), ops.convert_to_tensor(y), name);
}
else
{
throw new ValueError("x and y must both be non-None or both be None.");
}
}
/// <summary>
/// Returns the shape of a tensor.
/// </summary>
/// <param name="input">A `Tensor` or `SparseTensor`.</param>
/// <param name="name">A name for the operation (optional).</param>
/// <param name="out_type">
/// (Optional) The specified output type of the operation
/// (`int32` or `int64`). Defaults to `tf.int32`.
/// </param>
/// <returns>A `Tensor` of type `out_type`.</returns>
public static Tensor shape(Tensor input, string name = null, TF_DataType out_type = TF_DataType.TF_INT32)
=> shape_internal(input, name, optimize: true, out_type: out_type);
public static Tensor shape_v2(Tensor input, string name = null, TF_DataType out_type = TF_DataType.TF_INT32)
=> shape_internal(input, name, optimize: true, out_type: out_type);
public static Tensor size<T>(T input, string name = null, bool optimize = true, TF_DataType out_type = TF_DataType.TF_INT32)
=> size_internal(input, name, optimize: optimize, out_type: out_type);
public static Tensor shape_internal(Tensor input, string name = null, bool optimize = true, TF_DataType out_type = TF_DataType.TF_INT32)
{
return tf_with(ops.name_scope(name, "Shape", new { input }), scope =>
{
name = scope;
if (!tf.Context.executing_eagerly())
{
var input_shape = input.shape;
if (optimize && input.ndim > -1 && input_shape.IsFullyDefined)
{
if(out_type == TF_DataType.TF_INT32)
return constant_op.constant(input.shape.as_int_list(), name: name);
else
return constant_op.constant(input.shape.dims, name: name);
}
}
return tf.Context.ExecuteOp("Shape", name, new ExecuteOpArgs(input)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
out_type = op.get_attr<TF_DataType>("out_type")
}
}.SetAttributes(new
{
out_type
})).First();
});
}
private static Tensor size_internal<T>(T input, string name = null, bool optimize = true, TF_DataType out_type = TF_DataType.TF_INT32)
{
return tf_with(ops.name_scope(name, "Size", new { input }), scope =>
{
name = scope;
var input_tensor = ops.convert_to_tensor(input);
var input_shape = input_tensor.shape;
if (optimize)
{
if (input_shape.IsFullyDefined)
{
return constant_op.constant(input_shape.size, dtype: out_type, name: name);
}
}
return gen_array_ops.size(input_tensor, name: name, out_type: out_type);
});
}
public static Tensor tile(Tensor input, Tensor multiples, string name = null)
=> tf.Context.ExecuteOp("Tile", name, new ExecuteOpArgs(input, multiples)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
Tmultiples = op.get_attr<TF_DataType>("Tmultiples")
}
});
/*public static Tensor tile(Tensor input, Shape multiples, string name = null)
{
return tf.Context.ExecuteOp("Tile", name, new ExecuteOpArgs(input, multiples)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
Tmultiples = op.get_attr<TF_DataType>("Tmultiples")
}
});
}*/
public static Tensor zeros_like(Tensor tensor, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool optimize = true)
{
return tf_with(ops.name_scope(name, "zeros_like", new Tensor[] { tensor }), scope =>
{
name = scope;
tensor = ops.convert_to_tensor(tensor, name: "tensor");
// is_fully_defined return unexpected value.
if (optimize && tensor.shape.IsFullyDefined && dtype != TF_DataType.TF_VARIANT)
{
}
if (dtype != TF_DataType.DtInvalid && dtype != tensor.dtype && dtype != TF_DataType.TF_VARIANT)
{
throw new NotImplementedException("zeros_like");
// return zeros(shape_internal(tensor, optimize: optimize), dtype: dtype, name: name);
}
else
{
return gen_array_ops.zeros_like(tensor, name: name);
}
});
}
/// <summary>
/// When building ops to compute gradients, this op prevents the contribution of
/// its inputs to be taken into account.Normally, the gradient generator adds ops
/// to a graph to compute the derivatives of a specified 'loss' by recursively
/// finding out inputs that contributed to its computation.If you insert this op
/// in the graph it inputs are masked from the gradient generator. They are not
/// taken into account for computing gradients.
/// </summary>
/// <param name="input"></param>
/// <param name="name"></param>
/// <returns></returns>
public static Tensor stop_gradient(Tensor input, string name = null)
{
var tape = tf.GradientTape().stop_recording();
var result = gen_array_ops.stop_gradient(input, name);
tape.StartRecord();
return result;
}
/// <summary>
/// Extracts a strided slice of a tensor (generalized python array indexing).
/// </summary>
/// <param name="input_"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="strides"></param>
/// <param name="begin_mask"></param>
/// <param name="end_mask"></param>
/// <param name="ellipsis_mask"></param>
/// <param name="new_axis_mask"></param>
/// <param name="shrink_axis_mask"></param>
/// <param name="name"></param>
/// <returns></returns>
public static Tensor strided_slice(Tensor input_, Tensor begin, Tensor end,
Tensor strides = null,
int begin_mask = 0,
int end_mask = 0,
int ellipsis_mask = 0,
int new_axis_mask = 0,
int shrink_axis_mask = 0,
string name = null)
=> tf.Context.ExecuteOp("StridedSlice", name, new ExecuteOpArgs(input_, begin, end, strides)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
Index = op.get_attr<TF_DataType>("Index"),
begin_mask = op.get_attr<long>("begin_mask"),
end_mask = op.get_attr<long>("end_mask"),
ellipsis_mask = op.get_attr<long>("ellipsis_mask"),
new_axis_mask = op.get_attr<long>("new_axis_mask"),
shrink_axis_mask = op.get_attr<long>("shrink_axis_mask")
}
}.SetAttributes(new
{
begin_mask,
end_mask,
ellipsis_mask,
new_axis_mask,
shrink_axis_mask
}));
/// <summary>
/// Returns the gradient of `StridedSlice`.
///
/// Since `StridedSlice` cuts out pieces of its `input` which is size
/// `shape`, its gradient will have the same shape (which is passed here
/// as `shape`). The gradient will be zero in any element that the slice
/// does not select.
/// </summary>
/// <param name="shape">Must be one of the following types: `int32`, `int64`.</param>
/// <param name="begin">Must have the same type as `shape`.</param>
/// <param name="end">Must have the same type as `shape`.</param>
/// <param name="strides">Must have the same type as `shape`.</param>
/// <param name="dy">A `Tensor`.</param>
/// <param name="begin_mask">An optional `int`. Defaults to `0`.</param>
/// <param name="end_mask">An optional `int`. Defaults to `0`.</param>
/// <param name="ellipsis_mask">An optional `int`. Defaults to `0`.</param>
/// <param name="new_axis_mask">An optional `int`. Defaults to `0`.</param>
/// <param name="shrink_axis_mask">An optional `int`. Defaults to `0`.</param>
/// <param name="name">A name for the operation (optional).</param>
/// <returns>A `Tensor`. Has the same type as `dy`.</returns>
public static Tensor strided_slice_grad(Tensor shape, Tensor begin, Tensor end, Tensor strides, Tensor dy,
long begin_mask = 0, long end_mask = 0, long ellipsis_mask = 0, long new_axis_mask = 0,
long shrink_axis_mask = 0, string name = null)
=> tf.Context.ExecuteOp("StridedSliceGrad", name,
new ExecuteOpArgs(shape, begin, end, strides, dy)
{
GetGradientAttrs = (op) => new
{
T = op.get_attr<TF_DataType>("T"),
Index = op.get_attr<TF_DataType>("Index"),
begin_mask = op.get_attr<long>("begin_mask"),
end_mask = op.get_attr<long>("end_mask"),
ellipsis_mask = op.get_attr<long>("ellipsis_mask"),
new_axis_mask = op.get_attr<long>("new_axis_mask"),
shrink_axis_mask = op.get_attr<long>("shrink_axis_mask")
}
}.SetAttributes(new
{
begin_mask,
end_mask,
ellipsis_mask,
new_axis_mask,
shrink_axis_mask
}));
/// <summary>
/// Removes dimensions of size 1 from the shape of a tensor.
/// Given a tensor `input`, this operation returns a tensor of the same type with
/// all dimensions of size 1 removed.If you don't want to remove all size 1
/// dimensions, you can remove specific size 1 dimensions by specifying
/// `axis`.
/// </summary>
/// <param name="input"> A `Tensor`. The `input` to squeeze.</param>
/// <param name="axis"> An optional list of `ints`. Defaults to `[]`.
/// If specified, only squeezes the dimensions listed.The dimension
/// index starts at 0. It is an error to squeeze a dimension that is not 1.
/// Must be in the range `[-rank(input), rank(input))`.</param>
/// <param name="name"> A name for the operation (optional).</param>
/// <param name="squeeze_dims" >Deprecated keyword argument that is now axis.</param>
/// <returns>A `Tensor`. Has the same type as `input`.
/// Contains the same data as `input`, but has one or more dimensions of
/// size 1 removed.</returns>
public static Tensor squeeze(Tensor input, int[] axis = null, string name = null)
=> gen_array_ops.squeeze(input, axis, name);
public static Tensor identity(Tensor input, string name = null)
=> gen_array_ops.identity(input, name);
public static Tensor invert_permutation(Tensor x, string name = null)
=> gen_array_ops.invert_permutation(x, name: name);
public static Tensor matrix_diag(Tensor diagonal,
string name = "diag",
int k = 0,
int num_rows = -1,
int num_cols = -1,
float padding_value = 0f,
string align = "RIGHT_LEFT")
=> tf.Context.ExecuteOp("MatrixDiagV3", name,
new ExecuteOpArgs(diagonal, k, num_rows, num_cols, ops.convert_to_tensor(padding_value, dtype: diagonal.dtype))
.SetAttributes(new { align }));
public static Tensor matrix_set_diag(Tensor input,
Tensor diagonal,
string name = "set_diag",
int k = 0,
string align = "RIGHT_LEFT")
=> tf.Context.ExecuteOp("MatrixSetDiagV3", name, new ExecuteOpArgs(input, diagonal, k)
.SetAttributes(new { align }));
public static Tensor[] meshgrid<T>(T[] array, bool copy = true, bool sparse = false, string indexing = "xy")
{
return tf_with(ops.name_scope(null, "meshgrid", array), scope =>
{
var ndim = array.Length;
var s0 = range(ndim).Select(x => 1).ToArray();
var output = new List<Tensor>();
foreach (var (i, x) in enumerate(array))
{
var shape = s0.Take(i).ToArray().concat(new[] { -1 }).concat(s0.Skip(i + 1).ToArray());
output.add(reshape(stack(x), shape));
}
// Create parameters for broadcasting each tensor to the full size
var shapes = array.Select(x => size(x)).ToArray();
var output_dtype = _get_dtype_from_nested_lists(array).as_base_dtype();
if (indexing == "xy" && ndim > 1)
{
output[0] = reshape(output[0], new[] { 1, -1 }.concat(range(ndim - 2).Select(x => 1).ToArray()));
output[1] = reshape(output[1], new[] { -1, 1 }.concat(range(ndim - 2).Select(x => 1).ToArray()));
(shapes[0], shapes[1]) = (shapes[1], shapes[0]);
}
if(sparse)
return output.ToArray();
else
{
var mult_fact = ones(shapes, output_dtype);
return output.Select(x => x * mult_fact).ToArray();
}
});
}
public static Tensor moveaxis(NDArray array, Axis source, Axis destination)
{
List<int> perm = null;
source = source.axis.Select(x => x < 0 ? array.rank + x : x).ToArray();
destination = destination.axis.Select(x => x < 0 ? array.rank + x : x).ToArray();
if (array.shape.rank > -1)
{
perm = range(0, array.rank).Where(i => !source.axis.Contains(i)).ToList();
foreach (var (dest, src) in zip(destination.axis, source.axis).OrderBy(x => x.Item1))
{
perm.Insert(dest, src);
}
}
else
throw new NotImplementedException("");
return array_ops.transpose(array, perm.ToArray());
}
/// <summary>
/// Computes the shape of a broadcast given symbolic shapes.
/// When shape_x and shape_y are Tensors representing shapes(i.e.the result of
/// calling tf.shape on another Tensor) this computes a Tensor which is the shape
/// of the result of a broadcasting op applied in tensors of shapes shape_x and
/// shape_y.
/// For example, if shape_x is [1, 2, 3] and shape_y is [5, 1, 3], the result is a
/// Tensor whose value is [5, 2, 3].
/// This is useful when validating the result of a broadcasting operation when the
/// tensors do not have statically known shapes.
/// </summary>
/// <param name="shape_x"> A rank 1 integer `Tensor`, representing the shape of x.</param>
/// <param name="shape_y"> A rank 1 integer `Tensor`, representing the shape of y.</param>
/// <returns> A rank 1 integer `Tensor` representing the broadcasted shape.</returns>
public static Tensor broadcast_dynamic_shape(Tensor shape_x, Tensor shape_y)
=> gen_array_ops.broadcast_args(shape_x, shape_y);
public static Tensor broadcast_static_shape(Tensor shape_x, Tensor shape_y)
=> Framework.common_shapes.broadcast_shape(shape_x, shape_y);
/// <summary>
/// Concatenates tensors along one dimension.
/// </summary>
/// <param name="values"></param>
/// <param name="axis"></param>
/// <param name="name"></param>
/// <returns></returns>
public static Tensor concat(Tensor[] values, Tensor axis, string name = "concat")
{
return tf.Context.ExecuteOp("ConcatV2", name, new ExecuteOpArgs(values, axis));
}
public static Tensor concat(object[] values, int axis, string name = "concat")
{
return tf.Context.ExecuteOp("ConcatV2", name, new ExecuteOpArgs(values, axis));
}
/// <summary>
/// Gather slices from `params` according to `indices`. `indices` must be an integer tensor of any dimension(often 1-D).
/// </summary>
/// <typeparam name="T1">Element type of the indexed tensor.</typeparam>
/// <typeparam name="T2">Element type of the index tensor.</typeparam>
/// <param name="params">The `Tensor` from which to gather values. Must be at least rank `axis + 1`.</param>
/// <param name="indices">The index `Tensor`. Must be one of the following types: `int32`, `int64`. The values must be in range `[0, params.shape[axis])`.</param>
/// <param name="name">A name for the operation (optional).</param>
/// <param name="axis">
/// A `Tensor`. Must be one of the following types: `int32`, `int64`.
/// The `axis` in `params` to gather `indices` from.Must be greater than or equal to `batch_dims`.
/// Defaults to the first non-batch dimension. Supports negative indexes.
/// </param>
/// <param name="batch_dims">An integer. The number of batch dimensions. Must be less than or equal to rank(indices).</param>
/// <returns></returns>
public static Tensor gather(Tensor @params, Tensor indices, string name = null, Tensor axis = null, int batch_dims = 0)
{
if (axis is null)
axis = tf.convert_to_tensor(batch_dims);
if(tensor_util.constant_value(axis) != 0)
{
return gen_array_ops.gather_v2(@params, indices, axis, batch_dims: batch_dims, name: name);
}
return gen_array_ops.gather_v2(@params, indices, axis, name: name);
}
public static Tensor gather(Tensor @params, Tensor indices, int axis, string name = null, int batch_dims = 0)
=> gather(@params, indices, name, ops.convert_to_tensor(axis), batch_dims);
public static Tensor gather(ResourceVariable @params, Tensor indices, string name = null, Tensor axis = null, int batch_dims = 0)
{
if (axis is null)
axis = tf.convert_to_tensor(batch_dims);
if (tensor_util.constant_value(axis) != 0)
{
throw new NotImplementedException();
}
return @params.sparse_read(indices, name);
}
public static Tensor transpose<T1>(T1 a, Axis perm, string name = "transpose", bool conjugate = false)
{
return tf_with(ops.name_scope(name, "transpose", new { a }), scope =>
{
var a_tensor = ops.convert_to_tensor(a);
if (perm == null)
{
var rank = a_tensor.rank;