python - 在样本空间的开始和结束处有更多样本的样本
问题描述
您可以使用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。我不介意它是如何采样的,我只对在我的样本空间的开头和结尾返回更多样本的采样方法感兴趣。
一种解决方案是从高斯分布中采样索引,如果你得到一个接近分布平均值的数字,你就会在靠近样本空间的开头或结尾处画一个数字。但是,这种方法似乎比它需要的要复杂,并且不能保证您得到好的样本。
有谁知道在样本空间的开头和结尾生成样本的好方法?
解决方案
这将为您在间隔结束时提供更多样本:
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. ])
推荐阅读
- css - css 调试表格单元格内内联块 svgs 的响应高度
- javascript - 当来自 Google 表单的表单条目到达 Google 表格时,从邮政编码自动填充状态
- c# - Razor Pages 将处理程序中的图像返回给 ` ` 元素
- oauth-2.0 - OAuth 错误 400:invalid_request 缺少方案:/login
- react-native - 无法为 react-native 17.0.1 安装 material-ui/core
- excel - 有没有办法使用每个基于文本的单元格作为分隔符将一列分成多列?
- gpu - 在 OpenCL 上使用阻塞写入和带有非阻塞写入的 event.wait() 之间的区别
- ios - AF.upload 问题“模式无法匹配 URLRequest 类型的值”
- ag-grid - ag-Grid: enableRowGroup 只在 ag-Grid-Enterprise 中有效,你的列定义不应该有 enableRowGroup
- c# - 无法转换类型'System.Threading.Tasks.Task
' 到 'Microsoft.AspNetCore.Mvc.OkObjectResult'