python - 具有不平衡类的 k 折分层交叉验证

标签 python machine-learning scikit-learn

我有 4 个类的数据,我正在尝试构建一个分类器。一类有~1000个向量,另一类有~10^4,第三类有~10^5,第四类有~10^6。我希望使用交叉验证,所以我查看了 scikit-learn docs .

我的第一次尝试是使用 StratifiedShuffleSplit但这为每个类(class)提供了相同的百分比,使类(class)仍然严重不平衡。

Is there a way to do cross-validation but with the classes balanced in the training and test set?


附带说明,我无法计算出 StratifiedShuffleSplit 之间的区别。和 StratifiedKFold .描述看起来和我很相似。

最佳答案

My first try was to use StratifiedShuffleSplit but this gives the same percentage for each class, leaving the classes drastically imbalanced still.

我感觉您对分层策略的作用感到困惑,但您需要展示您的代码和结果来确定发生了什么(与原始集合中的百分比相同,还是返回的训练/测试集中的相同百分比?第一个是它应该是的)。

As a side note, I couldn't work out the difference between StratifiedShuffleSplit and StratifiedKFold . The descriptions look very similar to me.

其中一个肯定可以工作。第一个的描述肯定有点令人困惑,但这就是它们的作用。

StratifiedShuffleSplit

Provides train/test indices to split data in train test sets.

这意味着它将您的数据拆分为训练集和测试集。分层部分意味着将在此拆分中保持百分比。所以如果 10%您的数据属于第 1 类和 90%属于第 2 类,这将确保 10%您的火车组将在 1 类和 90%将在第 2 类。测试集也一样。

您的帖子听起来像是您想要的 50%测试集中的每个类。这不是分层所做的,分层保持原始百分比。你应该维护它们,否则你会给自己一个关于分类器性能的不相关的想法:谁在乎它对 50/50 的分类效果如何?拆分,在实践中你会看到 10/90 split ?

分层KFold

This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class.

k-fold cross validation .如果没有分层,它只会将您的数据拆分为 k折叠。然后,每折1 <= i <= k一次作为测试集,其他用于训练。结果最后取平均值。它类似于运行 ShuffleSplit k次。

分层将确保每个类别在整个数据中的百分比在每个单独的折叠中都相同(或非常接近)。


有很多关于不平衡类的文献。一些简单易用的方法包括使用类权重和分析 ROC 曲线。我建议以下资源作为起点:

  1. A scikit-learn example of using class weights .
  2. A quora question about implementing neural networks for imbalanced data .
  3. This stats.stackexchange question with more in-depth answers .

关于python - 具有不平衡类的 k 折分层交叉验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32615429/

相关文章:

python - 无法迭代二维数组来标准化数据

python-3.x - 为 tf.nn.embedding_lookup 预处理不同文本大小时 Pre-Padding 和 Post-Padding 文本的差异

python - scikit 学习中的逻辑回归

python - 通过 SSH 运行和安装脚本缺少的模块

python - 使用pyenv在Python的两个系统版本之间切换

python - 类型错误 : reduction operation 'argmax' not allowed for this dtype

performance - MATLAB 中人工神经网络的回归与性能图之间的差异

python-3.x - “管道”对象不可订阅

python - sklearn |线性回归 |合身

python - 无法卸载 Tensorflow