-
Notifications
You must be signed in to change notification settings - Fork 19.7k
Expand file tree
/
Copy pathnumpy.py
More file actions
9086 lines (7235 loc) · 280 KB
/
numpy.py
File metadata and controls
9086 lines (7235 loc) · 280 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
import builtins
import re
import numpy as np
from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.backend import KerasTensor
from keras.src.backend import any_symbolic_tensors
from keras.src.backend.common import dtypes
from keras.src.backend.common.backend_utils import canonicalize_axis
from keras.src.backend.common.backend_utils import to_tuple_or_list
from keras.src.ops import operation_utils
from keras.src.ops.operation import Operation
from keras.src.ops.operation_utils import broadcast_shapes
from keras.src.ops.operation_utils import reduce_shape
class Rot90(Operation):
def __init__(self, k=1, axes=(0, 1), *, name=None):
super().__init__(name=name)
self.k = k
self.axes = axes
def call(self, array):
return backend.numpy.rot90(array, k=self.k, axes=self.axes)
def compute_output_spec(self, array):
array_shape = list(array.shape)
if len(array_shape) < 2:
raise ValueError(
"Input array must have at least 2 dimensions. "
f"Received: array.shape={array_shape}"
)
if len(self.axes) != 2 or self.axes[0] == self.axes[1]:
raise ValueError(
f"Invalid axes: {self.axes}. "
"Axes must be a tuple of two different dimensions."
)
axis1, axis2 = self.axes
array_shape[axis1], array_shape[axis2] = (
array_shape[axis2],
array_shape[axis1],
)
return KerasTensor(shape=array_shape, dtype=array.dtype)
@keras_export(["keras.ops.rot90", "keras.ops.numpy.rot90"])
def rot90(array, k=1, axes=(0, 1)):
"""Rotate an array by 90 degrees in the plane specified by axes.
This function rotates an array counterclockwise
by 90 degrees `k` times in the plane specified by `axes`.
Supports arrays of two or more dimensions.
Args:
array: Input array to rotate.
k: Number of times the array is rotated by 90 degrees.
axes: A tuple of two integers specifying the
plane of rotation (defaults to `(0, 1)`).
Returns:
Rotated array.
Examples:
>>> import numpy as np
>>> from keras import ops
>>> m = np.array([[1, 2], [3, 4]])
>>> rotated = ops.rot90(m)
>>> rotated
array([[2, 4],
[1, 3]])
>>> m = np.arange(8).reshape((2, 2, 2))
>>> rotated = ops.rot90(m, k=1, axes=(1, 2))
>>> rotated
array([[[1, 3],
[0, 2]],
[[5, 7],
[4, 6]]])
"""
if any_symbolic_tensors((array,)):
return Rot90(k=k, axes=axes).symbolic_call(array)
return backend.numpy.rot90(array, k=k, axes=axes)
def shape_equal(shape1, shape2, axis=None, allow_none=True):
"""Check if two shapes are equal.
Args:
shape1: A list or tuple of integers for first shape to be compared.
shape2: A list or tuple of integers for second shape to be compared.
axis: An integer, list, or tuple of integers (optional):
Axes to ignore during comparison. Defaults to `None`.
allow_none (bool, optional): If `True`, allows `None` in a shape
to match any value in the corresponding position of the other shape.
Defaults to `True`.
Returns:
bool: `True` if shapes are considered equal based on the criteria,
`False` otherwise.
Examples:
>>> shape_equal((32, 64, 128), (32, 64, 128))
True
>>> shape_equal((32, 64, 128), (32, 64, 127))
False
>>> shape_equal((32, 64, None), (32, 64, 128), allow_none=True)
True
>>> shape_equal((32, 64, None), (32, 64, 128), allow_none=False)
False
>>> shape_equal((32, 64, 128), (32, 63, 128), axis=1)
True
>>> shape_equal((32, 64, 128), (32, 63, 127), axis=(1, 2))
True
>>> shape_equal((32, 64, 128), (32, 63, 127), axis=[1,2])
True
>>> shape_equal((32, 64), (32, 64, 128))
False
"""
if len(shape1) != len(shape2):
return False
shape1 = list(shape1)
shape2 = list(shape2)
if axis is not None:
if isinstance(axis, int):
axis = [axis]
for ax in axis:
shape1[ax] = -1
shape2[ax] = -1
if allow_none:
for i in range(len(shape1)):
if shape1[i] is None:
shape1[i] = shape2[i]
if shape2[i] is None:
shape2[i] = shape1[i]
return shape1 == shape2
class Absolute(Operation):
def call(self, x):
return backend.numpy.absolute(x)
def compute_output_spec(self, x):
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)
@keras_export(["keras.ops.absolute", "keras.ops.numpy.absolute"])
def absolute(x):
"""Compute the absolute value element-wise.
`keras.ops.abs` is a shorthand for this function.
Args:
x: Input tensor.
Returns:
An array containing the absolute value of each element in `x`.
Example:
>>> x = keras.ops.convert_to_tensor([-1.2, 1.2])
>>> keras.ops.absolute(x)
array([1.2, 1.2], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Absolute().symbolic_call(x)
return backend.numpy.absolute(x)
class Abs(Absolute):
pass
@keras_export(["keras.ops.abs", "keras.ops.numpy.abs"])
def abs(x):
"""Shorthand for `keras.ops.absolute`."""
return absolute(x)
class Add(Operation):
def call(self, x1, x2):
return backend.numpy.add(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
output_dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1_sparse = getattr(x1, "sparse", False)
x2_sparse = getattr(x2, "sparse", False)
output_sparse = x1_sparse and x2_sparse
return KerasTensor(
output_shape, dtype=output_dtype, sparse=output_sparse
)
@keras_export(["keras.ops.add", "keras.ops.numpy.add"])
def add(x1, x2):
"""Add arguments element-wise.
Args:
x1: First input tensor.
x2: Second input tensor.
Returns:
The tensor containing the element-wise sum of `x1` and `x2`.
Examples:
>>> x1 = keras.ops.convert_to_tensor([1, 4])
>>> x2 = keras.ops.convert_to_tensor([5, 6])
>>> keras.ops.add(x1, x2)
array([6, 10], dtype=int32)
`keras.ops.add` also broadcasts shapes:
>>> x1 = keras.ops.convert_to_tensor(
... [[5, 4],
... [5, 6]]
... )
>>> x2 = keras.ops.convert_to_tensor([5, 6])
>>> keras.ops.add(x1, x2)
array([[10 10]
[10 12]], shape=(2, 2), dtype=int32)
"""
if any_symbolic_tensors((x1, x2)):
return Add().symbolic_call(x1, x2)
return backend.numpy.add(x1, x2)
class All(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
self.axis = [axis]
else:
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.all(
x,
axis=self.axis,
keepdims=self.keepdims,
)
def compute_output_spec(self, x):
return KerasTensor(
reduce_shape(
x.shape,
axis=self.axis,
keepdims=self.keepdims,
),
dtype="bool",
)
@keras_export(["keras.ops.all", "keras.ops.numpy.all"])
def all(x, axis=None, keepdims=False):
"""Test whether all array elements along a given axis evaluate to `True`.
Args:
x: Input tensor.
axis: An integer or tuple of integers that represent the axis along
which a logical AND reduction is performed. The default
(`axis=None`) is to perform a logical AND over all the dimensions
of the input array. `axis` may be negative, in which case it counts
for the last to the first axis.
keepdims: If `True`, axes which are reduced are left in the result as
dimensions with size one. With this option, the result will
broadcast correctly against the input array. Defaults to `False`.
Returns:
The tensor containing the logical AND reduction over the `axis`.
Examples:
>>> x = keras.ops.convert_to_tensor([True, False])
>>> keras.ops.all(x)
array(False, shape=(), dtype=bool)
>>> x = keras.ops.convert_to_tensor([[True, False], [True, True]])
>>> keras.ops.all(x, axis=0)
array([ True False], shape=(2,), dtype=bool)
`keepdims=True` outputs a tensor with dimensions reduced to one.
>>> x = keras.ops.convert_to_tensor([[True, False], [True, True]])
>>> keras.ops.all(x, keepdims=True)
array([[False]], shape=(1, 1), dtype=bool)
"""
if any_symbolic_tensors((x,)):
return All(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.all(x, axis=axis, keepdims=keepdims)
class AllClose(Operation):
def __init__(self, rtol=1e-05, atol=1e-08, equal_nan=False, *, name=None):
super().__init__(name=name)
self.rtol = rtol
self.atol = atol
self.equal_nan = equal_nan
def call(self, x1, x2):
return backend.numpy.allclose(
x1,
x2,
rtol=self.rtol,
atol=self.atol,
equal_nan=self.equal_nan,
)
def compute_output_spec(self, x1, x2):
return KerasTensor([], dtype="bool")
@keras_export(["keras.ops.allclose", "keras.ops.numpy.allclose"])
def allclose(x1, x2, rtol=1e-05, atol=1e-08, equal_nan=False):
"""Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol * abs(b)`) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.
Args:
x1: First input tensor.
x2: Second input tensor.
rtol: The relative tolerance parameter (see Notes).
atol: The absolute tolerance parameter (see Notes).
equal_nan: Whether to compare NaN's as equal. If True, NaN's in
`a` will be considered equal to NaN's in `b` in the output array.
Returns:
True if the two arrays are equal within the given tolerance;
False otherwise.
"""
if any_symbolic_tensors((x1, x2)):
return AllClose(
rtol=rtol, atol=atol, equal_nan=equal_nan
).symbolic_call(x1, x2)
return backend.numpy.allclose(
x1, x2, rtol=rtol, atol=atol, equal_nan=equal_nan
)
class Angle(Operation):
def call(self, x):
return backend.numpy.angle(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
return KerasTensor(x.shape, dtype=dtype)
@keras_export(["keras.ops.angle", "keras.ops.numpy.angle"])
def angle(x):
"""Element-wise angle of a complex tensor.
Arguments:
x: Input tensor. Can be real or complex.
Returns:
Output tensor of same shape as x. containing the angle of each element
(in radians).
Example:
>>> x = keras.ops.convert_to_tensor([[1 + 3j, 2 - 5j], [4 - 3j, 3 + 2j]])
>>> keras.ops.angle(x)
array([[ 1.2490457, -1.19029 ],
[-0.6435011, 0.5880026]], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Angle().symbolic_call(x)
return backend.numpy.angle(x)
class Any(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
self.axis = [axis]
else:
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.any(
x,
axis=self.axis,
keepdims=self.keepdims,
)
def compute_output_spec(self, x):
return KerasTensor(
reduce_shape(
x.shape,
axis=self.axis,
keepdims=self.keepdims,
),
dtype="bool",
)
@keras_export(["keras.ops.any", "keras.ops.numpy.any"])
def any(x, axis=None, keepdims=False):
"""Test whether any array element along a given axis evaluates to `True`.
Args:
x: Input tensor.
axis: An integer or tuple of integers that represent the axis along
which a logical OR reduction is performed. The default
(`axis=None`) is to perform a logical OR over all the dimensions
of the input array. `axis` may be negative, in which case it counts
for the last to the first axis.
keepdims: If `True`, axes which are reduced are left in the result as
dimensions with size one. With this option, the result will
broadcast correctly against the input array. Defaults to `False`.
Returns:
The tensor containing the logical OR reduction over the `axis`.
Examples:
>>> x = keras.ops.convert_to_tensor([True, False])
>>> keras.ops.any(x)
array(True, shape=(), dtype=bool)
>>> x = keras.ops.convert_to_tensor([[True, False], [True, True]])
>>> keras.ops.any(x, axis=0)
array([ True True], shape=(2,), dtype=bool)
`keepdims=True` outputs a tensor with dimensions reduced to one.
>>> x = keras.ops.convert_to_tensor([[True, False], [True, True]])
>>> keras.ops.all(x, keepdims=True)
array([[False]], shape=(1, 1), dtype=bool)
"""
if any_symbolic_tensors((x,)):
return Any(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.any(x, axis=axis, keepdims=keepdims)
class Amax(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
axis = [axis]
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.amax(
x,
axis=self.axis,
keepdims=self.keepdims,
)
def compute_output_spec(self, x):
return KerasTensor(
reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
dtype=x.dtype,
)
@keras_export(["keras.ops.amax", "keras.ops.numpy.amax"])
def amax(x, axis=None, keepdims=False):
"""Returns the maximum of an array or maximum value along an axis.
Args:
x: Input tensor.
axis: Axis along which to compute the maximum.
By default (`axis=None`), find the maximum value in all the
dimensions of the input array.
keepdims: If `True`, axes which are reduced are left in the result as
dimensions that are broadcast to the size of the original
input tensor. Defaults to `False`.
Returns:
An array with the maximum value. If `axis=None`, the result is a scalar
value representing the maximum element in the entire array. If `axis` is
given, the result is an array with the maximum values along
the specified axis.
Examples:
>>> x = keras.ops.convert_to_tensor([[1, 3, 5], [2, 3, 6]])
>>> keras.ops.amax(x)
array(6, dtype=int32)
>>> x = keras.ops.convert_to_tensor([[1, 6, 8], [1, 5, 2]])
>>> keras.ops.amax(x, axis=0)
array([1, 6, 8], dtype=int32)
>>> x = keras.ops.convert_to_tensor([[1, 6, 8], [1, 5, 2]])
>>> keras.ops.amax(x, axis=1, keepdims=True)
array([[8], [5]], dtype=int32)
"""
if any_symbolic_tensors((x,)):
return Amax(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.amax(x, axis=axis, keepdims=keepdims)
class Amin(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
axis = [axis]
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.amin(x, axis=self.axis, keepdims=self.keepdims)
def compute_output_spec(self, x):
return KerasTensor(
reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
dtype=x.dtype,
)
@keras_export(["keras.ops.amin", "keras.ops.numpy.amin"])
def amin(x, axis=None, keepdims=False):
"""Returns the minimum of an array or minimum value along an axis.
Args:
x: Input tensor.
axis: Axis along which to compute the minimum.
By default (`axis=None`), find the minimum value in all the
dimensions of the input array.
keepdims: If `True`, axes which are reduced are left in the result as
dimensions that are broadcast to the size of the original
input tensor. Defaults to `False`.
Returns:
An array with the minimum value. If `axis=None`, the result is a scalar
value representing the minimum element in the entire array. If `axis` is
given, the result is an array with the minimum values along
the specified axis.
Examples:
>>> x = keras.ops.convert_to_tensor([1, 3, 5, 2, 3, 6])
>>> keras.ops.amin(x)
array(1, dtype=int32)
>>> x = keras.ops.convert_to_tensor([[1, 6, 8], [7, 5, 3]])
>>> keras.ops.amin(x, axis=0)
array([1,5,3], dtype=int32)
>>> x = keras.ops.convert_to_tensor([[1, 6, 8], [7, 5, 3]])
>>> keras.ops.amin(x, axis=1, keepdims=True)
array([[1],[3]], dtype=int32)
"""
if any_symbolic_tensors((x,)):
return Amin(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.amin(x, axis=axis, keepdims=keepdims)
class Append(Operation):
def __init__(self, axis=None, *, name=None):
super().__init__(name=name)
self.axis = axis
def call(self, x1, x2):
return backend.numpy.append(x1, x2, axis=self.axis)
def compute_output_spec(self, x1, x2):
x1_shape = x1.shape
x2_shape = x2.shape
dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
if self.axis is None:
if None in x1_shape or None in x2_shape:
output_shape = [None]
else:
output_shape = [int(np.prod(x1_shape) + np.prod(x2_shape))]
return KerasTensor(output_shape, dtype=dtype)
if not shape_equal(x1_shape, x2_shape, [self.axis]):
raise ValueError(
"`append` requires inputs to have the same shape except the "
f"`axis={self.axis}`, but received shape {x1_shape} and "
f"{x2_shape}."
)
output_shape = list(x1_shape)
output_shape[self.axis] = x1_shape[self.axis] + x2_shape[self.axis]
return KerasTensor(output_shape, dtype=dtype)
@keras_export(["keras.ops.append", "keras.ops.numpy.append"])
def append(
x1,
x2,
axis=None,
):
"""Append tensor `x2` to the end of tensor `x1`.
Args:
x1: First input tensor.
x2: Second input tensor.
axis: Axis along which tensor `x2` is appended to tensor `x1`.
If `None`, both tensors are flattened before use.
Returns:
A tensor with the values of `x2` appended to `x1`.
Examples:
>>> x1 = keras.ops.convert_to_tensor([1, 2, 3])
>>> x2 = keras.ops.convert_to_tensor([[4, 5, 6], [7, 8, 9]])
>>> keras.ops.append(x1, x2)
array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
When `axis` is specified, `x1` and `x2` must have compatible shapes.
>>> x1 = keras.ops.convert_to_tensor([[1, 2, 3], [4, 5, 6]])
>>> x2 = keras.ops.convert_to_tensor([[7, 8, 9]])
>>> keras.ops.append(x1, x2, axis=0)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=int32)
>>> x3 = keras.ops.convert_to_tensor([7, 8, 9])
>>> keras.ops.append(x1, x3, axis=0)
Traceback (most recent call last):
...
TypeError: Cannot concatenate arrays with different numbers of
dimensions: got (2, 3), (3,).
"""
if any_symbolic_tensors((x1, x2)):
return Append(axis=axis).symbolic_call(x1, x2)
return backend.numpy.append(x1, x2, axis=axis)
class Arange(Operation):
def __init__(self, dtype=None, *, name=None):
super().__init__(name=name)
self.dtype = dtype
def call(self, start, stop=None, step=None):
return backend.numpy.arange(start, stop, step=step, dtype=self.dtype)
def compute_output_spec(self, start, stop=None, step=None):
if stop is None:
start, stop = 0, start
if step is None:
step = 1
output_shape = [int(np.ceil((stop - start) / step))]
dtype = self.dtype
if dtype is None:
dtypes_to_resolve = [getattr(start, "dtype", type(start))]
if stop is not None:
dtypes_to_resolve.append(getattr(stop, "dtype", type(stop)))
if step is not None:
dtypes_to_resolve.append(getattr(step, "dtype", type(step)))
dtype = dtypes.result_type(*dtypes_to_resolve)
return KerasTensor(output_shape, dtype=dtype)
@keras_export(["keras.ops.arange", "keras.ops.numpy.arange"])
def arange(start, stop=None, step=None, dtype=None):
"""Return evenly spaced values within a given interval.
`arange` can be called with a varying number of positional arguments:
* `arange(stop)`: Values are generated within the half-open interval
`[0, stop)` (in other words, the interval including start but excluding
stop).
* `arange(start, stop)`: Values are generated within the half-open interval
`[start, stop)`.
* `arange(start, stop, step)`: Values are generated within the half-open
interval `[start, stop)`, with spacing between values given by step.
Args:
start: Integer or real, representing the start of the interval. The
interval includes this value.
stop: Integer or real, representing the end of the interval. The
interval does not include this value, except in some cases where
`step` is not an integer and floating point round-off affects the
length of `out`. Defaults to `None`.
step: Integer or real, represent the spacing between values. For any
output `out`, this is the distance between two adjacent values,
`out[i+1] - out[i]`. The default step size is 1. If `step` is
specified as a position argument, `start` must also be given.
dtype: The type of the output array. If `dtype` is not given, infer the
data type from the other input arguments.
Returns:
Tensor of evenly spaced values.
For floating point arguments, the length of the result is
`ceil((stop - start)/step)`. Because of floating point overflow, this
rule may result in the last element of out being greater than stop.
Examples:
>>> keras.ops.arange(3)
array([0, 1, 2], dtype=int32)
>>> keras.ops.arange(3.0)
array([0., 1., 2.], dtype=float32)
>>> keras.ops.arange(3, 7)
array([3, 4, 5, 6], dtype=int32)
>>> keras.ops.arange(3, 7, 2)
array([3, 5], dtype=int32)
"""
dtype = None if dtype is None else backend.standardize_dtype(dtype)
if any_symbolic_tensors((start, stop, step)):
return Arange(dtype=dtype).symbolic_call(start, stop, step=step)
return backend.numpy.arange(start, stop, step=step, dtype=dtype)
class Arccos(Operation):
def call(self, x):
return backend.numpy.arccos(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
return KerasTensor(x.shape, dtype=dtype)
@keras_export(["keras.ops.arccos", "keras.ops.numpy.arccos"])
def arccos(x):
"""Trigonometric inverse cosine, element-wise.
The inverse of `cos` so that, if `y = cos(x)`, then `x = arccos(y)`.
Args:
x: Input tensor.
Returns:
Tensor of the angle of the ray intersecting the unit circle at the given
x-coordinate in radians `[0, pi]`.
Example:
>>> x = keras.ops.convert_to_tensor([1, -1])
>>> keras.ops.arccos(x)
array([0.0, 3.1415927], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arccos().symbolic_call(x)
return backend.numpy.arccos(x)
class Arccosh(Operation):
def call(self, x):
return backend.numpy.arccosh(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
return KerasTensor(x.shape, dtype=dtype)
@keras_export(["keras.ops.arccosh", "keras.ops.numpy.arccosh"])
def arccosh(x):
"""Inverse hyperbolic cosine, element-wise.
Arguments:
x: Input tensor.
Returns:
Output tensor of same shape as x.
Example:
>>> x = keras.ops.convert_to_tensor([10, 100])
>>> keras.ops.arccosh(x)
array([2.993223, 5.298292], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arccosh().symbolic_call(x)
return backend.numpy.arccosh(x)
class Arcsin(Operation):
def call(self, x):
return backend.numpy.arcsin(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=dtype, sparse=sparse)
@keras_export(["keras.ops.arcsin", "keras.ops.numpy.arcsin"])
def arcsin(x):
"""Inverse sine, element-wise.
Args:
x: Input tensor.
Returns:
Tensor of the inverse sine of each element in `x`, in radians and in
the closed interval `[-pi/2, pi/2]`.
Example:
>>> x = keras.ops.convert_to_tensor([1, -1, 0])
>>> keras.ops.arcsin(x)
array([ 1.5707964, -1.5707964, 0.], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arcsin().symbolic_call(x)
return backend.numpy.arcsin(x)
class Arcsinh(Operation):
def call(self, x):
return backend.numpy.arcsinh(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=dtype, sparse=sparse)
@keras_export(["keras.ops.arcsinh", "keras.ops.numpy.arcsinh"])
def arcsinh(x):
"""Inverse hyperbolic sine, element-wise.
Arguments:
x: Input tensor.
Returns:
Output tensor of same shape as `x`.
Example:
>>> x = keras.ops.convert_to_tensor([1, -1, 0])
>>> keras.ops.arcsinh(x)
array([0.88137364, -0.88137364, 0.0], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arcsinh().symbolic_call(x)
return backend.numpy.arcsinh(x)
class Arctan(Operation):
def call(self, x):
return backend.numpy.arctan(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=dtype, sparse=sparse)
@keras_export(["keras.ops.arctan", "keras.ops.numpy.arctan"])
def arctan(x):
"""Trigonometric inverse tangent, element-wise.
Args:
x: Input tensor.
Returns:
Tensor of the inverse tangent of each element in `x`, in the interval
`[-pi/2, pi/2]`.
Example:
>>> x = keras.ops.convert_to_tensor([0, 1])
>>> keras.ops.arctan(x)
array([0., 0.7853982], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arctan().symbolic_call(x)
return backend.numpy.arctan(x)
class Arctan2(Operation):
def call(self, x1, x2):
return backend.numpy.arctan2(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
outputs_shape = broadcast_shapes(x1_shape, x2_shape)
x1_dtype = backend.standardize_dtype(
getattr(x1, "dtype", backend.floatx())
)
x2_dtype = backend.standardize_dtype(
getattr(x2, "dtype", backend.floatx())
)
dtype = dtypes.result_type(x1_dtype, x2_dtype, float)
return KerasTensor(outputs_shape, dtype=dtype)
@keras_export(["keras.ops.arctan2", "keras.ops.numpy.arctan2"])
def arctan2(x1, x2):
"""Element-wise arc tangent of `x1/x2` choosing the quadrant correctly.
The quadrant (i.e., branch) is chosen so that `arctan2(x1, x2)` is the
signed angle in radians between the ray ending at the origin and passing
through the point `(1, 0)`, and the ray ending at the origin and passing
through the point `(x2, x1)`. (Note the role reversal: the "y-coordinate"
is the first function parameter, the "x-coordinate" is the second.) By IEEE
convention, this function is defined for `x2 = +/-0` and for either or both
of `x1` and `x2` `= +/-inf`.
Args:
x1: First input tensor.
x2: Second input tensor.
Returns:
Tensor of angles in radians, in the range `[-pi, pi]`.
Examples:
Consider four points in different quadrants:
>>> x = keras.ops.convert_to_tensor([-1, +1, +1, -1])
>>> y = keras.ops.convert_to_tensor([-1, -1, +1, +1])
>>> keras.ops.arctan2(y, x) * 180 / numpy.pi
array([-135., -45., 45., 135.], dtype=float32)
Note the order of the parameters. `arctan2` is defined also when x2=0 and
at several other points, obtaining values in the range `[-pi, pi]`:
>>> keras.ops.arctan2(
... keras.ops.array([1., -1.]),
... keras.ops.array([0., 0.]),
... )
array([ 1.5707964, -1.5707964], dtype=float32)
>>> keras.ops.arctan2(
... keras.ops.array([0., 0., numpy.inf]),
... keras.ops.array([+0., -0., numpy.inf]),
... )
array([0., 3.1415925, 0.7853982], dtype=float32)
"""
if any_symbolic_tensors((x1, x2)):
return Arctan2().symbolic_call(x1, x2)
return backend.numpy.arctan2(x1, x2)
class Arctanh(Operation):
def call(self, x):
return backend.numpy.arctanh(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=dtype, sparse=sparse)
@keras_export(["keras.ops.arctanh", "keras.ops.numpy.arctanh"])
def arctanh(x):
"""Inverse hyperbolic tangent, element-wise.
Arguments:
x: Input tensor.
Returns:
Output tensor of same shape as `x`.
Example:
>>> x = keras.ops.convert_to_tensor([0, -0.5])
>>> keras.ops.arctanh(x)
array([ 0. , -0.54930615], dtype=float32)
"""
if any_symbolic_tensors((x,)):
return Arctanh().symbolic_call(x)
return backend.numpy.arctanh(x)
class Argmax(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.argmax(x, axis=self.axis, keepdims=self.keepdims)
def compute_output_spec(self, x):
if self.keepdims:
return KerasTensor(x.shape, dtype="int32")