【问题标题】:How to get the remaining sample after using random.sample() in Python?在 Python 中使用 random.sample() 后如何获取剩余样本?
【发布时间】:2019-01-02 17:25:51
【问题描述】:

我有一个很大的元素列表(在这个例子中,我假设它是用数字填充的)。例如: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() 函数不会删除它从原始列表中获取的元素)。你能帮我么?提前谢谢你。

【问题讨论】:

标签: python python-3.x random sample


【解决方案1】:

你可以这样做:

from random import sample

data = [1, 2, 3, 4, 5]

training = sample(a, len(data)*cut)

testing = [value for value in data if value not in training]

【讨论】:

    【解决方案2】:

    对我来说,以下代码可以将一个列表随机拆分为两个(训练/测试)集,尽管大多数机器学习库都包含前面提到的易于使用的拆分函数:

    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
    

    【讨论】:

    • 根据文档,random.shuffle 将 Shuffle the sequence x in place. ... To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead. - docs 所以要么在 l 上调用 shuffle 并使用 l 进行剪切,或者如果你想要一个新的列表使用样本。编写的代码不起作用,shuffled_l 是 None
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多