2424from neural_structured_learning .keras import adversarial_regularization
2525import numpy as np
2626import tensorflow as tf
27- import tensorflow .keras as keras
2827
2928from tensorflow .python .framework import test_util # pylint: disable=g-direct-tensorflow-import
3029
3130
3231def build_linear_keras_sequential_model (input_shape , weights ):
33- model = keras .Sequential ()
34- model .add (keras .Input (shape = input_shape , name = 'feature' ))
32+ model = tf . keras .Sequential ()
33+ model .add (tf . keras .Input (shape = input_shape , name = 'feature' ))
3534 model .add (
36- keras .layers .Dense (
35+ tf . keras .layers .Dense (
3736 weights .shape [- 1 ],
3837 use_bias = False ,
39- kernel_initializer = keras .initializers .Constant (weights )))
38+ kernel_initializer = tf . keras .initializers .Constant (weights )))
4039 return model
4140
4241
4342def build_linear_keras_functional_model (input_shape ,
4443 weights ,
4544 input_name = 'feature' ):
46- inputs = keras .Input (shape = input_shape , name = input_name )
47- layer = keras .layers .Dense (
45+ inputs = tf . keras .Input (shape = input_shape , name = input_name )
46+ layer = tf . keras .layers .Dense (
4847 weights .shape [- 1 ],
4948 use_bias = False ,
50- kernel_initializer = keras .initializers .Constant (weights ))
49+ kernel_initializer = tf . keras .initializers .Constant (weights ))
5150 outputs = layer (inputs )
52- return keras .Model (inputs = {input_name : inputs }, outputs = outputs )
51+ return tf . keras .Model (inputs = {input_name : inputs }, outputs = outputs )
5352
5453
5554def build_linear_keras_subclassed_model (input_shape , weights , dynamic = False ):
5655 del input_shape
5756
58- class LinearModel (keras .Model ):
57+ class LinearModel (tf . keras .Model ):
5958
6059 def __init__ (self ):
6160 super (LinearModel , self ).__init__ (dynamic = dynamic )
62- self .dense = keras .layers .Dense (
61+ self .dense = tf . keras .layers .Dense (
6362 weights .shape [- 1 ],
6463 use_bias = False ,
6564 name = 'dense' ,
66- kernel_initializer = keras .initializers .Constant (weights ))
65+ kernel_initializer = tf . keras .initializers .Constant (weights ))
6766
6867 def call (self , inputs ):
6968 return self .dense (inputs ['feature' ])
@@ -92,7 +91,7 @@ def _build_linear_regression_model_and_inputs(self, model_fn):
9291 x_adv = x0 + self .adv_step_size * np .sign ((y_hat - y0 ) * w .T )
9392 y_hat_adv = np .dot (x_adv , w )
9493 model = model_fn (input_shape = (2 ,), weights = w )
95- loss_fn = keras .losses .MeanSquaredError ()
94+ loss_fn = tf . keras .losses .MeanSquaredError ()
9695 inputs = {'feature' : tf .constant (x0 )}
9796 labels = tf .constant (y0 )
9897 expected_adv_loss = np .reshape ((y_hat_adv - y0 )** 2 , ())
@@ -102,12 +101,12 @@ def _build_linear_regression_model_and_inputs(self, model_fn):
102101 return inputs , labels , model , loss_fn , expected_adv_loss
103102
104103 def evaluate (self , * args , ** kwargs ):
105- if hasattr (keras .backend , 'get_session' ):
104+ if hasattr (tf . keras .backend , 'get_session' ):
106105 # Sets the Keras Session as default TF Session, so that the variable
107106 # in Keras subclassed model can be initialized correctly. The variable
108107 # is not created until the first call to the model, so the initialization
109108 # is not captured in the global_variables_initializer above.
110- with keras .backend .get_session ().as_default ():
109+ with tf . keras .backend .get_session ().as_default ():
111110 return super (AdversarialLossTest , self ).evaluate (
112111 * args , ** kwargs )
113112 else :
@@ -213,7 +212,7 @@ def test_with_model_kwargs(self):
213212 features = {'feature' : tf .constant (x0 )},
214213 labels = tf .constant (y0 ),
215214 model = model ,
216- loss_fn = keras .losses .MeanSquaredError (),
215+ loss_fn = tf . keras .losses .MeanSquaredError (),
217216 adv_config = self .adv_config ,
218217 model_kwargs = {'training' : True })
219218 # BatchNormalization returns 0 for signle-example batch when training=True.
@@ -235,7 +234,7 @@ def test_predict_by_adv_model_with_labels(self, model_fn):
235234 }
236235
237236 adv_model = adversarial_regularization .AdversarialRegularization (model )
238- adv_model .compile (optimizer = keras .optimizers .SGD (0.01 ), loss = 'MSE' )
237+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (0.01 ), loss = 'MSE' )
239238
240239 prediction = adv_model .predict (x = inputs , steps = 1 , batch_size = 1 )
241240 self .assertAllEqual ([[2.0 ]], prediction )
@@ -250,7 +249,7 @@ def test_predict_by_base_model(self, model_fn):
250249 inputs = {'feature' : tf .constant ([[5.0 , 3.0 ]])}
251250
252251 adv_model = adversarial_regularization .AdversarialRegularization (model )
253- adv_model .compile (optimizer = keras .optimizers .SGD (0.01 ), loss = 'MSE' )
252+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (0.01 ), loss = 'MSE' )
254253
255254 prediction = model .predict (x = inputs , steps = 1 , batch_size = 1 )
256255 self .assertAllEqual ([[2.0 ]], prediction )
@@ -287,10 +286,10 @@ def test_train_fgsm(self, model_fn):
287286 model = model_fn (input_shape = (2 ,), weights = w )
288287 adv_model = adversarial_regularization .AdversarialRegularization (
289288 model , label_keys = ['label' ], adv_config = adv_config )
290- adv_model .compile (optimizer = keras .optimizers .SGD (lr ), loss = 'MSE' )
289+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (lr ), loss = 'MSE' )
291290 adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
292291
293- self .assertAllClose (w_new , keras .backend .get_value (model .weights [0 ]))
292+ self .assertAllClose (w_new , tf . keras .backend .get_value (model .weights [0 ]))
294293
295294 def test_train_fgsm_functional_model_diff_feature_key (self ):
296295 # This test asserts that AdversarialRegularization works regardless of the
@@ -304,10 +303,10 @@ def test_train_fgsm_functional_model_diff_feature_key(self):
304303 input_shape = (2 ,), weights = w , input_name = 'the_feature' )
305304 adv_model = adversarial_regularization .AdversarialRegularization (
306305 model , label_keys = ['label' ], adv_config = adv_config )
307- adv_model .compile (optimizer = keras .optimizers .SGD (lr ), loss = 'MSE' )
306+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (lr ), loss = 'MSE' )
308307 adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
309308
310- self .assertAllClose (w_new , keras .backend .get_value (model .weights [0 ]))
309+ self .assertAllClose (w_new , tf . keras .backend .get_value (model .weights [0 ]))
311310
312311 @parameterized .named_parameters ([
313312 ('sequential' , build_linear_keras_sequential_model ),
@@ -330,10 +329,10 @@ def test_train_fgsm_with_sample_weights(self, model_fn):
330329 label_keys = ['label' ],
331330 sample_weight_key = 'sample_weight' ,
332331 adv_config = adv_config )
333- adv_model .compile (optimizer = keras .optimizers .SGD (lr ), loss = 'MSE' )
332+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (lr ), loss = 'MSE' )
334333 adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
335334
336- self .assertAllClose (w_new , keras .backend .get_value (model .weights [0 ]))
335+ self .assertAllClose (w_new , tf . keras .backend .get_value (model .weights [0 ]))
337336
338337 @parameterized .named_parameters ([
339338 ('sequential' , build_linear_keras_sequential_model ),
@@ -355,11 +354,11 @@ def test_train_with_distribution_strategy(self, model_fn):
355354 adv_model = adversarial_regularization .AdversarialRegularization (
356355 model , label_keys = ['label' ], adv_config = adv_config )
357356 adv_model .compile (
358- optimizer = keras .optimizers .SGD (lr ), loss = 'MSE' , metrics = ['mae' ])
357+ optimizer = tf . keras .optimizers .SGD (lr ), loss = 'MSE' , metrics = ['mae' ])
359358
360359 adv_model .fit (x = inputs )
361360
362- self .assertAllClose (w_new , keras .backend .get_value (model .weights [0 ]))
361+ self .assertAllClose (w_new , tf . keras .backend .get_value (model .weights [0 ]))
363362
364363 def test_train_with_loss_object (self ):
365364 w , x0 , y0 , lr , adv_config , w_new = self ._set_up_linear_regression ()
@@ -369,11 +368,11 @@ def test_train_with_loss_object(self):
369368 adv_model = adversarial_regularization .AdversarialRegularization (
370369 model , label_keys = ['label' ], adv_config = adv_config )
371370 adv_model .compile (
372- optimizer = keras .optimizers .SGD (lr ),
371+ optimizer = tf . keras .optimizers .SGD (lr ),
373372 loss = tf .keras .losses .MeanSquaredError ())
374373 adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
375374
376- self .assertAllClose (w_new , keras .backend .get_value (model .weights [0 ]))
375+ self .assertAllClose (w_new , tf . keras .backend .get_value (model .weights [0 ]))
377376
378377 def test_train_with_metrics (self ):
379378 w , x0 , y0 , lr , adv_config , _ = self ._set_up_linear_regression ()
@@ -383,7 +382,7 @@ def test_train_with_metrics(self):
383382 adv_model = adversarial_regularization .AdversarialRegularization (
384383 model , label_keys = ['label' ], adv_config = adv_config )
385384 adv_model .compile (
386- optimizer = keras .optimizers .SGD (lr ), loss = 'MSE' , metrics = ['mae' ])
385+ optimizer = tf . keras .optimizers .SGD (lr ), loss = 'MSE' , metrics = ['mae' ])
387386 history = adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
388387
389388 actual_labeled_loss = history .history ['mean_squared_error' ][0 ]
@@ -401,7 +400,7 @@ def test_train_with_duplicated_metrics(self):
401400 adv_model = adversarial_regularization .AdversarialRegularization (
402401 model , label_keys = ['label' ], adv_config = adv_config )
403402 adv_model .compile (
404- optimizer = keras .optimizers .SGD (lr ), loss = ['MSE' ], metrics = [['MSE' ]])
403+ optimizer = tf . keras .optimizers .SGD (lr ), loss = ['MSE' ], metrics = [['MSE' ]])
405404 history = adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
406405
407406 self .assertIn ('mean_squared_error' , history .history )
@@ -417,7 +416,7 @@ def test_train_with_metric_object(self):
417416 adv_model = adversarial_regularization .AdversarialRegularization (
418417 model , label_keys = ['label' ], adv_config = adv_config )
419418 adv_model .compile (
420- optimizer = keras .optimizers .SGD (lr ),
419+ optimizer = tf . keras .optimizers .SGD (lr ),
421420 loss = 'MSE' ,
422421 metrics = [tf .keras .metrics .MeanAbsoluteError ()])
423422 history = adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
@@ -434,23 +433,23 @@ def test_train_with_2_outputs(self):
434433 'label2' : tf .constant (- y0 )
435434 }
436435
437- input_layer = keras .Input (shape = (2 ,), name = 'feature' )
438- layer1 = keras .layers .Dense (
436+ input_layer = tf . keras .Input (shape = (2 ,), name = 'feature' )
437+ layer1 = tf . keras .layers .Dense (
439438 w .shape [- 1 ],
440439 use_bias = False ,
441- kernel_initializer = keras .initializers .Constant (w ))
442- layer2 = keras .layers .Dense (
440+ kernel_initializer = tf . keras .initializers .Constant (w ))
441+ layer2 = tf . keras .layers .Dense (
443442 w .shape [- 1 ],
444443 use_bias = False ,
445- kernel_initializer = keras .initializers .Constant (- w ))
446- model = keras .Model (
444+ kernel_initializer = tf . keras .initializers .Constant (- w ))
445+ model = tf . keras .Model (
447446 inputs = {'feature' : input_layer },
448447 outputs = [layer1 (input_layer ), layer2 (input_layer )])
449448
450449 adv_model = adversarial_regularization .AdversarialRegularization (
451450 model , label_keys = ['label1' , 'label2' ], adv_config = adv_config )
452451 adv_model .compile (
453- optimizer = keras .optimizers .SGD (lr ),
452+ optimizer = tf . keras .optimizers .SGD (lr ),
454453 loss = 'MSE' ,
455454 metrics = [tf .keras .metrics .MeanAbsoluteError ()])
456455 history = adv_model .fit (x = inputs , batch_size = 1 , steps_per_epoch = 1 )
@@ -468,11 +467,11 @@ def test_evaluate_binary_classification_metrics(self):
468467 y0 = np .array ([[0.0 , 1.0 , 1.0 ]])
469468 inputs = {'feature' : tf .constant (x0 ), 'label' : tf .constant (y0 )}
470469 model = build_linear_keras_sequential_model (input_shape = (2 ,), weights = w )
471- model .add (keras .layers .Lambda (tf .sigmoid ))
470+ model .add (tf . keras .layers .Lambda (tf .sigmoid ))
472471
473472 adv_model = adversarial_regularization .AdversarialRegularization (model )
474473 adv_model .compile (
475- optimizer = keras .optimizers .SGD (0.1 ),
474+ optimizer = tf . keras .optimizers .SGD (0.1 ),
476475 loss = 'squared_hinge' ,
477476 metrics = ['accuracy' , 'ce' ])
478477 metrics_values = adv_model .evaluate (inputs , steps = 1 )
@@ -494,11 +493,11 @@ def test_evaluate_classification_metrics(self):
494493 y0 = np .array ([[1 ]])
495494 inputs = {'feature' : tf .constant (x0 ), 'label' : tf .constant (y0 )}
496495 model = build_linear_keras_sequential_model (input_shape = (2 ,), weights = w )
497- model .add (keras .layers .Softmax ())
496+ model .add (tf . keras .layers .Softmax ())
498497
499498 adv_model = adversarial_regularization .AdversarialRegularization (model )
500499 adv_model .compile (
501- optimizer = keras .optimizers .SGD (0.1 ),
500+ optimizer = tf . keras .optimizers .SGD (0.1 ),
502501 loss = 'sparse_categorical_crossentropy' ,
503502 metrics = ['accuracy' , 'ce' ])
504503 metrics_values = adv_model .evaluate (inputs , steps = 1 )
@@ -520,7 +519,7 @@ def test_perturb_on_batch(self):
520519 model = build_linear_keras_functional_model (input_shape = (2 ,), weights = w )
521520 adv_model = adversarial_regularization .AdversarialRegularization (
522521 model , label_keys = ['label' ], adv_config = adv_config )
523- adv_model .compile (optimizer = keras .optimizers .SGD (lr ), loss = ['MSE' ])
522+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (lr ), loss = ['MSE' ])
524523 adv_inputs = adv_model .perturb_on_batch (inputs )
525524
526525 y_hat = np .dot (x0 , w )
@@ -535,7 +534,7 @@ def test_perturb_on_batch_custom_config(self):
535534 model = build_linear_keras_functional_model (input_shape = (2 ,), weights = w )
536535 adv_model = adversarial_regularization .AdversarialRegularization (
537536 model , label_keys = ['label' ], adv_config = adv_config )
538- adv_model .compile (optimizer = keras .optimizers .SGD (lr ), loss = ['MSE' ])
537+ adv_model .compile (optimizer = tf . keras .optimizers .SGD (lr ), loss = ['MSE' ])
539538
540539 adv_step_size = 0.2 # A different value from config.adv_step_size
541540 adv_inputs = adv_model .perturb_on_batch (inputs , adv_step_size = adv_step_size )
0 commit comments