我有一些数据集。我想把它分成一列火车和一组测试。列车组将保存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:
的次数太多了。你知道问题是什么吗
正如Michael Gardner所说,
train_test_split
是您正在寻找的函数默认情况下,它将随机拆分,但您可以使用
stratify
告诉它您希望在训练和测试数据集中的类列具有相同的比率它的工作原理如下:
相关问题 更多 >
编程相关推荐