简体   繁体   English

在损失函数中使用生成器

[英]Use generator in loss function

I need to incorporate additional information into a Keras loss function that depends on the current batch. 我需要将其他信息合并到Keras损失函数中,该函数取决于当前批次。 Since Keras losses only take two arguments, I considered adding this information by making the loss function call next() on a generator object. 由于Keras损失仅采用两个参数,因此我考虑通过在生成器对象上调用损失函数next()来添加此信息。 However, the generator is only called once (probably when adding the loss function in model.compile()). 但是,生成器仅被调用一次(可能是在model.compile()中添加损失函数时)。 Here is a sample code: 这是一个示例代码:

data_batches = yield_data_batches()
meta_batches = yield_meta_batches()
....
model.compile(loss=loss_function, ...)
model.fit_generator(generator=data_batches, ....)

def loss_function(x, y):
      meta_x, meta_y = next(meta_batches)
      x *= meta_x  # component-wise matrix multiplication
      y *= meta_y  # component-wise matrix multiplication
      return mse(x, y)

Is there a way to make the loss function get a new meta_batch each time it is evaluated on a data_batch? 有没有一种方法可以使损失函数每次在data_batch上求值时都获得一个新的meta_batch? Or is there another way to incorporate this meta information into the loss function? 还是有其他方法将此元信息合并到损失函数中?

Clarification: The meta_x and meta_y are binary matrices that should cancel out certain elements from the prediction as they should not count to the loss. 澄清:meta_x和meta_y是二进制矩阵,应从预测中抵消某些元素,因为它们不应计入损失。 For example: 例如:

y_true = (a,b,c,0) y_pred = (d,e,f,g) y_meta = (1,1,1,0)

Now, y_pred*y_meta should cancel out g so that it does not count to the loss. 现在,y_pred * y_meta应该抵消g,以便它不计入损失。

This does not work, since the loss function will be compiled and added to the compute graph. 这是行不通的,因为损失函数将被编译并添加到计算图中。 Your loss function may only depend on y_pred and y_true . 您的损失函数可能仅取决于y_predy_true

You can either incorporate this information in y_true , or weight the resulting loss with sample weights. 您可以将此信息合并到y_true ,也可以使用样本权重来加权所造成的损失。

Your approach would be equivalent to a combination of both: Assuming positive weights a and b (you call them meta_x and meta_y): |ax-by| 您的方法将等同于两者的组合:假设权重为a和b(您称它们为meta_x和meta_y):| ax-by | = a|xb/a*y|, so you just weight y_pred by b/a and add the sample weight a. = a | xb / a * y |,因此只需将y_pred乘以b / a并加上样本权重a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM