gpt4 book ai didi

python - scipy.stats.gaussian_kde 中的关键字错误?

转载 作者:行者123 更新时间:2023-12-01 05:39:45 24 4
gpt4 key购买 nike

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

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

我正在运行 Scipy 版本 0.9.0,这是一个 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')

最佳答案

以下是针对没有 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)
<小时/>

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'

关于python - scipy.stats.gaussian_kde 中的关键字错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17924896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com