在样本空间的开头和结尾处有更多样本的样本

时间:2019-07-18 20:13:10

标签: python numpy

您可以使用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]是另一个很好的采样。我不介意如何进行采样,我只是对采样方法感兴趣,该方法会将更多样本返回到样本空间的开始和结尾

一种解决方案是从高斯分布中采样索引,如果得到的数字接近分布均值,则会在样本空间的开始或结尾处绘制一个数字。但是,此方法似乎比需要的方法复杂得多,并且不能保证您获得好的样本。

有人知道在样本空间的开始和结尾生成样本的好方法吗?

2 个答案:

答案 0 :(得分:3)

这将为您提供更多样本到间隔的结束

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

您可以选择较高的指数以使末端的频率更高。

要获取更多样本到间隔的开始结束,请将原始线性空间对称为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. ])

答案 1 :(得分:3)

您可以重新缩放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.        ])
相关问题