python - 试图将我的数据集拆分为具有代表性的训练集和测试集
问题描述
我有一些数据集。我想把它分成一个训练集和测试集。训练集将容纳 2/3 的数据。我希望这两个集合代表整个集合。在我的“类”列中,我有 4 个或 2 个来代表两个类。我希望我的测试集具有相同的 4:2 比例。为了做到这一点,我创建了这段代码:
trainTotal = 455
benTotal = 296
malTotal = 455-296
b = 0
m = 0
tr = 0
i = 0
j = 0
for index, row in data.iterrows():
if row['Class'] == 2:
if tr < trainTotal and b < benTotal:
train.loc[i] = data.iloc[index]
b = b+1
tr = tr + 1
i = i+1
else:
test.loc[j] = data.iloc[index]
j = j+1
if row['Class'] == 4:
if tr < trainTotal and m < malTotal:
train.loc[i] = data.iloc[index]
tr = tr + 1
i = i + 1
m = m+1
else:
test.loc[j] = data.iloc[index]
j = j + 1
我在我的火车数据框中得到了正确的值总数,但这些案例并没有像我希望的那样表示。它进入了if tr < trainTotal and b < benTotal:
太多次。知道问题可能是什么吗?
解决方案
就像迈克尔加德纳说的,train_test_split
是你正在寻找的功能。
默认情况下,它会随机拆分,但您可以stratify
告诉它您希望训练和测试数据集中的 Class 列具有相同的比率。
它是这样工作的:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
data,
target,
test_size = 0.3,
stratify=data[['your_column']]
)
推荐阅读
- c# - HttpClient POST 上传失败,没有文件传输和恶意生成 ContentDisposition
- reactjs - 如何防止加载反应父组件
- android - 我在哪里可以找到 Android Studio 的最新金丝雀版本的 android gradle 插件?
- for-loop - Clojure:如何返回在函数的 for 循环中计算的值
- php - 如何使用 PHP 和 CURL 从 API 端点发布到多个 ID?
- node.js - React 中的“npm start”命令执行了哪些任务?
- javascript - 当第一页内容太短时,平滑锚链接活动元素错误
- github - 如何将 2 个 git 存储库合并到一个项目中
- angular - 离子复选框“选中”属性不起作用
- sql - 从表中动态提取 XML 元素值的 Oracle 查询