【问题标题】:stratified sample with replacement in pythonpython中带有替换的分层样本
【发布时间】:2019-03-11 11:11:20
【问题描述】:

我有一只熊猫DataFrame。我正在尝试创建一个带有替换的样本DataFrame 并对其进行分层。

这让我可以替换:

df_test = df.sample(n=100, replace=True, random_state=42, axis=0)

但是,我不确定如何分层。我可以使用weights 参数吗?如果可以,如何使用?我要分层的列是字符串。

这让我可以分层:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, Y, test_size=.50, stratify=Y, random_state=42)

但是,没有替换选项。

我怎样才能同时分层和替换?

【问题讨论】:

  • 你想用什么替换?

标签: python random sample sklearn-pandas


【解决方案1】:

这是一个有点老的问题,但由于谷歌首先在我寻找同样的东西时返回了这个问题,所以我认为把这个留在这里对每个人都很有用,包括我未来的自己。

显然sklearnsklearn.utils.resample 中提供了此功能:

from sklearn import datasets
from sklearn.utils import resample

X, y = datasets.load_iris(return_X_y=True)
X_new, y_new = resample(X, y, stratify=y)

您可以使用n_samples 参数控制样本数量。默认情况下,它设置为None,因此您可以返回X.shape[0] 替换随机样本(因为这是为引导目的而设计的)。希望这对某人有所帮助。

【讨论】:

【解决方案2】:

据我所知,sklearn 中的默认 StratifiedShuffleSplit 将运行替换,即非互斥策略。希望我理解正确。

import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 0, 1, 1, 1])
sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)
sss.get_n_splits(X, y)

print(sss)       

for train_index, test_index in sss.split(X, y):
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = X[train_index], X[test_index]
   y_train, y_test = y[train_index], y[test_index]

产量:

TRAIN: [5 2 3] TEST: [4 1 0]
TRAIN: [5 1 4] TEST: [0 2 3]
TRAIN: [5 0 2] TEST: [4 3 1]
TRAIN: [4 1 0] TEST: [2 3 5]
TRAIN: [0 5 1] TEST: [3 4 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多