本文介绍了Keras在二元分类模型中的类权重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,对于二进制分类模型中的不平衡数据,我们可以通过fit方法传递类权重字典.我的问题是,当在输出层中仅使用1个节点进行S形激活时,在训练过程中我们还可以应用类权重吗?

We know that we can pass a class weights dictionary in the fit method for imbalanced data in binary classification model. My question is that, when using only 1 node in the output layer with sigmoid activation, can we still apply the class weights during the training?

model = Sequential()
model.add(Dense(64, activation='tanh',input_shape=(len(x_train[0]),)))
model.add(Dense(1, activation='sigmoid')) 

model.compile(
    optimizer=optimizer, 
    loss=loss, 
    metrics=metrics)

model.fit(
    x_train, y_train, 
    epochs=args.e, 
    batch_size=batch_size,
    class_weight={0: 1, 1: 3})

推荐答案

如果要完全控制此权重,为什么不编写自定义损失函数?

If you want to fully control this weight, why not write a custom loss function?

from keras import backend as K
def weighted_binary_crossentropy( y_true, y_pred, weight=1. ) :
    y_true = K.clip(y_true, K.epsilon(), 1-K.epsilon())
    y_pred = K.clip(y_pred, K.epsilon(), 1-K.epsilon())
    logloss = -(y_true * K.log(y_pred) * weight + (1 - y_true) * K.log(1 - y_pred))
    return K.mean( logloss, axis=-1)

这篇关于Keras在二元分类模型中的类权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 07:25