forked from tensorflow/tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend_test.py
1756 lines (1490 loc) · 68.7 KB
/
backend_test.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 2016 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.
# ==============================================================================
"""Tests for Keras backend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import scipy.sparse
from tensorflow.core.protobuf import config_pb2
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.util import tf_inspect
def compare_single_input_op_to_numpy(keras_op,
np_op,
input_shape,
dtype='float32',
negative_values=True,
keras_args=None,
keras_kwargs=None,
np_args=None,
np_kwargs=None):
keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
inputs = 2. * np.random.random(input_shape)
if negative_values:
inputs -= 1.
keras_output = keras_op(keras.backend.variable(inputs, dtype=dtype),
*keras_args, **keras_kwargs)
keras_output = keras.backend.eval(keras_output)
np_output = np_op(inputs.astype(dtype), *np_args, **np_kwargs)
try:
np.testing.assert_allclose(keras_output, np_output, atol=1e-4)
except AssertionError:
raise AssertionError('Test for op `' + str(keras_op.__name__) + '` failed; '
'Expected ' + str(np_output) + ' but got ' +
str(keras_output))
def compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
dtype='float32',
keras_args=None,
keras_kwargs=None,
np_args=None,
np_kwargs=None):
keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
input_a = np.random.random(input_shape_a)
input_b = np.random.random(input_shape_b)
keras_output = keras_op(keras.backend.variable(input_a, dtype=dtype),
keras.backend.variable(input_b, dtype=dtype),
*keras_args, **keras_kwargs)
keras_output = keras.backend.eval(keras_output)
np_output = np_op(input_a.astype(dtype), input_b.astype(dtype),
*np_args, **np_kwargs)
try:
np.testing.assert_allclose(keras_output, np_output, atol=1e-4)
except AssertionError:
raise AssertionError('Test for op `' + str(keras_op.__name__) + '` failed; '
'Expected ' + str(np_output) + ' but got ' +
str(keras_output))
@test_util.run_all_in_graph_and_eager_modes
class BackendUtilsTest(test.TestCase):
def test_backend(self):
self.assertEqual(keras.backend.backend(), 'tensorflow')
def test_get_reset_uids(self):
self.assertEqual(keras.backend.get_uid('foo'), 1)
self.assertEqual(keras.backend.get_uid('foo'), 2)
keras.backend.reset_uids()
self.assertEqual(keras.backend.get_uid('foo'), 1)
def test_learning_phase(self):
with self.cached_session() as sess:
with self.assertRaises(ValueError):
keras.backend.set_learning_phase(2)
# Test running with a learning-phase-consuming layer
with keras.backend.learning_phase_scope(0):
x = keras.Input((3,))
y = keras.layers.BatchNormalization()(x)
if not context.executing_eagerly():
self.evaluate(variables.global_variables_initializer())
sess.run(y, feed_dict={x: np.random.random((2, 3))})
def test_learning_phase_name(self):
with ops.name_scope('test_scope'):
# Test that outer name scopes do not affect the learning phase's name.
lp = keras.backend.symbolic_learning_phase()
self.assertEqual(lp.name, 'keras_learning_phase:0')
def test_learning_phase_scope(self):
initial_learning_phase = keras.backend.learning_phase()
with keras.backend.learning_phase_scope(1):
self.assertEqual(keras.backend.learning_phase(), 1)
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
with keras.backend.learning_phase_scope(0):
self.assertEqual(keras.backend.learning_phase(), 0)
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
with self.assertRaises(ValueError):
with keras.backend.learning_phase_scope(None):
pass
self.assertEqual(keras.backend.learning_phase(), initial_learning_phase)
new_learning_phase = 0
keras.backend.set_learning_phase(new_learning_phase)
self.assertEqual(keras.backend.learning_phase(), new_learning_phase)
with keras.backend.learning_phase_scope(1):
self.assertEqual(keras.backend.learning_phase(), 1)
self.assertEqual(keras.backend.learning_phase(), new_learning_phase)
def test_learning_phase_scope_in_graph(self):
initial_learning_phase_outside_graph = keras.backend.learning_phase()
with keras.backend.get_graph().as_default():
initial_learning_phase_in_graph = keras.backend.learning_phase()
self.assertEqual(keras.backend.learning_phase(),
initial_learning_phase_outside_graph)
with keras.backend.learning_phase_scope(1):
self.assertEqual(keras.backend.learning_phase(), 1)
self.assertEqual(keras.backend.learning_phase(),
initial_learning_phase_outside_graph)
with keras.backend.get_graph().as_default():
self.assertEqual(keras.backend.learning_phase(),
initial_learning_phase_in_graph)
self.assertEqual(keras.backend.learning_phase(),
initial_learning_phase_outside_graph)
def test_int_shape(self):
x = keras.backend.ones(shape=(3, 4))
self.assertEqual(keras.backend.int_shape(x), (3, 4))
if not context.executing_eagerly():
x = keras.backend.placeholder(shape=(None, 4))
self.assertEqual(keras.backend.int_shape(x), (None, 4))
def test_in_train_phase(self):
y1 = keras.backend.variable(1)
y2 = keras.backend.variable(2)
if context.executing_eagerly():
with keras.backend.learning_phase_scope(0):
y_val_test = keras.backend.in_train_phase(y1, y2).numpy()
with keras.backend.learning_phase_scope(1):
y_val_train = keras.backend.in_train_phase(y1, y2).numpy()
else:
y = keras.backend.in_train_phase(y1, y2)
f = keras.backend.function([keras.backend.learning_phase()], [y])
y_val_test = f([0])[0]
y_val_train = f([1])[0]
self.assertAllClose(y_val_test, 2)
self.assertAllClose(y_val_train, 1)
def test_is_keras_tensor(self):
x = keras.backend.variable(1)
self.assertEqual(keras.backend.is_keras_tensor(x), False)
x = keras.Input(shape=(1,))
self.assertEqual(keras.backend.is_keras_tensor(x), True)
with self.assertRaises(ValueError):
keras.backend.is_keras_tensor(0)
def test_stop_gradient(self):
x = keras.backend.variable(1)
y = keras.backend.stop_gradient(x)
if not context.executing_eagerly():
self.assertEqual(y.op.name[:12], 'StopGradient')
xs = [keras.backend.variable(1) for _ in range(3)]
ys = keras.backend.stop_gradient(xs)
if not context.executing_eagerly():
for y in ys:
self.assertEqual(y.op.name[:12], 'StopGradient')
@test_util.run_all_in_graph_and_eager_modes
class BackendVariableTest(test.TestCase):
def test_zeros(self):
x = keras.backend.zeros((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones(self):
x = keras.backend.ones((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.ones((3, 4)))
def test_eye(self):
x = keras.backend.eye(4)
val = keras.backend.eval(x)
self.assertAllClose(val, np.eye(4))
def test_zeros_like(self):
x = keras.backend.zeros((3, 4))
y = keras.backend.zeros_like(x)
val = keras.backend.eval(y)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones_like(self):
x = keras.backend.zeros((3, 4))
y = keras.backend.ones_like(x)
val = keras.backend.eval(y)
self.assertAllClose(val, np.ones((3, 4)))
def test_random_uniform_variable(self):
x = keras.backend.random_uniform_variable((30, 20), low=1, high=2, seed=0)
val = keras.backend.eval(x)
self.assertAllClose(val.mean(), 1.5, atol=1e-1)
self.assertAllClose(val.max(), 2., atol=1e-1)
self.assertAllClose(val.min(), 1., atol=1e-1)
def test_random_normal_variable(self):
x = keras.backend.random_normal_variable((30, 20), 1., 0.5, seed=0)
val = keras.backend.eval(x)
self.assertAllClose(val.mean(), 1., atol=1e-1)
self.assertAllClose(val.std(), 0.5, atol=1e-1)
def test_count_params(self):
x = keras.backend.zeros((4, 5))
val = keras.backend.count_params(x)
self.assertAllClose(val, 20)
def test_constant(self):
ref_val = np.random.random((3, 4)).astype('float32')
x = keras.backend.constant(ref_val)
val = keras.backend.eval(x)
self.assertAllClose(val, ref_val)
def test_sparse_variable(self):
val = scipy.sparse.eye(10)
x = keras.backend.variable(val)
self.assertTrue(isinstance(x, sparse_tensor.SparseTensor))
y = keras.backend.to_dense(x)
self.assertFalse(keras.backend.is_sparse(y))
@test_util.run_all_in_graph_and_eager_modes
class BackendLinearAlgebraTest(test.TestCase):
def test_dot(self):
x = keras.backend.ones(shape=(2, 3))
y = keras.backend.ones(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.shape.as_list(), [2, 4])
x = keras.backend.ones(shape=(32, 28, 3))
y = keras.backend.ones(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.shape.as_list(), [32, 28, 4])
def test_batch_dot(self):
x = keras.backend.ones(shape=(32, 20, 1))
y = keras.backend.ones(shape=(32, 30, 20))
xy = keras.backend.batch_dot(x, y, axes=[1, 2])
self.assertEqual(xy.shape.as_list(), [32, 1, 30])
# TODO(fchollet): insufficiently tested.
def test_reduction_ops(self):
ops_to_test = [
(keras.backend.max, np.max),
(keras.backend.min, np.min),
(keras.backend.sum, np.sum),
(keras.backend.prod, np.prod),
(keras.backend.var, np.var),
(keras.backend.std, np.std),
(keras.backend.mean, np.mean),
(keras.backend.argmin, np.argmin),
(keras.backend.argmax, np.argmax),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7, 5),
keras_kwargs={'axis': 1},
np_kwargs={'axis': 1})
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7, 5),
keras_kwargs={'axis': -1},
np_kwargs={'axis': -1})
if 'keepdims' in tf_inspect.getargspec(keras_op).args:
compare_single_input_op_to_numpy(keras_op, np_op,
input_shape=(4, 7, 5),
keras_kwargs={'axis': 1,
'keepdims': True},
np_kwargs={'axis': 1,
'keepdims': True})
def test_elementwise_ops(self):
ops_to_test = [
(keras.backend.square, np.square),
(keras.backend.abs, np.abs),
(keras.backend.round, np.round),
(keras.backend.sign, np.sign),
(keras.backend.sin, np.sin),
(keras.backend.cos, np.cos),
(keras.backend.exp, np.exp),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op, input_shape=(4, 7))
ops_to_test = [
(keras.backend.sqrt, np.sqrt),
(keras.backend.log, np.log),
]
for keras_op, np_op in ops_to_test:
compare_single_input_op_to_numpy(keras_op, np_op,
input_shape=(4, 7),
negative_values=False)
compare_single_input_op_to_numpy(
keras.backend.clip, np.clip,
input_shape=(6, 4),
keras_kwargs={'min_value': 0.1, 'max_value': 2.4},
np_kwargs={'a_min': 0.1, 'a_max': 1.4})
compare_single_input_op_to_numpy(
keras.backend.pow, np.power,
input_shape=(6, 4),
keras_args=[3],
np_args=[3])
def test_two_tensor_ops(self):
ops_to_test = [
(keras.backend.equal, np.equal),
(keras.backend.not_equal, np.not_equal),
(keras.backend.greater, np.greater),
(keras.backend.greater_equal, np.greater_equal),
(keras.backend.less, np.less),
(keras.backend.less_equal, np.less_equal),
(keras.backend.maximum, np.maximum),
(keras.backend.minimum, np.minimum),
]
for keras_op, np_op in ops_to_test:
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_b=(4, 7))
def test_relu(self):
x = ops.convert_to_tensor([[-4, 0], [2, 7]], 'float32')
# standard relu
relu_op = keras.backend.relu(x)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# alpha (leaky relu used)
relu_op = keras.backend.relu(x, alpha=0.5)
if not context.executing_eagerly():
self.assertTrue('LeakyRelu' in relu_op.name)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, 0], [2, 7]])
# max_value < some elements
relu_op = keras.backend.relu(x, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 5]])
# nn.relu6 used
relu_op = keras.backend.relu(x, max_value=6)
if not context.executing_eagerly():
self.assertTrue('Relu6' in relu_op.name) # uses tf.nn.relu6
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 6]])
# max value > 6
relu_op = keras.backend.relu(x, max_value=10)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# max value is float
relu_op = keras.backend.relu(x, max_value=4.3)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 4.3]])
# max value == 0
relu_op = keras.backend.relu(x, max_value=0)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 0]])
# alpha and max_value
relu_op = keras.backend.relu(x, alpha=0.25, max_value=3)
self.assertAllClose(keras.backend.eval(relu_op), [[-1, 0], [2, 3]])
# threshold
relu_op = keras.backend.relu(x, threshold=3)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 7]])
# threshold is float
relu_op = keras.backend.relu(x, threshold=1.5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [2, 7]])
# threshold is negative
relu_op = keras.backend.relu(x, threshold=-5)
self.assertAllClose(keras.backend.eval(relu_op), [[-4, 0], [2, 7]])
# threshold and max_value
relu_op = keras.backend.relu(x, threshold=3, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[0, 0], [0, 5]])
# threshold and alpha
relu_op = keras.backend.relu(x, alpha=0.25, threshold=4)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, -1], [-0.5, 7]])
# threshold, alpha, and max_value
relu_op = keras.backend.relu(x, alpha=0.25, threshold=4, max_value=5)
self.assertAllClose(keras.backend.eval(relu_op), [[-2, -1], [-0.5, 5]])
@test_util.run_all_in_graph_and_eager_modes
class BackendShapeOpsTest(test.TestCase):
def test_reshape(self):
compare_single_input_op_to_numpy(keras.backend.reshape, np.reshape,
input_shape=(4, 7),
keras_args=[(2, 14)],
np_args=[(2, 14)])
def test_concatenate(self):
a = keras.backend.variable(np.ones((1, 2, 3)))
b = keras.backend.variable(np.ones((1, 2, 2)))
y = keras.backend.concatenate([a, b], axis=-1)
self.assertEqual(y.shape.as_list(), [1, 2, 5])
def test_permute_dimensions(self):
compare_single_input_op_to_numpy(keras.backend.permute_dimensions,
np.transpose,
input_shape=(4, 7),
keras_args=[(1, 0)],
np_args=[(1, 0)])
def test_resize_images(self):
height_factor = 2
width_factor = 2
data_format = 'channels_last'
x = keras.backend.variable(np.ones((1, 2, 2, 3)))
y = keras.backend.resize_images(x,
height_factor,
width_factor,
data_format)
self.assertEqual(y.shape.as_list(), [1, 4, 4, 3])
data_format = 'channels_first'
x = keras.backend.variable(np.ones((1, 3, 2, 2)))
y = keras.backend.resize_images(x,
height_factor,
width_factor,
data_format)
self.assertEqual(y.shape.as_list(), [1, 3, 4, 4])
# Invalid use:
with self.assertRaises(ValueError):
keras.backend.resize_images(x,
height_factor,
width_factor,
data_format='unknown')
def test_resize_volumes(self):
height_factor = 2
width_factor = 2
depth_factor = 2
data_format = 'channels_last'
x = keras.backend.variable(np.ones((1, 2, 2, 2, 3)))
y = keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format)
self.assertEqual(y.shape.as_list(), [1, 4, 4, 4, 3])
data_format = 'channels_first'
x = keras.backend.variable(np.ones((1, 3, 2, 2, 2)))
y = keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format)
self.assertEqual(y.shape.as_list(), [1, 3, 4, 4, 4])
# Invalid use:
with self.assertRaises(ValueError):
keras.backend.resize_volumes(x,
depth_factor,
height_factor,
width_factor,
data_format='unknown')
def test_repeat_elements(self):
x = keras.backend.variable(np.ones((1, 3, 2)))
y = keras.backend.repeat_elements(x, 3, axis=1)
self.assertEqual(y.shape.as_list(), [1, 9, 2])
# Use with a dynamic axis:
if not context.executing_eagerly():
x = keras.backend.placeholder(shape=(2, None, 2))
y = keras.backend.repeat_elements(x, 3, axis=1)
self.assertEqual(y.shape.as_list(), [2, None, 2])
def test_repeat(self):
x = keras.backend.variable(np.ones((1, 3)))
y = keras.backend.repeat(x, 2)
self.assertEqual(y.shape.as_list(), [1, 2, 3])
def test_flatten(self):
compare_single_input_op_to_numpy(keras.backend.flatten,
np.reshape,
input_shape=(4, 7, 6),
np_args=[(4 * 7 * 6,)])
def test_batch_flatten(self):
compare_single_input_op_to_numpy(keras.backend.batch_flatten,
np.reshape,
input_shape=(4, 7, 6),
np_args=[(4, 7 * 6)])
def test_temporal_padding(self):
def ref_op(x, padding):
shape = list(x.shape)
shape[1] += padding[0] + padding[1]
y = np.zeros(tuple(shape))
y[:, padding[0]:-padding[1], :] = x
return y
compare_single_input_op_to_numpy(keras.backend.temporal_padding,
ref_op,
input_shape=(4, 7, 6),
keras_args=[(2, 3)],
np_args=[(2, 3)])
def test_spatial_2d_padding(self):
def ref_op(x, padding, data_format='channels_last'):
shape = list(x.shape)
if data_format == 'channels_last':
shape[1] += padding[0][0] + padding[0][1]
shape[2] += padding[1][0] + padding[1][1]
y = np.zeros(tuple(shape))
y[:, padding[0][0]:-padding[0][1], padding[1][0]:-padding[1][1], :] = x
else:
shape[2] += padding[0][0] + padding[0][1]
shape[3] += padding[1][0] + padding[1][1]
y = np.zeros(tuple(shape))
y[:, :, padding[0][0]:-padding[0][1], padding[1][0]:-padding[1][1]] = x
return y
compare_single_input_op_to_numpy(
keras.backend.spatial_2d_padding,
ref_op,
input_shape=(2, 3, 2, 3),
keras_args=[((2, 3), (1, 2))],
keras_kwargs={'data_format': 'channels_last'},
np_args=[((2, 3), (1, 2))],
np_kwargs={'data_format': 'channels_last'})
compare_single_input_op_to_numpy(
keras.backend.spatial_2d_padding,
ref_op,
input_shape=(2, 3, 2, 3),
keras_args=[((2, 3), (1, 2))],
keras_kwargs={'data_format': 'channels_first'},
np_args=[((2, 3), (1, 2))],
np_kwargs={'data_format': 'channels_first'})
def test_spatial_3d_padding(self):
def ref_op(x, padding, data_format='channels_last'):
shape = list(x.shape)
if data_format == 'channels_last':
shape[1] += padding[0][0] + padding[0][1]
shape[2] += padding[1][0] + padding[1][1]
shape[3] += padding[2][0] + padding[2][1]
y = np.zeros(tuple(shape))
y[:,
padding[0][0]:-padding[0][1],
padding[1][0]:-padding[1][1],
padding[2][0]:-padding[2][1],
:] = x
else:
shape[2] += padding[0][0] + padding[0][1]
shape[3] += padding[1][0] + padding[1][1]
shape[4] += padding[2][0] + padding[2][1]
y = np.zeros(tuple(shape))
y[:, :,
padding[0][0]:-padding[0][1],
padding[1][0]:-padding[1][1],
padding[2][0]:-padding[2][1]] = x
return y
compare_single_input_op_to_numpy(
keras.backend.spatial_3d_padding,
ref_op,
input_shape=(2, 3, 2, 3, 2),
keras_args=[((2, 3), (1, 2), (2, 3))],
keras_kwargs={'data_format': 'channels_last'},
np_args=[((2, 3), (1, 2), (2, 3))],
np_kwargs={'data_format': 'channels_last'})
compare_single_input_op_to_numpy(
keras.backend.spatial_3d_padding,
ref_op,
input_shape=(2, 3, 2, 3, 2),
keras_args=[((2, 3), (1, 2), (2, 3))],
keras_kwargs={'data_format': 'channels_first'},
np_args=[((2, 3), (1, 2), (2, 3))],
np_kwargs={'data_format': 'channels_first'})
@test_util.run_all_in_graph_and_eager_modes
class BackendNNOpsTest(test.TestCase, parameterized.TestCase):
def test_bias_add(self):
keras_op = keras.backend.bias_add
np_op = np.add
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 2, 7),
input_shape_b=(7,))
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
x = keras.backend.variable((3, 4))
b = keras.backend.variable((3, 4))
keras.backend.bias_add(x, b)
with self.assertRaises(ValueError):
x = keras.backend.variable((3, 4))
b = keras.backend.variable((4,))
keras.backend.bias_add(x, b, data_format='unknown')
def test_bias_add_channels_first(self):
def keras_op(x, b):
return keras.backend.bias_add(x, b, data_format='channels_first')
def np_op(x, b):
if x.ndim == 3:
b = b.reshape((1, b.shape[0], 1))
if x.ndim == 4:
b = b.reshape((1, b.shape[0], 1, 1))
return x + b
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 7),
input_shape_b=(3,))
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 3, 5, 7),
input_shape_b=(3,))
def test_pool2d(self):
val = np.random.random((10, 3, 10, 10))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_first',
pool_mode='max')
self.assertEqual(y.shape.as_list(), [10, 3, 9, 9])
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_first',
pool_mode='avg')
self.assertEqual(y.shape.as_list(), [10, 3, 9, 9])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 9, 9, 3])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 10, 3])
val = np.random.random((10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5, 3])
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2, 2), strides=(2, 2))
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2, 2))
with self.assertRaises(ValueError):
y = keras.backend.pool2d(x, (2, 2), strides=(2, 2), pool_mode='other')
def test_pool3d(self):
val = np.random.random((10, 3, 10, 10, 10))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_first',
pool_mode='max')
self.assertEqual(y.shape.as_list(), [10, 3, 9, 9, 9])
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_first',
pool_mode='avg')
self.assertEqual(y.shape.as_list(), [10, 3, 9, 9, 9])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 9, 9, 9, 3])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(1, 1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 10, 10, 3])
val = np.random.random((10, 10, 10, 10, 3))
x = keras.backend.variable(val)
y = keras.backend.pool3d(x, (2, 2, 2), strides=(2, 2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5, 5, 3])
def test_conv1d(self):
val = np.random.random((10, 4, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='valid', data_format='channels_first')
self.assertEqual(y.shape.as_list(), [10, 5, 8])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 8, 5])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(1,),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 5])
val = np.random.random((10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv1d(x, k, strides=(2,),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5])
def test_local_conv_channels_dim(self):
filters = 3
batch_size = 2
for input_shape in [(3, 5), (2, 3, 5), (2, 5, 3, 4)]:
channels_in = input_shape[0]
input_spatial_shape = input_shape[1:]
dim = len(input_spatial_shape)
inputs = np.random.normal(0, 1, (batch_size,) + input_shape)
inputs_cf = keras.backend.variable(inputs)
for kernel_size in [1, 2]:
for stride in [1, 2]:
kernel_sizes = (kernel_size,) * dim
strides = (stride,) * dim
output_shape = tuple([(i - kernel_size + stride) // stride
for i in input_spatial_shape])
kernel_shape = (np.prod(output_shape),
np.prod(kernel_sizes) * channels_in,
filters)
kernel = np.random.normal(
0,
1,
output_shape + (channels_in, np.prod(kernel_sizes), filters)
)
kernel_cf = np.reshape(kernel, kernel_shape)
kernel_cf = keras.backend.variable(kernel_cf)
conv_cf = keras.backend.local_conv(inputs_cf,
kernel_cf,
kernel_sizes,
strides,
output_shape,
'channels_first')
inputs_cl = np.transpose(inputs, [0, 2] + list(range(3, dim + 2)) +
[1])
inputs_cl = keras.backend.variable(inputs_cl)
kernel_cl = np.reshape(
np.transpose(kernel, list(range(dim)) + [dim + 1, dim, dim + 2]),
kernel_shape
)
kernel_cl = keras.backend.variable(kernel_cl)
conv_cl = keras.backend.local_conv(inputs_cl,
kernel_cl,
kernel_sizes,
strides,
output_shape,
'channels_last')
conv_cf = keras.backend.eval(conv_cf)
conv_cl = keras.backend.eval(conv_cl)
self.assertAllCloseAccordingToType(
conv_cf,
np.transpose(conv_cl,
[0, dim + 1] + list(range(1, dim + 1))),
atol=1e-5
)
@parameterized.named_parameters(
('local_conv1d', (5, 6), (3,), (1,), (3,)),
('local_conv2d', (4, 5, 6), (3, 3), (1, 1), (2, 3)))
def test_local_conv_1d_and_2d(self,
input_shape,
kernel_sizes,
strides,
output_shape):
filters = 3
batch_size = 2
inputs = np.random.normal(0, 1, (batch_size,) + input_shape)
inputs = keras.backend.variable(inputs)
kernel = np.random.normal(0, 1, (np.prod(output_shape),
np.prod(kernel_sizes) * input_shape[-1],
filters))
kernel = keras.backend.variable(kernel)
local_conv = keras.backend.local_conv(inputs,
kernel,
kernel_sizes,
strides,
output_shape,
'channels_last')
if len(output_shape) == 1:
local_conv_dim = keras.backend.local_conv1d(inputs,
kernel,
kernel_sizes,
strides,
'channels_last')
else:
local_conv_dim = keras.backend.local_conv2d(inputs,
kernel,
kernel_sizes,
strides,
output_shape,
'channels_last')
local_conv = keras.backend.eval(local_conv)
local_conv_dim = keras.backend.eval(local_conv_dim)
self.assertAllCloseAccordingToType(local_conv, local_conv_dim)
def test_conv2d(self):
val = np.random.random((10, 4, 10, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv2d(x, k,
padding='valid', data_format='channels_first')
self.assertEqual(y.shape.as_list(), [10, 5, 8, 8])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 8, 8, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 10, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv2d(x, k, strides=(2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.conv2d(x, k, (2, 2, 2))
def test_separable_conv2d(self):
val = np.random.random((10, 4, 10, 10))
x = keras.backend.variable(val)
depthwise_kernel_val = np.random.random((3, 3, 4, 1))
pointwise_kernel_val = np.random.random((1, 1, 4, 5))
dk = keras.backend.variable(depthwise_kernel_val)
pk = keras.backend.variable(pointwise_kernel_val)
y = keras.backend.separable_conv2d(
x, dk, pk, padding='valid', data_format='channels_first')
self.assertEqual(y.shape.as_list(), [10, 5, 8, 8])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(1, 1), padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 8, 8, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(1, 1), padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 10, 5])
val = np.random.random((10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.separable_conv2d(
x, dk, pk, strides=(2, 2), padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(
x, dk, pk, (2, 2), padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(
x, dk, pk, (2, 2), data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.separable_conv2d(x, dk, pk, (2, 2, 2))
def test_conv3d(self):
val = np.random.random((10, 4, 10, 10, 10))
x = keras.backend.variable(val)
kernel_val = np.random.random((3, 3, 3, 4, 5))
k = keras.backend.variable(kernel_val)
y = keras.backend.conv3d(x, k,
padding='valid', data_format='channels_first')
self.assertEqual(y.shape.as_list(), [10, 5, 8, 8, 8])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(1, 1, 1),
padding='valid', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 8, 8, 8, 5])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(1, 1, 1),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 10, 10, 10, 5])
val = np.random.random((10, 10, 10, 10, 4))
x = keras.backend.variable(val)
y = keras.backend.conv3d(x, k, strides=(2, 2, 2),
padding='same', data_format='channels_last')
self.assertEqual(y.shape.as_list(), [10, 5, 5, 5, 5])
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2, 2),
padding='other', data_format='channels_last')
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2, 2),
data_format='other')
with self.assertRaises(ValueError):
y = keras.backend.conv3d(x, k, (2, 2))