python-3.x - 随机样本集,用于根据标签创建交叉验证和训练集

标签 python-3.x pandas dataframe

我正在尝试从训练集中提取随机样本 60:20:20 以创建训练集、交叉验证集和测试集。

我使用了以下代码:

 train=data.sample(frac=0.6)
 trcv=data.drop(train.index)
 test=trcv.sample(frac=0.5)
 cv=trcv.drop(test.index)

但是我意识到我的训练集是监督学习数据,并且数据帧的最后一列包含值为 1 或 0 的标签 Y(列名称)。

我想要创建训练、测试和交叉验证集的方式是,我想要分配 0.99:.1 y=0 和 y=1 的样本并将其分配给训练集。这意味着如果训练集有 100 条记录,我希望 99 条记录为 y=0,只有一条记录为 y=1。

剩余 99% y=1 的记录需要在交叉验证和测试集之间分割为 45%、44%

一种可能的方法是创建一个包含 Y 列值为 1 的记录副本的数据帧,然后从主数据帧中删除 y=1 的所有记录。

Y1=data[data.iloc[:,8]==1]
data=data[data.iloc[:,8]!=1]

然后将上述样本分布应用于CV、测试和训练集。

 train=data.sample(frac=0.6)
 trcv=data.drop(train.index)
 test=trcv.sample(frac=0.5)
 cv=trcv.drop(test.index)

现在从 y=1 的数据帧中采样 0.1:0.44:0.45

ycvT=Y1.sample(frac=0.99)
ytr=Y1.drop(ycvT.index)
ytest= ycvT.sample(frac=0.45)
ycv= ycvT.drop(ytest.index)

这将创建 3 个包含 y=1 的不同数据帧。

Now I can add them to the training , cross validation and test set.
train=train.append(ytr)
train=train.sample(frac=1).reset_index(drop=True)

..以及简历和测试集。

我想知道是否有更聪明(更短)的方法来做到这一点。我想限制自己使用 pandas、numpy 和 scipy 。

有什么建议吗?谢谢。

最佳答案

y = data.iloc[:, -1].values
g = data.groupby(y)

frac = .2

ones = g.get_group(1).sample(frac=frac)
zero = g.get_group(0).sample(len(ones) * 99)

train = pd.concat([ones, zero]).sample(frac=1)

关于python-3.x - 随机样本集,用于根据标签创建交叉验证和训练集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579999/

相关文章:

python - pandas 系列中的独特值计数

if-statement - if else 在 pyspark 中用于折叠列值

python - 使用 python 弹出数据框单元格中的第一个元素

python - 仅针对图像的特定点计算相邻像素的平均像素强度,并将其存储在n维数组中

python-3.x - 模块 'tensorflow' 没有属性 'random_uniform'

python - 使用 pytest 用于 Python 项目的正确文件夹结构是什么?

python - 为 pandas 数据框中的单元格赋值

python-3.x - os.kill 与 process.terminate 在 aiohttp 中

Python Pandas 选择指数大于 x 的指数

python - 如何消除Python数据框中的列和行的索引值?