【问题标题】:How to use mean_squared_error as loss with sklearn.model_selection.cross_val_score()如何使用 mean_squared_error 作为 sklearn.model_selection.cross_val_score() 的损失
【发布时间】:2019-09-28 21:31:22
【问题描述】:

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

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

如果我使用下面的方法

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

另一个错误引发:

支持的目标类型有:('binary', 'multiclass')。改为使用“多标签指示符”。

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

这是github link,这是麻烦的代码:

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”作为损失函数。

【问题讨论】:

    标签: python keras scikit-learn deep-learning loss-function


    【解决方案1】:

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

    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)
    

    【讨论】:

    • thx 但它如何与“categorical_crossentropy”一起使用?如果我删除 "labels = np_utils.to_categorical(labels, num_classes = 2)" 行,它会起作用。
    • 它适用于 categorical_crossentropy,因为它适用于多类问题。你的问题类型是什么?二进制还是多类?在深入编程之前最好先阅读理论。
    • 正如我所提到的,这是多类问题。你说是二分类!
    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 2019-09-03
    • 2019-07-12
    • 2013-11-28
    • 2020-08-20
    • 2023-04-03
    • 2020-11-26
    • 2017-11-19
    相关资源
    最近更新 更多