2

I'm trying to construct a custom loss function in tensorflow 2:

import tensorflow as tf
from tensorflow import keras

class YOLOv2Loss(keras.losses.Loss):
    def __init__(self,anchor_boxes):
        ...

However, if I then compile and fit a model that uses this loss function

anchor_boxes = ... # load anchor boxes from file
model = ... # build model here
train_batches = # extract training batches from tensorflow DataSet
yolov2_loss = YOLOv2Loss(anchor_boxes)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.5E-4)
model.compile(loss=yolov2_loss,optimizer=optimizer)
model.fit(train_batches)

I get

AttributeError: 'YOLOv2Loss' object has no attribute '_name_scope'

(full traceback included below).

I have tried to re-install tensorflow and keras (as suggested in some other posts) but none of this seems to fix the issue. I'm currently using tensorflow/keras version 2.8.0, i.e. the latest stable release.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-6e793fdad18a> in <module>
     12 optimizer = tf.keras.optimizers.Adam(learning_rate=0.5E-4,beta_1=0.9,beta_2=0.999, epsilon=1.E-8, decay=0.0)
     13 model.compile(loss=yolov2_loss,optimizer=optimizer)
---> 14 model.fit(train_batches)

/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1145           except Exception as e:  # pylint:disable=broad-except
   1146             if hasattr(e, "ag_error_metadata"):
-> 1147               raise e.ag_error_metadata.to_exception(e)
   1148             else:
   1149               raise

AttributeError: in user code:

    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1021, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1010, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1000, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 860, in train_step
        loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 918, in compute_loss
        return self.compiled_loss(
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/compile_utils.py", line 201, in __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "/usr/local/lib/python3.8/dist-packages/keras/losses.py", line 136, in __call__
        with backend.name_scope(self._name_scope), graph_ctx:

    AttributeError: 'YOLOv2Loss' object has no attribute '_name_scope'

2 Answers 2

4

I figured it out, it has nothing to do with my tensorflow installation: looking at the keras source code, the attribute _name_scope is set in the constructor of the base class keras.losses.Loss and I had forgotten to call the parent constructor in my derived class.

Once I add

super().__init__()

to the constructor of my YOLOv2Loss class the problem disappears.

Sign up to request clarification or add additional context in comments.

Comments

0

Adding the following line to the init function worked for me.

super().__init__(name="custom_loss",**kwargs)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.