【问题标题】:GridSearch 'UndefinedMetricWarning' and bad resultGridSearch 'UndefinedMetricWarning' 和错误的结果
【发布时间】:2017-12-01 12:46:02
【问题描述】:

我创建了一个简单的脚本来在随机森林分类器上应用网格搜索,虽然我过去曾使用过它,但现在它似乎坏了,我找不到原因。

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV

rfc = RandomForestClassifier(n_estimators=100, n_jobs=-1).fit(X, y)


grid_values = {'criterion':['gini','entropy'], 'max_features':['log2', 5, 10, 15, 20, 25], 'max_depth':[None, 5, 10, 15, 20],
               'min_samples_split':[2, 3],'n_jobs':[-1], 'class_weight': [{0 : 1., 1: 30.}, {0 : 1., 1: 50.}, {0 : 1., 1: 100.}]}

for eval_metric in ('precision', 'accuracy'):
  rfc_custom = GridSearchCV(rfc, param_grid=grid_values, scoring=eval_metric)
  rfc_custom.fit(X_train, y_train)
  rfc_custom.best_params_
  print('Grid best parameter (max. {0}): {1}'
         .format(eval_metric, rfc_custom.best_params_))
  print('Grid best score ({0}): {1}'
         .format(eval_metric, rfc_custom.best_score_))

当我运行它时,我收到以下警告:UndefinedMetricWarning: Precision is ill-defined and is set to 0.0 due to no predict samples.

在线搜索,我添加了此代码并且警告停止:

import warnings
import sklearn.exception

warnings.filterwarnings("ignore",category=sklearn.exceptions.UndefinedMetricWarning)

运行算法后,我得到 0.0 的精度

这是正常的,因为我收到了警告吗?我可能错过了什么吗?

【问题讨论】:

  • 下面的代码只隐藏了警告,但不改变算法的行为。问题是在预测值中,有一些类,算法从未预测过,所以精度是不确定的。
  • 哪一行发出了警告?
  • 它在 'GridSearchCV(rfc, param_grid=grid_values,scoring=eval_metric)' 行中发出。据我了解,每个交叉验证都会产生此错误,因为同一指标会产生多个错误。

标签: python scikit-learn


【解决方案1】:

我认为在某些 CV 条件下没有 TP 和 FP 样本,因此 GridSearchCV 内部发生了零分裂。如果验证数据没有标签数据,或者所有样本都以某种方式错误分类到其他样本中,就会发生这种情况。

memo:精度的定义是(TP)/(TP+FP),其中TP为真阳性,FP为假阳性。

【讨论】:

  • 这确实有道理,因为我在不均匀的数据集中只使用了几行(1000 行),只是为了检查我的算法是否有效。有没有办法确认所有交叉验证样本都是分层的?
  • 您需要手动分离StratifiedKFold的数据集。
  • 然后,画一个confusion matrix,检查每个预测标签至少有一个样本。
  • 我不确定是否有从 GridSearchCV 对象中提取此类信息的好方法...
猜你喜欢
  • 2016-03-15
  • 2022-10-21
  • 2021-10-10
  • 2020-03-15
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多