1

scipy.stats.gaussian_kde上的文档说该关键字bw_method应该用于尝试不同的方法,但是当我尝试使用它时出现错误:

TypeError: __init__() got an unexpected keyword argument 'bw_method'

我正在运行的版本0.9.0Scipy这里是MWE

import numpy as np
from scipy import stats
import scipy

print scipy.__version__

## Generate some random two-dimensional data:
def measure(n):
    m1 = np.random.normal(size=n)
    m2 = np.random.normal(scale=0.5, size=n)
    return m1+m2, m1-m2

m1, m2 = measure(2000)
xmin = m1.min()
xmax = m1.max()
ymin = m2.min()
ymax = m2.max()

# Perform a kernel density estimate on the data:
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([x.ravel(), y.ravel()])
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values, bw_method='silverman')
4

2 回答 2

1

我没有测试结果,但从文档看来,有一个名为 silverman_factor(self) 的方法:

import numpy as np
from scipy import stats
import scipy

print scipy.__version__

## Generate some random two-dimensional data:
def measure(n):
    m1 = np.random.normal(size=n)
    m2 = np.random.normal(scale=0.5, size=n)
    return m1+m2, m1-m2

m1, m2 = measure(2000)
xmin = m1.min()
xmax = m1.max()
ymin = m2.min()
ymax = m2.max()

# Perform a kernel density estimate on the data:
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([x.ravel(), y.ravel()])
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values)
kernel.silverman_factor()
于 2013-07-29T13:11:40.407 回答
1

这是没有bw_method关键字的 scipy 版本(0.12.0 之前?)的解决方法:

density = kde.gaussian_kde(data)
density.covariance_factor = density.silverman_factor
density._compute_covariance()

这种变通方法的灵感来自于查看源代码


这表明上述解决方法产生与以下相同的结果kde.gaussian_kde(data, bw_method='silverman')

import numpy as np
import scipy.stats as stats

data = ([1.5] * 7 + [2.5] * 2 + [3.5] * 8
        + [4.5] * 3 + [5.5] * 1 + [6.5] * 8)
x = np.linspace(0., 8, 100)

density = stats.gaussian_kde(data)
density.covariance_factor = density.silverman_factor
density._compute_covariance()
workaround = density(x)

density = stats.gaussian_kde(data, bw_method='silverman')
answer = density(x)

assert np.allclose(workaround, answer)

bw_method关键字是在 0.9.0 版之后的某个时间添加的:

>>> import scipy
>>> scipy.__version__
'0.9.0'
>>> import scipy.stats.kde as kde
>>> density = kde.gaussian_kde(data, bw_method='silverman')
TypeError: __init__() got an unexpected keyword argument 'bw_method'
于 2013-07-29T13:12:30.663 回答