pandas - 如何拆分重复样本以训练没有重叠的测试?
问题描述
我有一个 nlp 数据集(大约300K样本),其中存在重复数据。我想把它分成训练测试(<em> 70%-30%),它们应该没有重叠。
例如:
|dataset: | train | test |
| a | a | c |
| a | a | c |
| b | b | c |
| b | b | |
| b | b | |
| c | d | |
| c | d | |
| c | | |
| d | | |
| d | | |
我已经厌倦了详尽的随机样本,但它太耗时了。
解决方案
这是可行的,但需要几个步骤才能完成。
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# original dataset with duplicates
dataset = pd.DataFrame(["a", "a", "b", "b", "b", "c", "c", "c", "d", "d"])
# get unique values, remove duplicates, but keep original counts
data_no_dup, counts = np.unique(dataset, return_counts=True)
# split using the standard Scikit-Learn way
train_no_dup, test_no_dup = train_test_split(data_no_dup, test_size=0.2, random_state=0)
# retrieve original counts
train, test = [], []
for sample in train_no_dup:
train.extend([sample] * counts[list(data_no_dup).index(sample)])
for sample in test_no_dup:
test.extend([sample] * counts[list(data_no_dup).index(sample)])
print("Train: {}".format(train))
print("Test: {}".format(test))
输出
Train: ['d', 'd', 'b', 'b', 'b', 'a', 'a']
Test: ['c', 'c', 'c']
推荐阅读
- python - 嵌套列表理解-双迭代-Python中的经典CS问题-第3章-单词搜索
- powershell - forloop 正在循环,但只有相同的字符串
- python - 在 Python 列表中查找表示数字的连续字符串
- c - 设计一个算法来判断是否存在这样一个key等于数组中其他两个key之和
- excel - 根据以前的结果和 Excel 上的百分比计算最有可能的下一个结果
- python - 将 HTML 颜色名称转换为十六进制
- r - 多个公式叠加在散点图上
- mysql - 如何在mysql中定义一个表来保存4个非强制下拉值
- ruby-on-rails - 提交后选择值为空(Rails)
- flutter - 有没有办法在 Flutter WebView 中启用 Chrome 标志?