数据预处理--采样

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_WBCG/article/details/79105898

采样

采样就是按照某种规则从数据集中挑选样本数据。通常应用场景数据样本过大,抽取少部分样本来训练或验证,不仅可以节约计算机资源,在特定情况下也会提升实验效果。

随机采样

随机采样是从被采样数据集中随机地抽取特定数量的数据,需要指定采样的个数。随机采样分为 有放回采样无放回采样
有放回采样: 可能会出现重复数据
无放回采样:采样数据不会出现重复的样本数据

系统采样

系统采样又称等距采样,就是将总体的采样数据集按某一顺序号分成n个部分,再从第一部分随机抽取第k号数据,依次用相等间距从每一部分中各抽取一个数据来组成样本。 使用场景主要针对按一定关系排好的数据。
系统样本对于样本的限定过大,往往针对于不同层级的采样需要通过分层采样实现。

分层采样

分层采样是先将采样数据集分成若干个类别,再从每一类别内随机抽取一定数量的数据,然后将这些数据组合在一起。分层采样主要被用于生成训练样本的场景中。因为在监督学习中,正负样本的比例是不可控的,当正负样本的比例过大或过小时,对于样本训练结果都是有影响的,所以通常需要分层采样来控制训练样本中的正负样本比例。
分层采样从每一个层级中随机的抽取出特定的数据,每个层级抽取的比例是可以自定义的。

示例

注:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
       random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列

import random

dataMat = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# 分布式采样所用数据
dataMat1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
dataMat2 = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 115, 114, 116, 117, 118, 119]
dataMat3 = [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017,
            1018, 1019]


# 放回式随机采样
def RepetitionRandomSampling(dataMat, number):
    sample = []
    for i in range(number):
        sample.append(dataMat[random.randint(0, len(dataMat) - 1)])
    return sample


# 无放回式随机采样
def RandomSampling(dataMat, number):
    try:
        slice = random.sample(dataMat, number)
        return slice
    except:
        print("sample larger than population")


# 系统采样
def SystematicSampling(dataMat, number):
    length = len(dataMat)
    k = length / number
    k = k.__int__()
    sample = []
    i = 0
    if k > 0:
        while len(sample) != number:
            sample.append(dataMat[0 + i * k])
            i += 1
        return sample
    else:
        return RandomSampling(dataMat, number)


# 分布式采样
def StratifiedSampling(dataMat1, dataMat2, dataMat3, number):
    sample = []
    num = number / 3
    num=num.__int__()
    sample.append(RandomSampling(dataMat1, num))
    sample.append(RandomSampling(dataMat2, num))
    sample.append(RandomSampling(dataMat3, num))
    return sample


if __name__ == '__main__':
    print("数据集:")
    print(dataMat)
    print("无放回式采样:")
    slice = RandomSampling(dataMat, 8)
    print(slice)
    print("放回式采样:")
    sample = RepetitionRandomSampling(dataMat, 15)
    print(sample)
    print("系统采样:")
    sample = SystematicSampling(dataMat, 5);
    print(sample)
    print("分布式采样:")
    sample = StratifiedSampling(dataMat1, dataMat2, dataMat3, 9);
    print(sample)




猜你喜欢

转载自blog.csdn.net/M_WBCG/article/details/79105898