Add loss tensor(s), potentially dependent on layer inputs. Some losses (for instance, activity regularization losses) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs `a` and `b`, some entries in `layer.losses` may be
(self, losses, inputs=None)
| 1038 | |
| 1039 | @doc_controls.for_subclass_implementers |
| 1040 | def add_loss(self, losses, inputs=None): |
| 1041 | """Add loss tensor(s), potentially dependent on layer inputs. |
| 1042 | |
| 1043 | Some losses (for instance, activity regularization losses) may be dependent |
| 1044 | on the inputs passed when calling a layer. Hence, when reusing the same |
| 1045 | layer on different inputs `a` and `b`, some entries in `layer.losses` may |
| 1046 | be dependent on `a` and some on `b`. This method automatically keeps track |
| 1047 | of dependencies. |
| 1048 | |
| 1049 | This method can be used inside a subclassed layer or model's `call` |
| 1050 | function, in which case `losses` should be a Tensor or list of Tensors. |
| 1051 | |
| 1052 | Example: |
| 1053 | |
| 1054 | ```python |
| 1055 | class MyLayer(tf.keras.layers.Layer): |
| 1056 | def call(inputs, self): |
| 1057 | self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True) |
| 1058 | return inputs |
| 1059 | ``` |
| 1060 | |
| 1061 | This method can also be called directly on a Functional Model during |
| 1062 | construction. In this case, any loss Tensors passed to this Model must |
| 1063 | be symbolic and be able to be traced back to the model's `Input`s. These |
| 1064 | losses become part of the model's topology and are tracked in `get_config`. |
| 1065 | |
| 1066 | Example: |
| 1067 | |
| 1068 | ```python |
| 1069 | inputs = tf.keras.Input(shape=(10,)) |
| 1070 | x = tf.keras.layers.Dense(10)(inputs) |
| 1071 | outputs = tf.keras.layers.Dense(1)(x) |
| 1072 | model = tf.keras.Model(inputs, outputs) |
| 1073 | # Actvity regularization. |
| 1074 | model.add_loss(tf.abs(tf.reduce_mean(x))) |
| 1075 | ``` |
| 1076 | |
| 1077 | If this is not the case for your loss (if, for example, your loss references |
| 1078 | a `Variable` of one of the model's layers), you can wrap your loss in a |
| 1079 | zero-argument lambda. These losses are not tracked as part of the model's |
| 1080 | topology since they can't be serialized. |
| 1081 | |
| 1082 | Example: |
| 1083 | |
| 1084 | ```python |
| 1085 | inputs = tf.keras.Input(shape=(10,)) |
| 1086 | x = tf.keras.layers.Dense(10)(inputs) |
| 1087 | outputs = tf.keras.layers.Dense(1)(x) |
| 1088 | model = tf.keras.Model(inputs, outputs) |
| 1089 | # Weight regularization. |
| 1090 | model.add_loss(lambda: tf.reduce_mean(x.kernel)) |
| 1091 | ``` |
| 1092 | |
| 1093 | The `get_losses_for` method allows to retrieve the losses relevant to a |
| 1094 | specific set of inputs. |
| 1095 | |
| 1096 | Arguments: |
| 1097 | losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses |