python - 使用 sklearn.utils.resample 带分层和不带分层的区别

标签 python scikit-learn

使用 sklearn.utils.resample 带分层和不带分层有什么区别?

https://scikit-learn.org/stable/modules/generated/sklearn.utils.resample.html

import numpy
from sklearn.utils import resample


y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
res = resample(y, n_samples=5, replace=False, random_state=0)
print (res)
[1, 1, 0, 1, 1]

res = resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
print (res)

[1, 1, 1, 0, 1]

最佳答案

Stratify 表示保留原始类中的分布。

查看原始分布中的频率:

from sklearn.utils import resample
seed=42
np.random.seed(seed)
y = np.random.choice([0,1],size=100000, p=[.5,.5])
np.unique(y,return_counts=True)
(array([0, 1]), array([49934, 50066]))

然后,不进行分层的重新采样:

res = resample(y, n_samples=10000, replace=True, stratify=None, random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([5049, 4951]))

最后是分层:

res = resample(y, n_samples=10000, replace=True, stratify=y,random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([4993, 5007]))

关于python - 使用 sklearn.utils.resample 带分层和不带分层的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60321703/

相关文章:

python - 为什么具有名为 "del"、 "return"等的对象属性是语法错误?

检测到 Chromedriver 的 Python Selenium

python - 为什么 Python 是 3's PrettyPrinter behaving differently from Python 2' s,我如何获得相同的行为?

list - 通过反转另一个列表来扩展一个列表的最Pythonic方法是什么?

python - 创建给定位置的房地产价格指数

python - 使用 sklearn OneHotEncoder 时如何忽略数字列?

python - 在 self._compute_kernel(X) 中引发 ValueError ("X.shape[0] should be equal to X.shape[1]")

python - CountVectorizer 中的样本数量不一致

python - 调用另一个函数并可选择保留默认参数

python - sklearn roc_auc_score 与 multi_class= ="ovr"应该没有可用的平均值