您可以使用 Numpy's 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]
是另一个很好的示例。我不介意它是如何采样的,我只对向我的样本空间的开头和结尾返回更多样本的采样方法感兴趣。
一种解决方案是从高斯分布中抽取指数样本,如果您得到一个接近分布均值的数字,您可以在样本空间的开头或结尾绘制一个更接近的数字。然而,这种方法似乎比它需要的更复杂,而且不能保证你能得到好的 sample 。
有人知道在样本空间的开头和结尾生成样本的好方法吗?
最佳答案
这将为您提供更多样本到间隔的结束:
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. ])
关于python - 在样本空间的开始和结束处使用更多样本进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102014/