样品sp开头和结尾有更多样品的样品

2024-09-28 01:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

可以使用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]是另一个很好的示例。我不介意它是如何采样的,我只对采样方法感兴趣,这种方法在样本空间的开始和结束时返回更多的样本。你知道吗

一种解决方案是从高斯分布中抽取指数样本,如果你得到一个接近分布平均值的数字,你就可以在样本空间的起点或终点附近抽取一个数字。然而,这种方法似乎比它需要的更复杂,而且你不能保证得到好的样本。你知道吗

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


Tags: 方法importnumpy间隔asnp数字array
2条回答

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

这将给您提供更多的样本到间隔的结尾

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. ])

相关问题 更多 >

    热门问题