Allow `Layer.add_loss` to receive non-tensor; fixes error triggered when using a...
authorFrancois Chollet <fchollet@google.com>
Wed, 2 May 2018 23:58:35 +0000 (16:58 -0700)
committerTensorFlower Gardener <gardener@tensorflow.org>
Thu, 3 May 2018 00:01:23 +0000 (17:01 -0700)
PiperOrigin-RevId: 195175909

tensorflow/python/keras/_impl/keras/engine/base_layer.py
tensorflow/python/keras/_impl/keras/regularizers_test.py

index a3e78c9..3af4eaa 100644 (file)
@@ -29,6 +29,7 @@ from tensorflow.python.estimator import util as estimator_util
 from tensorflow.python.framework import dtypes
 from tensorflow.python.framework import ops
 from tensorflow.python.framework import tensor_shape
+from tensorflow.python.framework import tensor_util
 from tensorflow.python.keras._impl.keras import backend
 from tensorflow.python.keras._impl.keras import constraints
 from tensorflow.python.keras._impl.keras import initializers
@@ -390,6 +391,8 @@ class Layer(checkpointable.CheckpointableBase):
       raise RuntimeError('Layer.add_loss not supported in Eager mode.')
 
     losses = generic_utils.to_list(losses)
+    losses = [ops.convert_to_tensor(loss, dtype=backend.floatx())
+              if not tensor_util.is_tensor(loss) else loss for loss in losses]
     self._losses += losses
     if inputs is None:
       for loss in losses:
index 9a1612b..c4f0483 100644 (file)
@@ -71,6 +71,11 @@ class KerasRegularizersTest(test.TestCase):
         model.fit(x_train, y_train, batch_size=10,
                   epochs=1, verbose=0)
 
+  def test_zero_regularization(self):
+    inputs = keras.backend.ones(shape=(10, 10))
+    layer = keras.layers.Dense(3, kernel_regularizer=keras.regularizers.l2(0))
+    layer(inputs)
+
 
 if __name__ == '__main__':
   test.main()