scipy.stats.gaussian_kde上的文档说应该使用关键字bw_method
来尝试不同的方法,但是当我尝试使用它时,我收到错误:
TypeError: __init__() got an unexpected keyword argument 'bw_method'
我正在运行0.9.0
的{{1}}版本,这里是Scipy
:
MWE
答案 0 :(得分: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()
答案 1 :(得分:1)
以下是没有bw_method
关键字的scipy版本(在0.12.0之前?)的解决方法:
density = kde.gaussian_kde(data)
density.covariance_factor = density.silverman_factor
density._compute_covariance()
此解决方法的灵感来自looking at the source。
这表明上面的解决方法产生与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)
在版本0.9.0之后的某个时间添加了bw_method
关键字:
>>> 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'