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

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

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

  1. class CategoricalCrossentropy(keras.losses.Loss):
  2. def __init__(self, weight, name="example"):
  3. super().__init__(name=name)
  4. self.weight = weight
  5. def call(self, y_true, y_pred):
  6. weight = self.weight*np.exp(-1.0*step) #I'd like to use step number here to reduce weight.
  7. loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy
  8. return loss
nfeuvbwi

nfeuvbwi1#

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

  1. class CategoricalCrossentropy(keras.losses.Loss):
  2. def __init__(self, weight, name="example"):
  3. super().__init__(name=name)
  4. self.weight = weight
  5. def call(self, step, y_true, y_pred):
  6. weight = self.weight*np.exp(-1.0*step) #I'd like to use step number here to reduce weight.
  7. loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy
  8. return loss
  9. keras_weight = 1
  10. keras_example = CategoricalCrossentropy(keras_weight)
  11. for step in range(1, max_step+1): # assuming step cannot = 0
  12. loss = keras_example.call(1, y_true, y_perd)

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

  1. class CategoricalCrossentropy1(keras.losses.Loss):
  2. def __init__(self, weight, name="example"):
  3. super().__init__(name=name)
  4. self.weight = weight
  5. self.step = 1 #again, assuming step cannot = 0
  6. def call(self, y_true, y_pred):
  7. weight = self.weight*np.exp(-1.0*self.step) #I'd like to use step number here to reduce weight.
  8. loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred))/y_shape[1]/y_shape[2] #impose weight on CategoricalCrossentropy
  9. self.step += 1 # add to step
  10. return loss

希望这能有所帮助

展开查看全部

相关问题