Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions official/resnet/keras/keras_imagenet_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def run_imagenet_with_keras(flags_obj):
# in the graph.
#tf.keras.backend.set_learning_phase(True)

model.compile(loss=softmax_crossentropy_with_logits,
model.compile(loss=cross_entropy_plus_l2_loss,
optimizer=opt,
metrics=['accuracy'],
distribute=strategy)
Expand Down Expand Up @@ -239,7 +239,7 @@ def run_imagenet_with_keras(flags_obj):
steps_per_epoch, samples_per_second))


def softmax_crossentropy_with_logits(y_true, y_pred):
def _softmax_crossentropy_with_logits(y_true, y_pred):
"""A loss function replicating tf's sparse_softmax_cross_entropy

Args:
Expand All @@ -250,6 +250,18 @@ def softmax_crossentropy_with_logits(y_true, y_pred):
logits=y_pred,
labels=tf.reshape(tf.cast(y_true, tf.int64), [-1,]))

def cross_entropy_plus_l2_loss(y_true, y_pred):
weight_decay = 1e-4
entropy_loss = _softmax_crossentropy_with_logits(y_true, y_pred)
l2_loss = weight_decay * tf.add_n(
# loss is computed using fp32 for numerical stability.
[tf.nn.l2_loss(tf.cast(v, tf.float32)) for v in tf.trainable_variables()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this populated for Keras? I think we may need to add regularization losses to the layers explicitly. What is the difference in loss that you see with this change?

if not v.name.startswith('bn')])

return entropy_loss + l2_loss



def main(_):
with logger.benchmark_context(flags.FLAGS):
run_imagenet_with_keras(flags.FLAGS)
Expand Down