使用嵌套交叉验证在SKlearn中生成分类报告(平均值/个体值)

是否可以通过某种方法从cross_val_score中获取分类报告?我正在使用嵌套交叉验证,并且可以在这里获得模型的各种分数,但我希望看到外层循环的分类报告。有何建议?

# 选择内外循环的交叉验证技术,独立于数据集。
# 例如 "LabelKFold", "LeaveOneOut", "LeaveOneLabelOut" 等。
inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)
outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)
# 非嵌套参数搜索和评分
clf = GridSearchCV(estimator=svr, param_grid=p_grid, cv=inner_cv)
# 带参数优化的嵌套交叉验证
nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)

我想在这里看到分类报告和分数值。http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html


回答:

我们可以定义自己的评分函数如下:

from sklearn.metrics import classification_report, accuracy_score, make_scorer
def classification_report_with_accuracy_score(y_true, y_pred):
    print classification_report(y_true, y_pred) # 打印分类报告
    return accuracy_score(y_true, y_pred) # 返回准确率分数

现在,只需使用make_scorer调用cross_val_score,并使用我们的新评分函数:

# 带参数优化的嵌套交叉验证
nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv, \
               scoring=make_scorer(classification_report_with_accuracy_score))
print nested_score 

它将同时打印分类报告的文本,并以数字形式返回nested_score

当使用这个新评分函数运行http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html示例时,输出的最后几行将如下所示:

#   precision    recall  f1-score   support    #
#0       1.00      1.00      1.00        14
#1       1.00      1.00      1.00        14
#2       1.00      1.00      1.00         9
#avg / total       1.00      1.00      1.00        37
#[ 0.94736842  1.          0.97297297  1. ]
#平均差异为0.007742,标准偏差为0.007688。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注