10
10
11
11
from keras_contrib .wrappers import ConcreteDropout
12
12
13
-
14
13
def test_cdropout ():
15
14
# Data
16
15
in_dim = 20
@@ -20,7 +19,7 @@ def test_cdropout():
20
19
21
20
# Model
22
21
inputs = Input (shape = (in_dim ,))
23
- dense = Dense (1 , use_bias = True , input_shape = ( in_dim ,) )
22
+ dense = Dense (1 , use_bias = True )
24
23
# Model, normal
25
24
cd = ConcreteDropout (dense , in_dim , prob_init = (init_prop , init_prop ))
26
25
x = cd (inputs )
@@ -53,6 +52,56 @@ def sigmoid(x):
53
52
loss = np .sum (kernel_regularizer + dropout_regularizer )
54
53
eval_loss = model .evaluate (X )
55
54
assert_approx_equal (eval_loss , loss )
55
+
56
+ def test_cdropout_conv ():
57
+ # Data
58
+ in_dim = 20
59
+ init_prop = .1
60
+ np .random .seed (1 )
61
+ X = np .random .randn (1 , in_dim , in_dim , 1 )
62
+
63
+ # Model
64
+ inputs = Input (shape = (in_dim , in_dim , 1 ,))
65
+ conv2d = Conv2D (1 , (3 ,3 ))
66
+ # Model, normal
67
+ cd = ConcreteDropout (conv2d , in_dim , prob_init = (init_prop , init_prop ))
68
+ x = cd (inputs )
69
+ model = Model (inputs , x )
70
+ model .compile (loss = None , optimizer = 'rmsprop' )
71
+ # Model, reference w/o Dropout
72
+ x_ref = conv2d (inputs )
73
+ model_ref = Model (inputs , x_ref )
74
+ model_ref .compile (loss = None , optimizer = 'rmsprop' )
75
+
76
+ # Check about correct 3rd weight (equal to initial value)
77
+ W = model .get_weights ()
78
+ assert_array_almost_equal (W [2 ], [np .log (init_prop )])
79
+
80
+ # Check if ConcreteDropout in prediction phase is the same as no dropout
81
+ out = model .predict (X )
82
+ out_ref = model_ref .predict (X )
83
+ assert_allclose (out , out_ref , atol = 1e-5 )
84
+
85
+ # Check if ConcreteDropout has the right amount of losses deposited
86
+ assert_equal (len (model .losses ), 1 )
87
+
88
+ # Check if the loss correspons the the desired value
89
+ def sigmoid (x ):
90
+ return 1. / (1. + np .exp (- x ))
91
+ p = np .squeeze (sigmoid (W [2 ]))
92
+ kernel_regularizer = cd .weight_regularizer * np .sum (np .square (W [0 ])) / (1. - p )
93
+ dropout_regularizer = (p * np .log (p ) + (1. - p ) * np .log (1. - p ))
94
+ dropout_regularizer *= cd .dropout_regularizer * 1 # because only channels are dropped
95
+ loss = np .sum (kernel_regularizer + dropout_regularizer )
96
+ eval_loss = model .evaluate (X )
97
+ assert_approx_equal (eval_loss , loss )
98
+
99
+ def test_cdropout_wrong_layertype ():
100
+ """To be replaced with a real function test, if implemented.
101
+ """
102
+ with pytest .raises (ValueError ):
103
+ inputs = Input (shape = (in_dim , in_dim ,))
104
+ cd = ConcreteDropout (Conv1D (1 , 3 ), in_dim , prob_init = (init_prop , init_prop ))(inputs )
56
105
57
106
58
107
if __name__ == '__main__' :
0 commit comments