gpt4 book ai didi

keras - Keras 中验证集的不同损失函数

转载 作者:行者123 更新时间:2023-12-02 01:20:51 27 4
gpt4 key购买 nike

我有不平衡的训练数据集,这就是我构建自定义加权分类交叉熵损失函数的原因。但问题是我的验证集是平衡的,我想使用常规的分类交叉熵损失。那么我可以在 Keras 中为验证集传递不同的损失函数吗?我的意思是用于训练的加权集和用于验证集的常规集?

def weighted_loss(y_pred, y_ture):
'
'
'


return loss

model.compile(loss= weighted_loss, metric='accuracy')

最佳答案

您可以尝试后端函数 K.in_train_phase()DropoutBatchNormalization 层使用该函数来实现不同的行为培训和验证。

def custom_loss(y_true, y_pred):
weighted_loss = ... # your implementation of weighted crossentropy loss
unweighted_loss = K.sparse_categorical_crossentropy(y_true, y_pred)
return K.in_train_phase(weighted_loss, unweighted_loss)

K.in_train_phase()的第一个参数是训练阶段使用的张量,第二个参数是测试阶段使用的张量。

例如,如果我们将weighted_loss设置为0(只是为了验证K.in_train_phase()函数的效果):

def custom_loss(y_true, y_pred):
weighted_loss = 0 * K.sparse_categorical_crossentropy(y_true, y_pred)
unweighted_loss = K.sparse_categorical_crossentropy(y_true, y_pred)
return K.in_train_phase(weighted_loss, unweighted_loss)

model = Sequential([Dense(100, activation='relu', input_shape=(100,)), Dense(1000, activation='softmax')])
model.compile(optimizer='adam', loss=custom_loss)
model.outputs[0]._uses_learning_phase = True # required if no dropout or batch norm in the model

X = np.random.rand(1000, 100)
y = np.random.randint(1000, size=1000)
model.fit(X, y, validation_split=0.1)

Epoch 1/10
900/900 [==============================] - 1s 868us/step - loss: 0.0000e+00 - val_loss: 6.9438

正如你所看到的,训练阶段的损失确实是1乘以0。

请注意,如果模型中没有 dropout 或批量归一化,您需要手动“打开”_uses_learning_phase bool 开关,否则K.in_train_phase() 默认情况下没有任何效果。

关于keras - Keras 中验证集的不同损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com