首页 > 解决方案 > 如何使用 mean_squared_error 作为 sklearn.model_selection.cross_val_score() 的损失

问题描述

我可以使用“categorical_crossentropy”作为损失函数而不会出错,但是当我用“mse”替换它时,会出现这个错误:

检查目标时出错:预期 dense_2 的形状为 (2,) 但得到的数组的形状为 (1,)

如果我使用以下方法

labels = np_utils.to_categorical(labels, num_classes = 2)

另一个错误引发:

支持的目标类型是:('binary', 'multiclass')。取而代之的是“多标签指示器”。

问题是如何将“mse”与 cross_val_score() 函数一起使用?

这是 github链接,这是麻烦的代码:

model = KerasClassifier(build_fn=customXceptionBuild, epochs=epochs, batch_size=batch_size)
kfold = StratifiedKFold(n_splits=folds, shuffle=True, random_state=random_state)

def classification_report_with_accuracy_score(y_true, y_pred):
    originalclass.extend(y_true)
    predictedclass.extend(y_pred)
    return accuracy_score(y_true, y_pred) # return accuracy score

scoring = make_scorer(classification_report_with_accuracy_score)

scores = cross_val_score(model, data, labels, cv=kfold, error_score="raise", scoring=scoring ) 

customXceptionBuild 函数实现了 Xception 预训练模型,并使用“mse”作为损失函数。

标签: pythonkerasscikit-learndeep-learningloss-function

解决方案


第一个错误是关于输出大小不匹配,改变这个

F3 = Dense(classes, activation='softmax')(D2)

F3 = Dense(1, activation='softmax')(D2)

由于这是一个二元分类,您只需要 1 个神经元。

或者,如果您想修复第二个错误,这就是原因。不可能对 one-hot 编码标签进行分层。您可以在分层后进行一次热编码。因此,

labels = np_utils.to_categorical(labels, num_classes = 2)

应该紧随其后

kfold = StratifiedKFold(n_splits=folds, shuffle=True, random_state=random_state)

推荐阅读