This repository has been archived by the owner on Jul 1, 2024. It is now read-only.
forked from keras-team/keras
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmxnet_backend.py
6021 lines (4920 loc) · 206 KB
/
mxnet_backend.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
# -*- coding: utf-8 -*-
from __future__ import print_function
import warnings
import mxnet as mx
import numpy as np
from subprocess import CalledProcessError
from numbers import Number
from functools import wraps
from collections import defaultdict
from mxnet import MXNetError
from .common import floatx, epsilon, image_data_format
_UID_PREFIXES = defaultdict(int)
_LEARNING_PHASE = 1
_MODEL = None
_REENTRY = False
NAME_SCOPE_STACK = []
_CURRENT_SCOPE_CTX = None
py_all = all
class name_scope(object):
def __init__(self, name):
self.name = name
def __enter__(self):
global NAME_SCOPE_STACK
NAME_SCOPE_STACK.append(self.name)
def __exit__(self, exc_type, exc_val, exc_tb):
NAME_SCOPE_STACK.pop()
def is_reentry():
return _REENTRY
def set_reentry(value):
global _REENTRY
assert type(value) == bool, 'Please set to a boolean value.'
_REENTRY = value
def set_model(model):
global _MODEL
_MODEL = model
def clear_session():
global _MODEL
reset_uids()
_MODEL = None
def learning_phase():
return _LEARNING_PHASE # 0 = test, 1 = train
def set_learning_phase(value):
global _LEARNING_PHASE
if value not in {0, 1}:
raise ValueError('MXNet Backend: Expected learning phase to be '
'0 or 1.')
_LEARNING_PHASE = value
def keras_mxnet_symbol(func):
"""Decorator function used with all Keras API implementation. This
decorator helps to establish the symbolic graph for the result MXNet symbol
generated in the operator function.
# Arguments
func: Decorated function reference.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
global _REENTRY
reset = False
try:
if _REENTRY:
train_symbol = func(*args, **kwargs)
test_symbol = train_symbol
else:
_REENTRY = True
reset = True
actual_learning_phase = learning_phase()
# Create Train Symbol
set_learning_phase(1)
train_symbol = func(*args, **kwargs)
# Create Test Symbol
set_learning_phase(0)
test_symbol = func(*args, **kwargs)
set_learning_phase(actual_learning_phase)
assert type(train_symbol) == type(test_symbol)
train_symbols = []
test_symbols = []
if isinstance(train_symbol, tuple):
train_symbols = list(train_symbol)
test_symbols = list(test_symbol)
if isinstance(train_symbol, KerasSymbol):
train_symbols = [train_symbol]
test_symbols = [test_symbol]
assert len(train_symbols) == len(test_symbols)
for train_r, test_r in zip(train_symbols, test_symbols):
assert type(train_r) == type(test_r)
if isinstance(train_r, KerasSymbol):
train_r = [train_r]
test_r = [test_r]
for train_i, test_i in zip(train_r, test_r):
if isinstance(train_i, KerasSymbol):
for arg in list(args) + list(kwargs.values()) + list(test_i.get_neighbor()):
if isinstance(arg, (list, tuple)):
for t in arg:
train_i.add_neighbor(t)
else:
train_i.add_neighbor(arg)
if reset:
assert isinstance(train_i._train_sym, mx.sym.Symbol)
assert isinstance(test_i._pred_sym, mx.sym.Symbol)
assert train_i._name == test_i._name
train_i._pred_sym = test_i._pred_sym
assert train_i._train_sym is not None and train_i._pred_sym is not None
else:
assert (train_i == test_i) is True
if reset:
_REENTRY = False
return train_symbol
finally:
if reset:
_REENTRY = False
return func_wrapper
# VARIABLE MANIPULATION
def cast_to_floatx(x):
"""Cast a Numpy array to the default Keras float type.
# Arguments
x: Numpy array.
# Returns
The same Numpy array, cast to its new type.
# Example
```python
>>> from keras import backend as K
>>> K.floatx()
'float32'
>>> arr = numpy.array([1.0, 2.0], dtype='float64')
>>> arr.dtype
dtype('float64')
>>> new_arr = K.cast_to_floatx(arr)
>>> new_arr
array([ 1., 2.], dtype=float32)
>>> new_arr.dtype
dtype('float32')
```
"""
x = np.asarray(x, dtype=floatx())
if x.shape:
return x
else:
return x.tolist()
def is_sparse(tensor):
if hasattr(tensor, 'tocoo'):
return True
elif isinstance(tensor, KerasSymbol):
if tensor.get_stype() == 'csr':
return True
return False
def to_dense(tensor):
"""Converts a sparse tensor into a dense tensor
and returns it.
# Arguments
tensor: A tensor instance (potentially sparse).
# Returns
A dense tensor.
# Examples
```python
>>> from keras import backend as K
>>> b = K.placeholder((2, 2), sparse=True)
>>> print(K.is_sparse(b))
True
>>> c = K.to_dense(b)
>>> print(K.is_sparse(c))
False
```
"""
if hasattr(tensor, 'tocoo'):
return tensor.toarray()
elif isinstance(tensor, mx.sym.Symbol):
return tensor.stype('default')
elif isinstance(tensor, KerasSymbol):
return eval(tensor)
else:
return tensor
def variable(value, dtype=None, name=None, constraint=None, sparse_weight=False):
"""Instantiates a variable and returns it.
# Arguments
value: Numpy array, initial value of the tensor.
dtype: Tensor type.
name: Optional name string for the tensor.
constraint: Optional projection function to be
applied to the variable after an optimizer update.
sparse_weight: Parameter used for MXNet backend to use sparse weight for training.
# Returns
A variable instance (with Keras metadata included).
# Examples
```python
>>> from keras import backend as K
>>> val = np.array([[1, 2], [3, 4]])
>>> kvar = K.variable(value=val, dtype='float64', name='example_var')
>>> K.dtype(kvar)
'float64'
>>> print(kvar)
example_var
>>> kvar.eval()
array([[ 1., 2.],
[ 3., 4.]])
```
"""
if constraint:
warnings.warn('MXNet backend does not support constraints. Keyword '
'arguments such as `kernel_constraint` and '
'`bias_constraint`', stacklevel=2)
if dtype is None:
dtype = floatx()
is_vector = False
if hasattr(value, "shape") and value.shape == (1,):
is_vector = True
if isinstance(value, Number):
value = np.array([value])
if isinstance(value, KerasSymbol):
value = eval(value)
if hasattr(value, 'tocoo'):
v = mx.nd.sparse.csr_matrix((value.data, value.indices, value.indptr), shape=value.shape)
name = _prepare_name(name, 'variable')
ret = _keras_variable(name, v.shape, v.dtype, 'csr', is_vector)
ret._keras_shape = value.shape
ret._uses_learning_phase = False
ret.bind(v)
return ret
elif sparse_weight:
v = mx.nd.array(value).tostype('row_sparse')
name = _prepare_name(name, 'variable')
ret = _keras_variable(name, v.shape, v.dtype, 'row_sparse', is_vector)
ret._keras_shape = value.shape
ret._uses_learning_phase = False
ret.bind(v)
return ret
# MXNet backend do not support scalars
if isinstance(value, np.ndarray) and len(value.shape) == 0:
raise ValueError('MXNet Backend: Scalars are not supported. Provided value for variable '
'- ', value)
dtype = _convert_string_dtype(dtype)
name = _prepare_name(name, 'variable')
ndarray = mx.nd.array(value, dtype=dtype)
ret = _keras_variable(name, ndarray.shape, ndarray.dtype, 'default', is_vector)
ret.bind(ndarray)
if isinstance(value, np.ndarray):
ret._keras_shape = tuple([d if d != 0 else None for d in value.shape])
elif hasattr(value, 'shape'):
ret._keras_shape = tuple([d if d != 0 else None for d in map(int, value.shape)])
ret._uses_learning_phase = False
return ret
@keras_mxnet_symbol
def constant(value, dtype=None, shape=None, name=None):
"""Creates a constant tensor.
# Arguments
value: A constant value (or list)
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
# Returns
A Constant Tensor.
"""
if dtype is None:
dtype = floatx()
if type(value) is np.ndarray:
mx_ndarray = mx.nd.array(value, dtype=dtype)
elif type(value) is list:
mx_ndarray = mx.nd.array(value, dtype=dtype)
elif shape is None:
mx_ndarray = mx.nd.array(value, dtype=dtype)
else:
shape = tuple([0 if dim is None else dim for dim in shape])
np_ndarray = np.ndarray(shape, dtype=dtype)
np_ndarray.fill(value)
mx_ndarray = mx.nd.array(np_ndarray)
# MXNet does not support Scalars. Shape of a Scalar Tensor with MXNet is
# (1, ) instead of (). Return is as MXNet NDArray instance as this is
# useful in K.eval() function to return as is (1, )
if shape == (1,):
return mx_ndarray
else:
name = _prepare_name(name, 'constant')
const_var = _keras_variable(name=name, dtype=dtype, shape=mx_ndarray.shape)
const_var.bind(mx_ndarray)
return const_var
def is_keras_tensor(x):
"""Returns whether `x` is a Keras tensor.
A "Keras tensor" is a tensor that was returned by a Keras layer,
(`Layer` class) or by `Input`.
# Arguments
x: A candidate tensor.
# Returns
A boolean: Whether the argument is a Keras tensor.
# Raises
ValueError: In case `x` is not a symbolic tensor.
# Examples
```python
>>> from keras import backend as K
>>> from keras.layers import Input, Dense
>>> np_var = numpy.array([1, 2])
>>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor.
ValueError
>>> k_var = tf.placeholder('float32', shape=(1,1))
>>> K.is_keras_tensor(k_var) # A variable indirectly created outside of keras is not a Keras tensor.
False
>>> keras_var = K.variable(np_var)
>>> K.is_keras_tensor(keras_var) # A variable created with the keras backend is not a Keras tensor.
False
>>> keras_placeholder = K.placeholder(shape=(2, 4, 5))
>>> K.is_keras_tensor(keras_placeholder) # A placeholder is not a Keras tensor.
False
>>> keras_input = Input([10])
>>> K.is_keras_tensor(keras_input) # An Input is a Keras tensor.
True
>>> keras_layer_output = Dense(10)(keras_input)
>>> K.is_keras_tensor(keras_layer_output) # Any Keras layer output is a Keras tensor.
True
```
"""
if not isinstance(x, KerasSymbol):
raise ValueError('MXNet Backend: Unexpectedly found an instance of type `' +
str(type(x)) + '`.''Expected a symbolic tensor instance.')
return hasattr(x, '_keras_history')
def is_tensor(x):
return isinstance(x, KerasSymbol) or isinstance(x, mx.sym.Symbol) or isinstance(x, mx.nd.NDArray)
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):
"""Instantiates a placeholder tensor and returns it.
# Arguments
shape: Shape of the placeholder
(integer tuple, may include `None` entries).
ndim: Number of axes of the tensor.
At least one of {`shape`, `ndim`} must be specified.
If both are specified, `shape` is used.
dtype: Placeholder type.
sparse: Boolean, whether the placeholder should have a sparse type.
name: Optional name string for the placeholder.
# Returns
Tensor instance (with Keras metadata included).
# Examples
```python
>>> from keras import backend as K
>>> input_ph = K.placeholder(shape=(2, 4, 5))
>>> input_ph._keras_shape
(2, 4, 5)
>>> input_ph
placeholder1:[tensor=False dtype=float32]
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
if shape is None and ndim is None:
raise ValueError('MXNet Backend: Specify either a shape or ndim value.')
name = _prepare_name(name, 'placeholder')
if shape:
shape = tuple([0 if dim is None else dim for dim in shape])
else:
shape = tuple([0 for _ in range(ndim)])
if sparse:
sym = _keras_variable(name, shape=shape, dtype=dtype, stype='csr')
sym._keras_shape = tuple([d if d != 0 else None for d in shape])
sym._mxnet_placeholder = True
sym._uses_learning_phase = False
return sym
sym = _keras_variable(name, shape=shape, dtype=dtype, stype='default')
sym._keras_shape = tuple([d if d != 0 else None for d in shape])
sym._mxnet_placeholder = True
sym._uses_learning_phase = False
return sym
def is_placeholder(x):
"""Returns whether `x` is a placeholder.
# Arguments
x: A candidate placeholder.
# Returns
Boolean.
# Examples
```python
>>> from keras import backend as K
>>> input_ph = K.placeholder(shape=(2,4,5))
>>> K.is_placeholder(input_ph)
True
```
"""
return hasattr(x, '_mxnet_placeholder') and x._mxnet_placeholder
def shape(x):
"""Returns the symbolic shape of a tensor or variable.
# Arguments
x: A tensor or variable.
# Returns
A symbolic shape (which is itself a tensor).
# Examples
```python
>>> from keras import backend as K
>>> val = np.array([[1, 2], [3, 4]])
>>> kvar = K.variable(value=val)
>>> inputs = K.placeholder(shape=(2, 4, 5))
>>> K.shape(kvar)
(2,3)
>>> K.shape(inputs)
(2,4,5)
```
"""
if isinstance(x, KerasSymbol):
return x.shape
else:
return None
def int_shape(x):
"""Returns the shape tensor or variable as a tuple of int or None entries.
# Arguments
x: Tensor or variable.
# Returns
A tuple of integers (or None entries).
# Examples
```python
>>> from keras import backend as K
>>> inputs = K.placeholder(shape=(2, 4, 5))
>>> K.int_shape(inputs)
(2, 4, 5)
>>> val = np.array([[1, 2], [3, 4]])
>>> kvar = K.variable(value=val)
>>> K.int_shape(kvar)
(2, 2)
```
"""
if hasattr(x, '_keras_shape'):
return x._keras_shape
try:
if type(x.shape) is tuple:
return x.shape
else:
return tuple(x.shape.as_list())
except ValueError:
return None
def ndim(x):
"""Returns the number of axes in a tensor, as an integer.
# Arguments
x: Tensor or variable.
# Returns
Integer (scalar), number of axes.
# Examples
```python
>>> from keras import backend as K
>>> inputs = K.placeholder(shape=(2, 4, 5))
>>> val = np.array([[1, 2], [3, 4]])
>>> kvar = K.variable(value=val)
>>> K.ndim(inputs)
3
>>> K.ndim(kvar)
2
```
"""
shape = x.shape
if shape is not None:
return len(shape)
return None
def dtype(x):
"""Returns the dtype of a Keras tensor or variable, as a string.
# Arguments
x: Tensor or variable.
# Returns
String, dtype of `x`.
# Examples
```python
>>> from keras import backend as K
>>> K.dtype(K.placeholder(shape=(2,4,5)))
'float32'
>>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))
'float32'
>>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))
'float64'
# Keras variable
>>> kvar = K.variable(np.array([[1, 2], [3, 4]]))
>>> K.dtype(kvar)
'float32'
>>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
>>> K.dtype(kvar)
'float32'
```
"""
return x.dtype
def eval(x):
"""Evaluates the value of a variable.
# Arguments
x: A variable.
# Returns
A Numpy array.
# Examples
```python
>>> from keras import backend as K
>>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
>>> K.eval(kvar)
array([[ 1., 2.],
[ 3., 4.]], dtype=float32)
```
"""
if isinstance(x, KerasSymbol):
if x.tensor is not None:
if x.name in x.get_bind_values() and _MODEL is not None:
_MODEL._sync_weights()
ret = x.eval().asnumpy()
else:
ret = _forward_pass(x)[0].asnumpy()
# If the Tensor shape is (1, ) and does not have attribute "_is_vector", then, it is considered to be scalar.
# Return the value.
if ret.shape == (1,) and not hasattr(x, '_is_vector'):
ret = ret[0]
return ret
elif isinstance(x, mx.nd.NDArray):
return x.asnumpy()
else:
return x
def zeros(shape, dtype=None, name=None):
"""Instantiates an all-zeros variable and returns it.
# Arguments
shape: Tuple of integers, shape of returned Keras variable
dtype: String, data type of returned Keras variable
name: String, name of returned Keras variable
# Returns
A variable (including Keras metadata), filled with `0.0`.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.zeros((3,4))
>>> K.eval(kvar)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
shape = tuple([0 if dim is None else dim for dim in shape])
value = mx.nd.zeros(shape, dtype=dtype)
name = _prepare_name(name, 'zeroinit')
kvar = _keras_variable(name, value.shape, value.dtype)
kvar.bind(value)
return kvar
def ones(shape, dtype=None, name=None):
"""Instantiates an all-ones tensor variable and returns it.
# Arguments
shape: Tuple of integers, shape of returned Keras variable.
dtype: String, data type of returned Keras variable.
name: String, name of returned Keras variable.
# Returns
A Keras variable, filled with `1.0`.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.ones((3,4))
>>> K.eval(kvar)
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
shape = tuple([0 if dim is None else dim for dim in shape])
value = mx.nd.ones(shape, dtype=dtype)
name = _prepare_name(name, 'oneinit')
kvar = _keras_variable(name=name, shape=shape, dtype=dtype)
kvar.bind(value)
return kvar
def eye(size, dtype=None, name=None):
"""Instantiate an identity matrix and returns it.
# Arguments
size: Integer, number of rows/columns.
dtype: String, data type of returned Keras variable.
name: String, name of returned Keras variable.
# Returns
A Keras variable, an identity matrix.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.eye(3)
>>> K.eval(kvar)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
value = mx.nd.array(np.eye(size, dtype=dtype))
name = _prepare_name(name, 'eyeinit')
kvar = _keras_variable(name=name, shape=size, dtype=dtype)
kvar.bind(value)
return kvar
@keras_mxnet_symbol
def zeros_like(x, dtype=None, name=None):
"""Instantiates an all-zeros variable of the same shape as another tensor.
# Arguments
x: Keras variable or Keras tensor.
dtype: String, dtype of returned Keras variable.
None uses the dtype of x.
name: String, name for the variable to create.
# Returns
A Keras variable with the shape of x filled with zeros.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.variable(np.random.random((2,3)))
>>> kvar_zeros = K.zeros_like(kvar)
>>> K.eval(kvar_zeros)
array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
```
"""
return KerasSymbol(mx.sym.zeros_like(data=x.symbol, name=_prepare_name(name, 'zeroslikeinit')))
def ones_like(x, dtype=None, name=None):
"""Instantiates an all-ones variable of the same shape as another tensor.
# Arguments
x: Keras variable or tensor.
dtype: String, dtype of returned Keras variable.
None uses the dtype of x.
name: String, name for the variable to create.
# Returns
A Keras variable with the shape of x filled with ones.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.variable(np.random.random((2,3)))
>>> kvar_ones = K.ones_like(kvar)
>>> K.eval(kvar_ones)
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
```
"""
return KerasSymbol(mx.sym.ones_like(data=x.symbol, name=_prepare_name(name, 'oneslikeinit')))
def identity(x):
"""Returns a tensor with the same content as the input tensor.
# Arguments
x: The input tensor.
# Returns
A tensor of the same shape, type and content.
# Examples
```python
>>> from keras import backend as K
>>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
>>> kvar_copy = K.identity(kvar)
>>> K.eval(kvar)
array([[ 1., 2.],
[ 3., 4.]], dtype=float32)
>>> K.eval(kvar_copy)
array([[ 1., 2.],
[ 3., 4.]], dtype=float32)
```
"""
name = _prepare_name(None, 'identityinit')
dtype = x.dtype
x_value = eval(x)
mx_shape = tuple([0 if x is None else x for x in x.shape])
mx_value = mx.nd.array(x_value, dtype=dtype)
k_var = _keras_variable(name=name, dtype=dtype, shape=mx_shape)
k_var.bind(mx_value)
return k_var
def random_uniform_variable(shape, low, high, dtype=None,
name=None, seed=None):
"""Instantiates a variable with values drawn from a uniform distribution.
# Arguments
shape: Tuple of integers, shape of returned Keras variable.
low: Float, lower boundary of the output interval.
high: Float, upper boundary of the output interval.
dtype: String, dtype of returned Keras variable.
name: String, name of returned Keras variable.
seed: Integer, random seed.
# Returns
A Keras variable, filled with drawn samples.
# Example
```python
>>> rand_var = K.random_uniform_variable(shape=(3,3), low=1, high=3)
>>> K.eval(rand_var)
array([[ 2.09762716, 2.18568921, 2.43037868],
[ 2.6885314 , 2.20552683, 2.71589136],
[ 2.0897665 , 2.69450331, 1.84730959]], dtype=float32)
>>> rand_var1 = K.random_uniform_variable(shape=(3,3), low=1, high=3, seed=128)
>>> rand_var2 = K.random_uniform_variable(shape=(3,3), low=1, high=3, seed=128)
>>> K.eval(rand_var1)
array([[ 1.07625926, 1.60461187, 1.30567968],
[ 2.43757105, 2.77134657, 2.16382241],
[ 1.7636764 , 2.51851654, 1.96760654]], dtype=float32)
>>> K.eval(rand_var2)
array([[ 1.07625926, 1.60461187, 1.30567968],
[ 2.43757105, 2.77134657, 2.16382241],
[ 1.7636764 , 2.51851654, 1.96760654]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
name = _prepare_name(name, 'randomuniform')
if seed:
mx.random.seed(seed)
value = mx.random.uniform(low=low, high=high, dtype='float32', shape=shape)
if dtype != np.float32:
value = mx.nd.Cast(value, dtype=dtype)
k_var = _keras_variable(name=name, shape=shape, dtype=dtype)
k_var.bind(value)
return k_var
def random_normal_variable(shape, mean, scale, dtype=None,
name=None, seed=None):
"""Instantiates a variable with values drawn from a normal distribution.
# Arguments
shape: Tuple of integers, shape of returned Keras variable.
mean: Float, mean of the normal distribution.
scale: Float, standard deviation of the normal distribution.
dtype: String, dtype of returned Keras variable.
name: String, name of returned Keras variable.
seed: Integer, random seed.
# Returns
A Keras variable, filled with drawn samples.
# Example
```python
>>> rand_var = K.random_normal_variable(shape=(3,3), mean=0, scale=1)
>>> K.eval(rand_var)
array([[ 1.16307867, 2.21220636, 0.48380461],
[ 0.7740038 , 0.29956347, 1.04344034],
[ 0.15302546, 1.18392551, -1.16881478]], dtype=float32)
>>> rand_var1 = K.random_normal_variable(shape=(3,3), mean=0, scale=1, seed=128)
>>> rand_var2 = K.random_normal_variable(shape=(3,3), mean=0, scale=1, seed=128)
>>> K.eval(rand_var1)
array([[-0.75213492, 0.47400656, 0.95352972],
[ 0.20251541, -0.62203991, 1.36481571],
[-0.08511394, -1.4962182 , -0.20014545]], dtype=float32)
>>> K.eval(rand_var2)
array([[-0.75213492, 0.47400656, 0.95352972],
[ 0.20251541, -0.62203991, 1.36481571],
[-0.08511394, -1.4962182 , -0.20014545]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
dtype = _convert_string_dtype(dtype)
name = _prepare_name(name, 'randomnormal')
if seed:
mx.random.seed(seed)
value = mx.random.normal(loc=mean, scale=scale, dtype='float32', shape=shape)
if dtype != np.float32:
value = mx.nd.Cast(value, dtype=dtype)
k_var = _keras_variable(name=name, shape=shape, dtype=dtype)
k_var.bind(value)
return k_var
def count_params(x):
"""Returns the number of scalars in a Keras variable.
# Arguments
x: Keras variable.
# Returns
Integer, the number of scalars in `x`.
# Example
```python
>>> k_var = K.zeros((2,3))
>>> K.count_params(k_var)
6
>>> K.eval(k_var)
array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
```
"""
shape = tuple([0 if x is None else x for x in x.shape])
return np.prod([shape[i] for i in range(len(shape))])
@keras_mxnet_symbol
def cast(x, dtype):
"""Casts a tensor to a different dtype and returns it.
You can cast a Keras variable but it still returns a Keras tensor.
# Arguments
x: Keras tensor (or variable).
dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).
# Returns
Keras tensor with dtype `dtype`.
# Example
```python
>>> from keras import backend as K
>>> input = K.placeholder((2, 3), dtype='float32')
>>> input
placeholder1:[tensor=True dtype=float32]
# It doesn't work in-place as below.
>>> K.cast(input, dtype='float16')
cast0:[tensor=True dtype=float16]
>>> input
placeholder1:[tensor=True dtype=float32]
# you need to assign it.
>>> input = K.cast(input, dtype='float16')
>>> input
cast2:[tensor=True dtype=float16]
```
"""
if isinstance(x, KerasSymbol):
return KerasSymbol(
mx.sym.Cast(data=x.symbol, dtype=dtype))
elif hasattr(x, 'astype'):
return x.astype(dtype)
else:
raise TypeError('MXNet Backend: The input is not valid for cast operation.')
# UPDATES OPS
def update(x, new_x):
"""Update the value of `x` to `new_x`.
# Arguments
x: A `Variable`.
new_x: A tensor of same shape as `x`.
# Returns
The variable `x` updated.
"""
raise NotImplementedError('MXNet Backend: Update operations are not supported yet.')
def update_add(x, increment):
"""Update the value of `x` by adding `increment`.
# Arguments
x: A `Variable`.
increment: A tensor of same shape as `x`.
# Returns
The variable `x` updated.
"""
raise NotImplementedError('MXNet Backend: Update operations are not supported yet.')
def update_sub(x, decrement):
"""Update the value of `x` by subtracting `decrement`.
# Arguments
x: A `Variable`.
decrement: A tensor of same shape as `x`.
# Returns
The variable `x` updated.
"""
raise NotImplementedError('MXNet Backend: Update operations are not supported yet.')
@keras_mxnet_symbol
def moving_average_update(x, value, momentum):
"""Compute the moving average of a variable.
# Arguments
x: A `Variable`.
value: A tensor with the same shape as `x`.
momentum: The moving average momentum.
# Returns
An operation to update the variable.
"""
return KerasSymbol(x.symbol * momentum + value * (1. - momentum))