可以降低label为0时对loss函数的贡献,或是相反的,提升非0对loss的贡献
在直接使用StackOverflow的解决办法时,出现了希望得到float矩阵但是得到int23的报错,添加:true=tf.cast(true, dtype=tf.float32) 即可。修改后如下:
def weightedLoss(w):
def loss(true, pred):
true=tf.cast(true, dtype=tf.float32)
error = K.binary_crossentropy(true,pred,from_logits=True)
error = K.switch(K.equal(true, 0), w * error , error)
return error
return loss
用的时候:
model.compile(loss = weightedLoss(0.1), ...)
我们可以给出推荐的w值:
w = K.mean(y_train) w = w / (1 - w) #this line compesates the lack of the 90% weights for class 1
但是,根据我实际运行的情况,更推荐把用1/w,即:
def weightedLoss(w):
def loss(true, pred):
true=tf.cast(true, dtype=tf.float32)
error = K.square(true - pred)
error = K.switch(K.equal(true, 1), error/w , error)
return error
return loss



