带宽内核密度

2024-05-16 10:16:48 发布

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

我试图计算一系列值的核密度函数:

x=[-0.04124324405924407, 0, 0.005249724476788287, 0.03599351958245578, -0.00252785423151014, 0.01007584102031178, -0.002510349639322063, -0.01264302961474806, -0.01797169063489579]

下面是这个网站:http://mark-kay.net/2013/12/24/kernel-density-estimation/我想计算带宽的最佳值,所以我写了这段代码:

from sklearn.grid_search import GridSearchCV
grid = GridSearchCV(KernelDensity(),{'bandwidth': np.linspace(-1.0, 1.0, 30)},cv=20) # 20-fold cross-validation
grid.fit(x[:, None])
grid.best_params_

但当我运行这个:

grid.fit(x[:, None])

我得到这个错误:

Error: TypeError: list indices must be integers, not tuple

有人知道怎么修吗?谢谢


Tags: 函数代码nonehttpnet网站densitykernel
2条回答

您正在使用python list,其中应该使用numpy.array。后者支持更丰富的indexing

import numpy as np
x = np.array([-0.04124324405924407, 0, 0.005249724476788287, 0.03599351958245578, -0.00252785423151014, 0.01007584102031178, -0.002510349639322063, -0.01264302961474806, -0.01797169063489579])

鉴于样本量较小,我将使用OpenTURNSKernelSmoothing类。默认情况下,它提供Scott的多维规则。如果需要,我们可以使用Sheapler和Jones的直接插件算法,它在许多情况下提供了良好的带宽,即使分布是多模式的

以下脚本使用默认带宽

x = [
    -0.04124324405924407,
    0,
    0.005249724476788287,
    0.03599351958245578,
    -0.00252785423151014,
    0.01007584102031178,
    -0.002510349639322063,
    -0.01264302961474806,
    -0.01797169063489579,
]
import openturns as ot
sample = ot.Sample(x, 1)
factory = ot.KernelSmoothing()
distribution = factory.build(sample)

就这样

如果要使用更智能的带宽选择,我们可以使用computePluginBandwidth方法,该方法基于Sheapler和Jones的直接“求解方程”规则。在下面的脚本中,我在评估带宽后绘制了分布图

bandwidth = factory.computePluginBandwidth(sample)
distribution = factory.build(sample, bandwidth)
distribution.drawPDF()

带宽评估为0.00941247。PDF格式如下

PDF estimated from KernelSmoothing

相关问题 更多 >