I have my custom loss class and a callback to update weight which I got from here, here. The second link is kind of a little bit not quite my scenario because we need to access loss history and accuracy in order to update weight, so I think callback from the first link is the best way to do that.
Here is the code I got
class AdaptiveLossCallback(tf.keras.callbacks.Callback):
def __init__(self):
super(AdaptiveLossCallback, self).__init__()
self.weight1 = tf.Variable(1.0, trainable=False, name='weight1', dtype=tf.float32)
self.weight2 = tf.Variable(0.0, trainable=False, name='weight2', dtype=tf.float32)
def on_epoch_end(self, epoch, logs=None):
if epoch == 49:
self.weight1 = tf.assign(self.weight1 , tf.constant(0.5))
self.weight2 = tf.assign(self.weight2 , tf.constant(0.5))
elif epoch == 74:
self.weight1 = tf.assign(self.weight1 , tf.constant(0.0))
self.weight2 = tf.assign(self.weight2 , tf.constant(1.0))
class CustomLoss(tf.keras.losses.Loss):
def __init__(self,
adaptive_loss=None,
from_logits=False,
reduction=losses_utils.ReductionV2.AUTO,
name=None):
super(CustomLoss, self).__init__(reduction=reduction)
self.from_logits = from_logits
self.adaptive_loss = adaptive_loss
def call(self, y_true, y_pred):
...
weight1 = self.adaptive_loss.weight1
weight2 = self.adaptive_loss.weight2
return weight1 * loss1 + weight2 * loss2
But I can't seem to make it work. When running this I will say
Attempting to use uninitialized value weight1
After I try this
session = tf.keras.backend.get_session()
session.run(tf.global_variables_initializer())
model.fit(...)
It seems to work but the weight value is not updating at all.
What I am doing wrong and how can I fix this? Is there a better way to add a changeable variable to Keras model?
Thanks
PS. I can't use Keras model loss_weights
because I have only one output