When making a custom metric

Hi, there.

I have an error message when making a new custom metric.

The error message is…
—> AttributeError: Can’t set the attribute “metrics”, likely because it conflicts with an existing read-only @property of the object. Please choose a different name. <<—

The code is as follows.


trn_loss_f_cce = keras.metrics.Mean(name=‘trn_loss_f_cce_name’)
trn_metric_f_acc = keras.metrics.CategoricalAccuracy(name=‘trn_metric_f_acc_name’)

class NewModel(keras.Model):
def init(self, model_f):
super(NewModel, self).init()
self.model_f = model_f
def compile(self, optimizer_f, trn_loss_f):
super(FnrResNet, self).compile()
self.optimizer_f = optimizer_f
self.trn_loss_f = trn_loss_f
def train_step(self, data):
x, y = data
with tf.GradientTape() as gtape:
y_pred_f = self.model_f(x, training=True)
trn_loss_t = self.compute_loss(x, y, y_pred_f)
grads_t = gtape.gradient(trn_loss_t, self.model_f.trainable_weights)
self.optimizer_f.apply_gradients(zip(grads_t, self.model_f.trainable_weights))
self.metrics = self.compute_metrics(x, y, y_pred_f)
return {m.name: m.result() for m in self.metrics}
def compute_loss(self, x, y, y_pred_f):
loss = self.trn_loss_f(y, y_pred_f)
trn_loss_f_cce.update_state(loss)
return loss
def compute_metrics(self, x, y, y_pred_f):
trn_metric_f_acc.update_state(y, y_pred_f)
return {
‘trn_loss_f_cce’: trn_loss_f_cce,
‘trn_metric_f_acc’: trn_metric_f_acc
}

new_model = NewModel(model_f=model_f)

new_model.compile(
optimizer_f=keras.optimizers.Adam(learning_rate=lr_schedule(0)),
trn_loss_f=keras.losses.CategoricalCrossentropy(),
)


I tried the Tensorflow guide in “tf.keras.Model  |  TensorFlow v2.10.0
There is a direction that " # Note that self.custom_metric is not listed in self.metrics"
So, I did not define self.metrcis.

How can I solve this?

Thanks~

^^;;

[Before]
self.metrics = self.compute_metrics(x, y, y_pred_f)
return {m.name: m.result() for m in self.metrics}

[After]
return self.compute_metrics(x, y, y_pred_f)

Thanks~

Hi @owen.shin,

I was not able to replicated the error from the code above provided. Can you go through this link for detail understanding of how to declare custom metrics in different ways in tensorflow and let me know if this will solve your problem.

Thanks & Regards.

@Siva_Sravana_Kumar_N
I solved the problem by myself.
But the link you provided will be helpful.
Thank you.

1 Like