How to tell a parameter to user-defined class function

Dear all.
I am trying to describe the Huber loss as below by myself.
Instantiating by loss=huber_loss(delta=0.5), and calling it by loss(a,b),
the code seems to work as I intend but I am not sure the way to describe
is correct or not. What I want to know is how to tell the delta to the class
function. Is this correct?

Thank you
Yu

class huber_loss(tf.keras.losses.Loss):
def init(self,delta):
self.delta=delta
super(huber_loss,self).init()
def call(self,y_true,y_pred):
a=tf.where(tf.abs(y_pred-y_true)<self.delta,
0.5*(y_pred-y_true)2,
0.5*self.delta
2+self.delta*(tf.abs(y_pred-y_true)-self.delta))
return tf.math.reduce_mean(a)

Hi @Yuichiro_Morishita,

Here are some small changes in your code:

import tensorflow as tf

class HuberLoss(tf.keras.losses.Loss):
    def __init__(self, delta):
        super(HuberLoss, self).__init__()
        self.delta = delta

    def call(self, y_true, y_pred):
        a = tf.where(tf.abs(y_pred - y_true) < self.delta,
                     0.5 * tf.square(y_pred - y_true),
                     self.delta * tf.abs(y_pred - y_true) - 0.5 * tf.square(self.delta))
        return tf.reduce_mean(a)
  1. In the __init__ method, the super() function is called with the HuberLoss class itself as the first argument, followed by self to initialize the parent class.
  2. The call method is modified to use tf.square() instead of ** for squaring the difference between y_pred and y_true.
  3. The tf.math.reduce_mean() function is replaced with tf.reduce_mean() for computing the mean of a.

Finally , your approach to passing the delta value to the class function is correct. In your code, you are instantiating the HuberLoss class with a delta value and then using that value within the call method.

I hope this helps!

Thanks.

Dear Laxma_Reddy_Patlolla

Some of characters I pasted above were ignored and it looks strange.
In spite of this, thank you for your feed-backs.

Best regards
YU