我正在尝试使用自适应loss_weight
实现多任务CNN,随着时代的增加衰减。我提到了这个Github issue。
# callback for adaptive loss_weight
class LossWeightCallback(Callback):
def __init__(self, alpha):
self.alpha = alpha
def on_epoch_end(self, epoch, logs={}):
self.alpha = self.alpha * 0.9
# initial loss_weight
alpha = K.variable(10)
# model
img_input = Input(shape=(224, 224, 3), name='input')
...
model = Model(inputs=img_input, outputs=[y1, y2])
# compile
model.compile(keras.optimizers.SGD(lr=1e-4, momentum=0.9),
loss={'output1': 'categorical_crossentropy', 'output2': 'mse'},
loss_weights={'output1': 1, 'output2': alpha},
metrics={'output1': 'accuracy', 'output2': 'mse'})
# Fit model
checkpointer = ModelCheckpoint('multitask_model.h5', monitor='val_output1_acc', verbose=1, save_best_only=True)
results = model.fit(x_train, {'output1': y_train1, 'output2': y_train2},
validation_split=0.1, batch_size= 100, epochs=50,
callbacks=[checkpointer, LossWeightCallback(alpha)])
但是此代码在第1个纪元结束后返回错误:
TypeError: ('Not JSON Serializable:', <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>)
这个错误有什么解决方案吗?先感谢您。
这不是一个完美的答案,但是当我从checkpointer
中删除callbacks
时,如下所示,错误消失了,代码运行良好。
model.fit()
当使用results = model.fit(x_train, {'output1': y_train1, 'output2': y_train2},
validation_split=0.1, batch_size= 100, epochs=50,
callbacks=[LossWeightCallback(alpha)])
和自定义回调时,似乎on_epoch_end()
函数冲突...