首页 > 解决方案 > 在样本空间的开始和结束处有更多样本的样本

问题描述

您可以使用Numpy 的 Linspace在指定的时间间隔内获得均匀间隔的数字:

$ import numpy as np
$ np.linspace(0,10,5)
>>> array([ 0. ,  2.5,  5. ,  7.5, 10. ])

但是,我想在间隔的开始和结束时采样更多的数字。例如,如果我的间隔是[0-10]并且我想要 5 个样本。一个好的样本是:

>>> array([0, 1, 5, 9, 10])

我知道有人可能会说有很多方法可以对这个空间进行采样,例如:[0, 0.5, 5, 9.5, 10]is another good sample。我不介意它是如何采样的,我只对在我的样本空间的开头和结尾返回更多样本的采样方法感兴趣

一种解决方案是从高斯分布中采样索引,如果你得到一个接近分布平均值的数字,你就会在靠近样本空间的开头或结尾处画一个数字。但是,这种方法似乎比它需要的要复杂,并且不能保证您得到好的样本。

有谁知道在样本空间的开头和结尾生成样本的好方法?

标签: pythonnumpy

解决方案


这将为您在间隔结束时提供更多样本:

np.sqrt(np.linspace(0,100,5))
array([  0.        ,   5.        ,   7.07106781,   8.66025404,  10.        ])

您可以选择更高的指数以获得更频繁的间隔。

要在间隔的开头结尾获得更多样本,请将原始 linspace 对称为 0,然后将其移位。

一般功能:

def nonlinspace(xmin, xmax, n=50, power=2):
    '''Intervall from xmin to xmax with n points, the higher the power, the more dense towards the ends'''
    xm = (xmax - xmin) / 2
    x = np.linspace(-xm**power, xm**power, n)
    return np.sign(x)*abs(x)**(1/power) + xm + xmin

例子:

>>> nonlinspace(0,10,5,2).round(2)
array([  0.  ,   1.46,   5.  ,   8.54,  10.  ])
>>> nonlinspace(0,10,5,3).round(2)
array([  0.  ,   1.03,   5.  ,   8.97,  10.  ])
>>> nonlinspace(0,10,5,4).round(2)
array([  0. ,   0.8,   5. ,   9.2,  10. ])

推荐阅读