我正在尝试在tensorflow 2中构建一个自定义损失函数:
import tensorflow as tf
from tensorflow import keras
class YOLOv2Loss(keras.losses.Loss):
def __init__(self,anchor_boxes):
...
然而,如果我然后编译并拟合使用这个损失函数的模型
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)
我
AttributeError: 'YOLOv2Loss' object has no attribute '_name_scope'
(完整的回溯包括在下面)。
我已经尝试重新安装tensorflow和keras(如其他一些帖子所建议的),但这些似乎都没有解决问题。我目前使用tensorflow/keras 2.8.0版本,即最新的稳定版本。
---------------------------------------------------------------------------
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'
我弄清楚了,它与我的tensorflow安装无关:查看keras源代码,属性_name_scope
是在基类keras.losses.Loss
的构造函数中设置的,我忘记在派生类中调用父构造函数。
一旦我加上
super().__init__()
到我的YOLOv2Loss
类的构造函数,问题就消失了。
在init中添加以下行Function for me.
super().__init__(name="custom_loss",**kwargs)