【问题标题】:Why optimizing models for precision throws me error: Precision is ill-defined and being set to 0.0 due to no predicted samples?为什么针对精度优化模型会引发错误:由于没有预测样本,精度定义不明确并设置为 0.0?
【发布时间】:2019-09-30 08:02:13
【问题描述】:

我正在尝试预测糖尿病,其中 1 = 糖尿病患者和 0 = 非糖尿病患者,并且我正在使用随机森林和决策树。我的数据明显不平衡,导致我的分类器预测敏感性为 0,特异性为 99。它尝试了几种方法,包括使用 SMOTE 重新采样我的数据。现在我想优化模型的精度以提高真阳性率,但是当我运行 gridsearch 时,它会抛出以下错误:

UndefinedMetricWarning:精度定义不明确,由于没有预测样本而被设置为 0.0。

无论如何我都尝试进行预测,结果与我没有使用精度优化时的结果相同。

我的代码如下所示:

cl = RandomForestClassifier() 
params = {  
    'n_estimators': [100, 300, 500, 800, 1000],
    'criterion': ['gini', 'entropy'],
    'bootstrap': [True, False],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [4,5,6,7,8],
}

scorers = {
    'precision_score': make_scorer(precision_score),
    'recall_score': make_scorer(recall_score),
    'accuracy_score': make_scorer(accuracy_score)
}

clff = GridSearchCV(estimator=cl, scoring= scorers, param_grid=params, refit='precision_score', cv=5, verbose=0)

forestscore= clff.fit(X_train, y_train) 

有人可以帮助我了解该怎么做以及问题出在哪里吗?

【问题讨论】:

    标签: python scikit-learn precision cross-validation grid-search


    【解决方案1】:

    问题可能在于,由于您的估算器总是返回相同的值,y_train 的某些标签永远无法预测。因此,无法预测准确度。您可以在此线程上找到类似的问题:

    UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

    如果您尝试这些行,则会收到错误消息:

    from sklearn.metrics import precision_score
    y_true = [0, 1, 1, 0, 1, 1]
    y_pred = [0, 0, 0, 0, 0, 0]
    precision_score(y_true, y_pred)
    
    UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples.
      'precision', 'predicted', average, warn_for)
    0.0
    

    精度分数似乎需要二进制值才能正确计算分数。由于您的向量之一(在您的情况下是预测的)仅由 0 组成,因此无法计算分数,然后将其设置为 0.0

    消除此警告的解决方案是使用您的估算器成功计算 1,因此为 score 函数提供的预测 y 不为零。

    【讨论】:

    • 我以正确的方式将数据集拆分为训练和测试,所以我真的不知道该怎么办。我显然不想让警告静音,因为这对我的预测没有帮助。当我运行网格搜索@AntoningG 时,此警告正在运行。
    • 我完成了我之前的回答给你一个例子@LuisaKa
    • 非常感谢! @AntoninG。
    猜你喜欢
    • 2019-09-22
    • 2018-09-25
    • 2020-07-27
    • 2021-10-02
    • 2018-09-29
    • 2022-01-09
    • 2017-07-07
    • 2016-10-01
    • 2016-05-15
    相关资源
    最近更新 更多