微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 通过使用pandas中groupby()的百分比从Train集中获取验证集

拥有具有多类目标变量类别的训练数据集

train.groupby('category').size()

0     2220
1     4060
2      760
3     1480
4      220
5      440
6    23120
7     1960
8    64840
@H_502_6@

我想通过获得每个类的百分比(比如说20%)从列车集中获取新的验证数据集,以避免在验证集中丢失类并破坏模型.所以基本上理想的输出将是df具有相同的结构和信息,如火车组,但具有如下参数:

0     444
1     812
2     152
3     296
4      44
5      88
6    4624
7     392
8   12968
@H_502_6@

在熊猫中解决它是否有任何直接的方法

解决方法:

Groupby和sample应该为您做到这一点

df = pd.DataFrame({'category': np.random.choice(['a', 'b', 'c', 'd', 'e'], 100), 'val': np.random.randn(100)})

idx = df.groupby('category').apply(lambda x: x.sample(frac=0.2, random_state = 0)).index.get_level_values(1)

test = df.iloc[idx, :].reset_index(drop = True)
train = df.drop(idx).reset_index(drop = True)
@H_502_6@

编辑:你也可以用scikit学习,

df = pd.DataFrame({'category': np.random.choice(['a', 'b', 'c', 'd', 'e'], 100), 'val': np.random.randn(100)})

X = df.iloc[:, :1].values
y = df.iloc[:, -1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = X)

X_train.shape, X_test.shape, y_train.shape, y_test.shape

((80, 1), (20, 1), (80,), (20,))
@H_502_6@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐