通过步长增加在自定义损耗函数中减轻重量

t98cgbkg  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(387)

我想改变随着步幅增加而施加在减肥上的重量。为了实现这一点,我使用了tf.keras.loss.loss的子类。但是,其函数中的参数(如_uinit__;()或call())在计算过程中似乎无法执行步骤。
如何在tf.keras.loss.loss的子类中获取步骤号?
这是我的密码。

class CategoricalCrossentropy(keras.losses.Loss):
    def __init__(self, weight, name="example"):
        super().__init__(name=name)
        self.weight = weight

    def call(self, y_true, y_pred):

        weight = self.weight*np.exp(-1.0*step) #I'd like to use step number here to reduce weight.
        loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy

        return loss
nfeuvbwi

nfeuvbwi1#

编辑(因为您没有告诉函数step的值是什么,这将是函数无法收集的局部变量,因为它有自己的局部变量。)
我认为您正在通过迭代设置步骤。只需将其作为输入添加到调用函数中即可。

class CategoricalCrossentropy(keras.losses.Loss):
    def __init__(self, weight, name="example"):
        super().__init__(name=name)
        self.weight = weight

    def call(self, step, y_true, y_pred):

        weight = self.weight*np.exp(-1.0*step) #I'd like to use step number here to reduce weight.
        loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy

        return loss

keras_weight = 1
keras_example = CategoricalCrossentropy(keras_weight)

for step in range(1, max_step+1):     # assuming step cannot = 0
    loss = keras_example.call(1, y_true, y_perd)

如果你想让这个步骤成为物体记忆中的东西,你可以简单地添加一个阿曲布他。

class CategoricalCrossentropy1(keras.losses.Loss):
    def __init__(self, weight, name="example"):
        super().__init__(name=name)
        self.weight = weight
        self.step = 1           #again, assuming step cannot = 0

    def call(self, y_true, y_pred):
        weight = self.weight*np.exp(-1.0*self.step) #I'd like to use step number here to reduce weight.
        loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy

        self.step += 1  # add to step

        return loss

希望这能有所帮助

相关问题