您可以使用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]
是另一个很好的样本。我不介意它是如何采样的,我只对采样方法感兴趣,这些方法在我的样本空间的开始和结束时返回更多样本。
一种解决方案是从高斯分布中对索引进行采样,如果您得到一个接近分布平均值的数字,则绘制一个更接近样本空间开头或结尾的数字。但是,这种方法似乎比需要的要复杂得多,并且不能保证获得好的样品。
有谁知道在样本空间的开头和结尾生成样本的好方法?
这将为您提供更多样本,直到间隔的末尾:
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. ])
您可以重新缩放tanh
以获得具有可调团块的序列:
import numpy as np
def sigmoidspace(low,high,n,shape=1):
raw = np.tanh(np.linspace(-shape,shape,n))
return (raw-raw[0])/(raw[-1]-raw[0])*(high-low)+low
# default shape parameter
sigmoidspace(1,10,10)
# array([ 1. , 1.6509262 , 2.518063 , 3.60029094, 4.8461708 ,
# 6.1538292 , 7.39970906, 8.481937 , 9.3490738 , 10. ])
# small shape parameter -> almost linear points
sigmoidspace(1,10,10,0.01)
# array([ 1. , 1.99995391, 2.99994239, 3.99995556, 4.99998354,
# 6.00001646, 7.00004444, 8.00005761, 9.00004609, 10. ])
# large shape paramter -> strong clustering towards the ends
sigmoidspace(1,10,10,10)
# array([ 1. , 1.00000156, 1.00013449, 1.01143913, 1.87995338,
# 9.12004662, 9.98856087, 9.99986551, 9.99999844, 10. ])