我有一个很大的元素列表(在这个例子中我假设它充满了数字)。例如:l = [1,2,3,4,5,6,7,8,9,10]
现在我想从该列表中取出 2 个样本,一个包含 80% 的元素(当然是随机选择的),另一个包含剩余元素(20%),所以我可以使用更大的元素一个用于训练机器学习工具,其余的用于测试训练。我使用的函数来自random
,我这样使用它:
sz = len(l) #Size of the original list
per = int((80 * sz) / 100) #This will be the length of the sample list with the 80% of the elements (I guess)
random.seed(1) # As I want to obtain the same results every time I run it.
l2 = random.sample(l, per)
我不完全确定,但我相信使用该代码我会得到包含 80% 数字的随机样本。
l2 = [3,4,7,2,9,5,1,8]
尽管如此,我似乎找不到获取具有剩余元素的其他示例列表的方法 l3 = [6,10]
(sample()
函数不会删除它从原始列表中获取的元素)。你能帮我么?预先感谢您。
最佳答案
对我来说,以下代码可以将列表随机拆分为两个(训练/测试)集,尽管大多数机器学习库都包含前面提到的易于使用的拆分函数:
l = [1,2,3,4,5,6,7,8,9,10]
sz = len(l)
cut = int(0.8 * sz) #80% of the list
shuffled_l = random.shuffle(l)
l2 = shuffled_l[:cut] # first 80% of shuffled list
l3 = shuffled_l[cut:] # last 20% of shuffled list
关于python - 如何在Python中使用random.sample()后获取剩余的样本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526577/