简体   繁体   English

TF/KERAS:将列表作为单个输出的损失传递

[英]TF/KERAS : passing a list as loss for single output

I have only one output for my model, but I would like to combine two different loss functions, ( Note: number of CLASSES = 24 ).我的模型只有一个输出,但我想结合两个不同的损失函数,(注意:类数 = 24 )。

c = 0.8
lamda = 32

# My personalized loss function
def selective_loss(y_true, y_pred): .
    loss = K.categorical_crossentropy(
        K.repeat_elements(y_pred[:, -1:], CLASSES, axis=1) * y_true[:, :-1],
        y_pred[:, :-1]) + lamda * K.maximum(-K.mean(y_pred[:, -1]) + c, 0) ** 2
    return loss

p = np.ones(CLASSES) / CLASSES#The weights of class.

#And doing de model compile.
model.compile(loss = ['categorical_crossentropy', selective_loss],
              loss_weights = p,
              optimizer= sgd,                            
              metrics = ['accuracy'])

But it complains that I need two outputs because I defined two losses:但它抱怨我需要两个输出,因为我定义了两个损失:

ValueError: When passing a list as loss, it should have one entry per model outputs. The model has 1 outputs, but you passed loss=['categorical_crossentropy', <function selective_loss at 0x7fcfb68daa60>]

Would you have to combine the two losses into one?您是否必须将两种损失合二为一? And if so, how would you do it?如果是这样,你会怎么做?

Or better to have two outputs?还是最好有两个输出? Would this affect the prediction?这会影响预测吗? How would it be?会怎样?

I perform a weighting between the two loss functions, use alpha 0.5 but other float is valid too:我在两个损失函数之间进行加权,使用 alpha 0.5 但其他浮点数也有效:

#Private loss is the selective_loss.
def total_loss(y_true, y_pred):
    alpha = 0.5
    return (1-alpha)*categorical_crossentropy(y_true, y_pred) + alpha*selective_loss(y_true, y_pred)

#Compile the model with weighting loss.
model.compile(loss = total_loss,
              loss_weights = p,
              optimizer= sgd,                            
              metrics = ['accuracy'])

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

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