/
np_math_ops.py
1438 lines (1065 loc) · 40.5 KB
/
np_math_ops.py
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 2020 The TensorFlow 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.
# ==============================================================================
"""Mathematical operations."""
# pylint: disable=g-direct-tensorflow-import
import numbers
import sys
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import bitwise_ops
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import sort_ops
from tensorflow.python.ops import special_math_ops
from tensorflow.python.ops.numpy_ops import np_array_ops
from tensorflow.python.ops.numpy_ops import np_arrays
from tensorflow.python.ops.numpy_ops import np_dtypes
from tensorflow.python.ops.numpy_ops import np_export
from tensorflow.python.ops.numpy_ops import np_utils
pi = np_export.np_export_constant(__name__, 'pi', np.pi)
e = np_export.np_export_constant(__name__, 'e', np.e)
inf = np_export.np_export_constant(__name__, 'inf', np.inf)
@np_utils.np_doc_only('dot')
def dot(a, b): # pylint: disable=missing-docstring
def f(a, b): # pylint: disable=missing-docstring
return np_utils.cond(
np_utils.logical_or(
math_ops.equal(array_ops.rank(a), 0),
math_ops.equal(array_ops.rank(b), 0)),
lambda: a * b,
lambda: np_utils.cond( # pylint: disable=g-long-lambda
math_ops.equal(array_ops.rank(b), 1),
lambda: math_ops.tensordot(a, b, axes=[[-1], [-1]]),
lambda: math_ops.tensordot(a, b, axes=[[-1], [-2]])))
return _bin_op(f, a, b)
# TODO(wangpeng): Make element-wise ops `ufunc`s
def _bin_op(tf_fun, a, b, promote=True):
if promote:
a, b = np_array_ops._promote_dtype_binary(a, b) # pylint: disable=protected-access
else:
a = np_array_ops.array(a)
b = np_array_ops.array(b)
return tf_fun(a, b)
@np_utils.np_doc('add')
def add(x1, x2):
def add_or_or(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
return math_ops.logical_or(x1, x2)
return math_ops.add(x1, x2)
return _bin_op(add_or_or, x1, x2)
@np_utils.np_doc('subtract')
def subtract(x1, x2):
return _bin_op(math_ops.subtract, x1, x2)
@np_utils.np_doc('multiply')
def multiply(x1, x2):
def mul_or_and(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
return math_ops.logical_and(x1, x2)
return math_ops.multiply(x1, x2)
return _bin_op(mul_or_and, x1, x2)
@np_utils.np_doc('true_divide')
def true_divide(x1, x2): # pylint: disable=missing-function-docstring
def _avoid_float64(x1, x2):
if x1.dtype == x2.dtype and x1.dtype in (dtypes.int32, dtypes.int64):
x1 = math_ops.cast(x1, dtype=dtypes.float32)
x2 = math_ops.cast(x2, dtype=dtypes.float32)
return x1, x2
def f(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
float_ = np_dtypes.default_float_type()
x1 = math_ops.cast(x1, float_)
x2 = math_ops.cast(x2, float_)
if not np_dtypes.is_allow_float64():
# math_ops.truediv in Python3 produces float64 when both inputs are int32
# or int64. We want to avoid that when is_allow_float64() is False.
x1, x2 = _avoid_float64(x1, x2)
return math_ops.truediv(x1, x2)
return _bin_op(f, x1, x2)
@np_utils.np_doc('divide')
def divide(x1, x2): # pylint: disable=missing-function-docstring
return true_divide(x1, x2)
@np_utils.np_doc('floor_divide')
def floor_divide(x1, x2): # pylint: disable=missing-function-docstring
def f(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
x1 = math_ops.cast(x1, dtypes.int8)
x2 = math_ops.cast(x2, dtypes.int8)
return math_ops.floordiv(x1, x2)
return _bin_op(f, x1, x2)
@np_utils.np_doc('mod')
def mod(x1, x2): # pylint: disable=missing-function-docstring
def f(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
x1 = math_ops.cast(x1, dtypes.int8)
x2 = math_ops.cast(x2, dtypes.int8)
return math_ops.mod(x1, x2)
return _bin_op(f, x1, x2)
@np_utils.np_doc('remainder')
def remainder(x1, x2): # pylint: disable=missing-function-docstring
return mod(x1, x2)
@np_utils.np_doc('divmod')
def divmod(x1, x2): # pylint: disable=redefined-builtin
return floor_divide(x1, x2), mod(x1, x2)
@np_utils.np_doc('maximum')
def maximum(x1, x2): # pylint: disable=missing-function-docstring
# Fast path for when maximum is used as relu.
if isinstance(
x2, numbers.Real) and not isinstance(x2, bool) and x2 == 0 and isinstance(
x1, np_arrays.ndarray) and x1.dtype != dtypes.bool:
return nn_ops.relu(np_array_ops.asarray(x1))
def max_or_or(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
return math_ops.logical_or(x1, x2)
return math_ops.maximum(x1, x2)
return _bin_op(max_or_or, x1, x2)
@np_utils.np_doc('minimum')
def minimum(x1, x2):
def min_or_and(x1, x2):
if x1.dtype == dtypes.bool:
assert x2.dtype == dtypes.bool
return math_ops.logical_and(x1, x2)
return math_ops.minimum(x1, x2)
return _bin_op(min_or_and, x1, x2)
@np_utils.np_doc('clip')
def clip(a, a_min, a_max): # pylint: disable=missing-docstring
if a_min is None and a_max is None:
raise ValueError('Not more than one of `a_min` and `a_max` may be `None`.')
if a_min is None:
return minimum(a, a_max)
elif a_max is None:
return maximum(a, a_min)
else:
a, a_min, a_max = np_array_ops._promote_dtype(a, a_min, a_max) # pylint: disable=protected-access
return clip_ops.clip_by_value(*np_utils.tf_broadcast(a, a_min, a_max))
@np_utils.np_doc('matmul')
def matmul(x1, x2): # pylint: disable=missing-docstring
def f(x1, x2):
try:
if x1._rank() == 2 and x2._rank() == 2: # pylint: disable=protected-access
# Fast path for known ranks.
return gen_math_ops.mat_mul(x1, x2)
return np_utils.cond(
math_ops.equal(np_utils.tf_rank(x2), 1),
lambda: math_ops.tensordot(x1, x2, axes=1),
lambda: np_utils.cond( # pylint: disable=g-long-lambda
math_ops.equal(np_utils.tf_rank(x1), 1),
lambda: math_ops.tensordot( # pylint: disable=g-long-lambda
x1, x2, axes=[[0], [-2]]),
lambda: math_ops.matmul(x1, x2)))
except errors.InvalidArgumentError as err:
raise ValueError(str(err)).with_traceback(sys.exc_info()[2])
return _bin_op(f, x1, x2)
# Exported so it can be called from Tensor.__matmul__. NumPy's matmul handles
# batched matmul as well, so simply including promotion in TF's current
# __matmul__ implementation was not sufficient.
setattr(np_arrays.ndarray, '_matmul', matmul)
@np_utils.np_doc('tensordot')
def tensordot(a, b, axes=2):
return _bin_op(lambda a, b: math_ops.tensordot(a, b, axes=axes), a, b)
@np_utils.np_doc_only('inner')
def inner(a, b): # pylint: disable=missing-function-docstring
def f(a, b):
return np_utils.cond(
np_utils.logical_or(
math_ops.equal(array_ops.rank(a), 0),
math_ops.equal(array_ops.rank(b), 0)), lambda: a * b,
lambda: math_ops.tensordot(a, b, axes=[[-1], [-1]]))
return _bin_op(f, a, b)
@np_utils.np_doc('cross')
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): # pylint: disable=missing-docstring
def f(a, b): # pylint: disable=missing-docstring
# We can't assign to captured variable `axisa`, so make a new variable
if axis is None:
axis_a = axisa
axis_b = axisb
axis_c = axisc
else:
axis_a = axis
axis_b = axis
axis_c = axis
if axis_a < 0:
axis_a = np_utils.add(axis_a, array_ops.rank(a))
if axis_b < 0:
axis_b = np_utils.add(axis_b, array_ops.rank(b))
def maybe_move_axis_to_last(a, axis):
def move_axis_to_last(a, axis):
return array_ops.transpose(
a,
array_ops.concat([
math_ops.range(axis),
math_ops.range(axis + 1, array_ops.rank(a)), [axis]
],
axis=0))
return np_utils.cond(axis == np_utils.subtract(array_ops.rank(a), 1),
lambda: a, lambda: move_axis_to_last(a, axis))
a = maybe_move_axis_to_last(a, axis_a)
b = maybe_move_axis_to_last(b, axis_b)
a_dim = np_utils.getitem(array_ops.shape(a), -1)
b_dim = np_utils.getitem(array_ops.shape(b), -1)
def maybe_pad_0(a, size_of_last_dim):
def pad_0(a):
return array_ops.pad(
a,
array_ops.concat([
array_ops.zeros([array_ops.rank(a) - 1, 2], dtypes.int32),
constant_op.constant([[0, 1]], dtypes.int32)
],
axis=0))
return np_utils.cond(
math_ops.equal(size_of_last_dim, 2), lambda: pad_0(a), lambda: a)
a = maybe_pad_0(a, a_dim)
b = maybe_pad_0(b, b_dim)
c = math_ops.cross(*np_utils.tf_broadcast(a, b))
if axis_c < 0:
axis_c = np_utils.add(axis_c, array_ops.rank(c))
def move_last_to_axis(a, axis):
r = array_ops.rank(a)
return array_ops.transpose(
a,
array_ops.concat(
[math_ops.range(axis), [r - 1],
math_ops.range(axis, r - 1)],
axis=0))
c = np_utils.cond(
(a_dim == 2) & (b_dim == 2),
lambda: c[..., 2],
lambda: np_utils.cond( # pylint: disable=g-long-lambda
axis_c == np_utils.subtract(array_ops.rank(c), 1), lambda: c,
lambda: move_last_to_axis(c, axis_c)))
return c
return _bin_op(f, a, b)
@np_utils.np_doc_only('vdot')
def vdot(a, b): # pylint: disable=missing-docstring
a, b = np_array_ops._promote_dtype(a, b) # pylint: disable=protected-access
a = np_array_ops.reshape(a, [-1])
b = np_array_ops.reshape(b, [-1])
if a.dtype == np_dtypes.complex128 or a.dtype == np_dtypes.complex64:
a = conj(a)
return dot(a, b)
@np_utils.np_doc('power')
def power(x1, x2):
return _bin_op(math_ops.pow, x1, x2)
@np_utils.np_doc('float_power')
def float_power(x1, x2):
return power(x1, x2)
@np_utils.np_doc('arctan2')
def arctan2(x1, x2):
return _bin_op(math_ops.atan2, x1, x2)
@np_utils.np_doc('nextafter')
def nextafter(x1, x2):
return _bin_op(math_ops.nextafter, x1, x2)
@np_utils.np_doc('heaviside')
def heaviside(x1, x2): # pylint: disable=missing-function-docstring
def f(x1, x2):
return array_ops.where_v2(
x1 < 0, constant_op.constant(0, dtype=x2.dtype),
array_ops.where_v2(x1 > 0, constant_op.constant(1, dtype=x2.dtype), x2))
y = _bin_op(f, x1, x2)
if not np.issubdtype(y.dtype.as_numpy_dtype, np.inexact):
y = y.astype(np_dtypes.default_float_type())
return y
@np_utils.np_doc('hypot')
def hypot(x1, x2):
return sqrt(square(x1) + square(x2))
@np_utils.np_doc('kron')
def kron(a, b): # pylint: disable=missing-function-docstring
# pylint: disable=protected-access,g-complex-comprehension
a, b = np_array_ops._promote_dtype(a, b)
t_a = np_utils.cond(
a.ndim < b.ndim,
lambda: np_array_ops.reshape( # pylint: disable=g-long-lambda
a, np_array_ops._pad_left_to(b.ndim, a.shape)),
lambda: a)
t_b = np_utils.cond(
b.ndim < a.ndim,
lambda: np_array_ops.reshape( # pylint: disable=g-long-lambda
b, np_array_ops._pad_left_to(a.ndim, b.shape)),
lambda: b)
def _make_shape(shape, prepend):
ones = array_ops.ones_like(shape)
if prepend:
shapes = [ones, shape]
else:
shapes = [shape, ones]
return array_ops.reshape(array_ops.stack(shapes, axis=1), [-1])
a_shape = array_ops.shape(t_a)
b_shape = array_ops.shape(t_b)
a_reshaped = np_array_ops.reshape(t_a, _make_shape(a_shape, False))
b_reshaped = np_array_ops.reshape(t_b, _make_shape(b_shape, True))
out_shape = a_shape * b_shape
return np_array_ops.reshape(a_reshaped * b_reshaped, out_shape)
@np_utils.np_doc('outer')
def outer(a, b):
def f(a, b):
return array_ops.reshape(a, [-1, 1]) * array_ops.reshape(b, [-1])
return _bin_op(f, a, b)
# This can also be implemented via tf.reduce_logsumexp
@np_utils.np_doc('logaddexp')
def logaddexp(x1, x2):
amax = maximum(x1, x2)
delta = x1 - x2
return np_array_ops.where(
isnan(delta),
x1 + x2, # NaNs or infinities of the same sign.
amax + log1p(exp(-abs(delta))))
@np_utils.np_doc('logaddexp2')
def logaddexp2(x1, x2):
amax = maximum(x1, x2)
delta = x1 - x2
return np_array_ops.where(
isnan(delta),
x1 + x2, # NaNs or infinities of the same sign.
amax + log1p(exp2(-abs(delta))) / np.log(2))
@np_utils.np_doc('polyval')
def polyval(p, x): # pylint: disable=missing-function-docstring
def f(p, x):
if p.shape.rank == 0:
p = array_ops.reshape(p, [1])
p = array_ops.unstack(p)
# TODO(wangpeng): Make tf version take a tensor for p instead of a list.
y = math_ops.polyval(p, x)
# If the polynomial is 0-order, numpy requires the result to be broadcast to
# `x`'s shape.
if len(p) == 1:
y = array_ops.broadcast_to(y, x.shape)
return y
return _bin_op(f, p, x)
@np_utils.np_doc('isclose')
def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): # pylint: disable=missing-docstring
def f(a, b): # pylint: disable=missing-docstring
dtype = a.dtype
if np.issubdtype(dtype.as_numpy_dtype, np.inexact):
rtol_ = ops.convert_to_tensor(rtol, dtype.real_dtype)
atol_ = ops.convert_to_tensor(atol, dtype.real_dtype)
result = (math_ops.abs(a - b) <= atol_ + rtol_ * math_ops.abs(b))
if equal_nan:
result = result | (math_ops.is_nan(a) & math_ops.is_nan(b))
return result
else:
return a == b
return _bin_op(f, a, b)
@np_utils.np_doc('allclose')
def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
return np_array_ops.all(
isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
def _tf_gcd(x1, x2): # pylint: disable=missing-function-docstring
def _gcd_cond_fn(_, x2):
return math_ops.reduce_any(x2 != 0)
def _gcd_body_fn(x1, x2):
# math_ops.mod will raise an error when any element of x2 is 0. To avoid
# that, we change those zeros to ones. Their values don't matter because
# they won't be used.
x2_safe = array_ops.where_v2(x2 != 0, x2, constant_op.constant(1, x2.dtype))
x1, x2 = (array_ops.where_v2(x2 != 0, x2, x1),
array_ops.where_v2(x2 != 0, math_ops.mod(x1, x2_safe),
constant_op.constant(0, x2.dtype)))
return (array_ops.where_v2(x1 < x2, x2,
x1), array_ops.where_v2(x1 < x2, x1, x2))
if (not np.issubdtype(x1.dtype.as_numpy_dtype, np.integer) or
not np.issubdtype(x2.dtype.as_numpy_dtype, np.integer)):
raise ValueError('Arguments to gcd must be integers.')
shape = array_ops.broadcast_dynamic_shape(
array_ops.shape(x1), array_ops.shape(x2))
x1 = array_ops.broadcast_to(x1, shape)
x2 = array_ops.broadcast_to(x2, shape)
value, _ = control_flow_ops.while_loop(_gcd_cond_fn, _gcd_body_fn,
(math_ops.abs(x1), math_ops.abs(x2)))
return value
# Note that np.gcd may not be present in some supported versions of numpy.
@np_utils.np_doc('gcd')
def gcd(x1, x2):
return _bin_op(_tf_gcd, x1, x2)
# Note that np.lcm may not be present in some supported versions of numpy.
@np_utils.np_doc('lcm')
def lcm(x1, x2): # pylint: disable=missing-function-docstring
def f(x1, x2):
d = _tf_gcd(x1, x2)
# Same as the `x2_safe` trick above
d_safe = array_ops.where_v2(
math_ops.equal(d, 0), constant_op.constant(1, d.dtype), d)
return array_ops.where_v2(
math_ops.equal(d, 0), constant_op.constant(0, d.dtype),
math_ops.abs(x1 * x2) // d_safe)
return _bin_op(f, x1, x2)
def _bitwise_binary_op(tf_fn, x1, x2): # pylint: disable=missing-function-docstring
def f(x1, x2):
is_bool = (x1.dtype == dtypes.bool)
if is_bool:
assert x2.dtype == dtypes.bool
x1 = math_ops.cast(x1, dtypes.int8)
x2 = math_ops.cast(x2, dtypes.int8)
r = tf_fn(x1, x2)
if is_bool:
r = math_ops.cast(r, dtypes.bool)
return r
return _bin_op(f, x1, x2)
@np_utils.np_doc('bitwise_and')
def bitwise_and(x1, x2):
return _bitwise_binary_op(bitwise_ops.bitwise_and, x1, x2)
@np_utils.np_doc('bitwise_or')
def bitwise_or(x1, x2):
return _bitwise_binary_op(bitwise_ops.bitwise_or, x1, x2)
@np_utils.np_doc('bitwise_xor')
def bitwise_xor(x1, x2):
return _bitwise_binary_op(bitwise_ops.bitwise_xor, x1, x2)
@np_utils.np_doc('bitwise_not', link=np_utils.AliasOf('invert'))
def bitwise_not(x):
def f(x):
if x.dtype == dtypes.bool:
return math_ops.logical_not(x)
return bitwise_ops.invert(x)
return _scalar(f, x)
def _scalar(tf_fn, x, promote_to_float=False):
"""Computes the tf_fn(x) for each element in `x`.
Args:
tf_fn: function that takes a single Tensor argument.
x: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `ops.convert_to_tensor`.
promote_to_float: whether to cast the argument to a float dtype
(`np_dtypes.default_float_type`) if it is not already.
Returns:
An ndarray with the same shape as `x`. The default output dtype is
determined by `np_dtypes.default_float_type`, unless x is an ndarray with a
floating point type, in which case the output type is same as x.dtype.
"""
x = np_array_ops.asarray(x)
if promote_to_float and not np.issubdtype(x.dtype.as_numpy_dtype, np.inexact):
x = x.astype(np_dtypes.default_float_type())
return tf_fn(x)
@np_utils.np_doc('log')
def log(x):
return _scalar(math_ops.log, x, True)
@np_utils.np_doc('exp')
def exp(x):
return _scalar(math_ops.exp, x, True)
@np_utils.np_doc('sqrt')
def sqrt(x):
return _scalar(math_ops.sqrt, x, True)
@np_utils.np_doc('abs', link=np_utils.AliasOf('absolute'))
def abs(x): # pylint: disable=redefined-builtin
return _scalar(math_ops.abs, x)
@np_utils.np_doc('absolute')
def absolute(x):
return abs(x)
@np_utils.np_doc('fabs')
def fabs(x):
return abs(x)
@np_utils.np_doc('ceil')
def ceil(x):
return _scalar(math_ops.ceil, x, True)
@np_utils.np_doc('floor')
def floor(x):
return _scalar(math_ops.floor, x, True)
@np_utils.np_doc('conj')
def conj(x):
return _scalar(math_ops.conj, x)
@np_utils.np_doc('negative')
def negative(x):
return _scalar(math_ops.negative, x)
@np_utils.np_doc('reciprocal')
def reciprocal(x):
return _scalar(math_ops.reciprocal, x)
@np_utils.np_doc('signbit')
def signbit(x):
def f(x):
if x.dtype == dtypes.bool:
return array_ops.fill(array_ops.shape(x), False)
return x < 0
return _scalar(f, x)
@np_utils.np_doc('sin')
def sin(x):
return _scalar(math_ops.sin, x, True)
@np_utils.np_doc('cos')
def cos(x):
return _scalar(math_ops.cos, x, True)
@np_utils.np_doc('tan')
def tan(x):
return _scalar(math_ops.tan, x, True)
@np_utils.np_doc('sinh')
def sinh(x):
return _scalar(math_ops.sinh, x, True)
@np_utils.np_doc('cosh')
def cosh(x):
return _scalar(math_ops.cosh, x, True)
@np_utils.np_doc('tanh')
def tanh(x):
return _scalar(math_ops.tanh, x, True)
@np_utils.np_doc('arcsin')
def arcsin(x):
return _scalar(math_ops.asin, x, True)
@np_utils.np_doc('arccos')
def arccos(x):
return _scalar(math_ops.acos, x, True)
@np_utils.np_doc('arctan')
def arctan(x):
return _scalar(math_ops.atan, x, True)
@np_utils.np_doc('arcsinh')
def arcsinh(x):
return _scalar(math_ops.asinh, x, True)
@np_utils.np_doc('arccosh')
def arccosh(x):
return _scalar(math_ops.acosh, x, True)
@np_utils.np_doc('arctanh')
def arctanh(x):
return _scalar(math_ops.atanh, x, True)
@np_utils.np_doc('deg2rad')
def deg2rad(x):
def f(x):
return x * (np.pi / 180.0)
return _scalar(f, x, True)
@np_utils.np_doc('rad2deg')
def rad2deg(x):
return x * (180.0 / np.pi)
_tf_float_types = [
dtypes.bfloat16, dtypes.float16, dtypes.float32, dtypes.float64
]
@np_utils.np_doc('angle')
def angle(z, deg=False): # pylint: disable=missing-function-docstring
def f(x):
if x.dtype in _tf_float_types:
# Workaround for b/147515503
return array_ops.where_v2(x < 0, np.pi, 0)
else:
return math_ops.angle(x)
y = _scalar(f, z, True)
if deg:
y = rad2deg(y)
return y
@np_utils.np_doc('cbrt')
def cbrt(x):
def f(x):
# __pow__ can't handle negative base, so we use `abs` here.
rt = math_ops.abs(x)**(1.0 / 3)
return array_ops.where_v2(x < 0, -rt, rt)
return _scalar(f, x, True)
@np_utils.np_doc('conjugate', link=np_utils.AliasOf('conj'))
def conjugate(x):
return _scalar(math_ops.conj, x)
@np_utils.np_doc('exp2')
def exp2(x):
def f(x):
return 2**x
return _scalar(f, x, True)
@np_utils.np_doc('expm1')
def expm1(x):
return _scalar(math_ops.expm1, x, True)
@np_utils.np_doc('fix')
def fix(x):
def f(x):
return array_ops.where_v2(x < 0, math_ops.ceil(x), math_ops.floor(x))
return _scalar(f, x, True)
@np_utils.np_doc('iscomplex')
def iscomplex(x):
return np_array_ops.imag(x) != 0
@np_utils.np_doc('isreal')
def isreal(x):
return np_array_ops.imag(x) == 0
@np_utils.np_doc('iscomplexobj')
def iscomplexobj(x):
x = np_array_ops.array(x)
return np.issubdtype(x.dtype.as_numpy_dtype, np.complexfloating)
@np_utils.np_doc('isrealobj')
def isrealobj(x):
return not iscomplexobj(x)
@np_utils.np_doc('isnan')
def isnan(x):
return _scalar(math_ops.is_nan, x, True)
def _make_nan_reduction(np_fun_name, reduction, init_val):
"""Helper to generate nan* functions."""
@np_utils.np_doc(np_fun_name)
def nan_reduction(a, axis=None, dtype=None, keepdims=False):
a = np_array_ops.array(a)
v = np_array_ops.array(init_val, dtype=a.dtype)
return reduction(
np_array_ops.where(isnan(a), v, a),
axis=axis,
dtype=dtype,
keepdims=keepdims)
return nan_reduction
nansum = _make_nan_reduction('nansum', np_array_ops.sum, 0)
nanprod = _make_nan_reduction('nanprod', np_array_ops.prod, 1)
@np_utils.np_doc('nanmean')
def nanmean(a, axis=None, dtype=None, keepdims=None): # pylint: disable=missing-docstring
a = np_array_ops.array(a)
if np.issubdtype(a.dtype.as_numpy_dtype, np.bool_) or np.issubdtype(
a.dtype.as_numpy_dtype, np.integer):
return np_array_ops.mean(a, axis=axis, dtype=dtype, keepdims=keepdims)
nan_mask = logical_not(isnan(a))
if dtype is None:
dtype = a.dtype.as_numpy_dtype
normalizer = np_array_ops.sum(
nan_mask, axis=axis, dtype=dtype, keepdims=keepdims)
return nansum(a, axis=axis, dtype=dtype, keepdims=keepdims) / normalizer
@np_utils.np_doc('isfinite')
def isfinite(x):
return _scalar(math_ops.is_finite, x, True)
@np_utils.np_doc('isinf')
def isinf(x):
return _scalar(math_ops.is_inf, x, True)
@np_utils.np_doc('isneginf')
def isneginf(x):
return x == np_array_ops.full_like(x, -np.inf)
@np_utils.np_doc('isposinf')
def isposinf(x):
return x == np_array_ops.full_like(x, np.inf)
@np_utils.np_doc('log2')
def log2(x):
return log(x) / np.log(2)
@np_utils.np_doc('log10')
def log10(x):
return log(x) / np.log(10)
@np_utils.np_doc('log1p')
def log1p(x):
return _scalar(math_ops.log1p, x, True)
@np_utils.np_doc('positive')
def positive(x):
return _scalar(lambda x: x, x)
@np_utils.np_doc('sinc')
def sinc(x):
def f(x):
pi_x = x * np.pi
return array_ops.where_v2(x == 0, array_ops.ones_like(x),
math_ops.sin(pi_x) / pi_x)
return _scalar(f, x, True)
@np_utils.np_doc('square')
def square(x):
return _scalar(math_ops.square, x)
@np_utils.np_doc('diff')
def diff(a, n=1, axis=-1): # pylint: disable=missing-function-docstring
def f(a):
# TODO(agarwal): transpose and reshape to N, H, 1 and do a 1D convolution
# TODO(agarwal): avoid depending on static rank.
nd = a.shape.rank
if nd is None:
raise ValueError(
'Function `diff` currently requires a known rank for input `a`. '
f'Received: a={a} (unknown rank)')
if (axis + nd if axis < 0 else axis) >= nd:
raise ValueError(
f'Argument `axis` (received axis={axis}) is out of bounds '
f'for input {a} of rank {nd}.')
if n < 0:
raise ValueError('Argument `order` must be a non-negative integer. '
f'Received: axis={n}')
slice1 = [slice(None)] * nd
slice2 = [slice(None)] * nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
op = math_ops.not_equal if a.dtype == dtypes.bool else math_ops.subtract
for _ in range(n):
a = op(a[slice1], a[slice2])
return a
return _scalar(f, a)
def _wrap(f, reverse=False):
"""Wraps binary ops so they can be added as operator overloads on ndarray."""
def _f(a, b):
if reverse:
a, b = b, a
if getattr(b, '__array_priority__',
0) > np_arrays.ndarray.__array_priority__:
return NotImplemented
return f(a, b)
return _f
def _comparison(tf_fun, x1, x2, cast_bool_to_int=False):
"""Helper function for comparision."""
dtype = np_utils.result_type(x1, x2)
# Cast x1 and x2 to the result_type if needed.
x1 = np_array_ops.array(x1, dtype=dtype)
x2 = np_array_ops.array(x2, dtype=dtype)
if cast_bool_to_int and x1.dtype == dtypes.bool:
x1 = math_ops.cast(x1, dtypes.int32)
x2 = math_ops.cast(x2, dtypes.int32)
return tf_fun(x1, x2)
@np_utils.np_doc('equal')
def equal(x1, x2):
return _comparison(math_ops.equal, x1, x2)
@np_utils.np_doc('not_equal')
def not_equal(x1, x2):
return _comparison(math_ops.not_equal, x1, x2)
@np_utils.np_doc('greater')
def greater(x1, x2):
return _comparison(math_ops.greater, x1, x2, True)
@np_utils.np_doc('greater_equal')
def greater_equal(x1, x2):
return _comparison(math_ops.greater_equal, x1, x2, True)
@np_utils.np_doc('less')
def less(x1, x2):
return _comparison(math_ops.less, x1, x2, True)
@np_utils.np_doc('less_equal')