python - 通过在 pandas 中使用 groupby() 的百分比从训练集中获取验证集
问题描述
拥有一个包含多类目标变量的训练数据集category
train.groupby('category').size()
0 2220
1 4060
2 760
3 1480
4 220
5 440
6 23120
7 1960
8 64840
我想通过每个类的百分比(比如说 20%)从训练集中获取新的验证数据集,以避免在验证集中丢失类并破坏模型。所以基本上理想的输出将是 df 具有相同的结构和信息,如火车集,但参数如下:
0 444
1 812
2 152
3 296
4 44
5 88
6 4624
7 392
8 12968
是否有任何直接的方法可以在熊猫中解决它?
解决方案
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)
编辑:您也可以使用 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,))
推荐阅读
- excel - MS Access 有没有办法根据以前的记录进行计算?
- android - Wayland 上的 Android 模拟器:模拟器以退出代码 134 终止
- python - 在列中保留第一次出现的值模式
- android - 在 Android 应用程序中安装预填充的 SQLite 数据库的最佳方法是什么?
- flutter - Gridview 和 Gridtile Flutter
- reactjs - 你能下载整个 Amplify webapp 吗?
- r - R: Shiny Flexdashboard: 为什么 selectInput 不显示所有选项?
- php - 隐藏 iframe(加载 PHP 函数),直到单击表单按钮
- python - 使用正则表达式清洁歌词
- html - Pandoc:是否可以在 markdown 中禁用对内联 HTML 的解释?