gpt4 book ai didi

python - 使用观察权重绘制密度

转载 作者:行者123 更新时间:2023-11-28 16:35:32 24 4
gpt4 key购买 nike

有没有一种方法可以使用具有观察权重的数据来绘制密度图?

我有一个观察值向量 x 和一个整数权重向量 y,这样 y1 表示我们有多少观察值 x1。即,密度

   x    y 
1 2
2 2
2 3

等于 1, 1, 2, 2, 2, 2 ,2 (2x1, 5x2) 的密度。据我了解,matplotlib.pyplot.hist(weights=y) 在绘制直方图时允许观察权重。是否有计算和绘制密度的等价物?

我希望这个包能够做到这一点的原因是我的数据非常大,我正在寻找更高效的替代方案。

或者,我对其他软件包持开放态度。

最佳答案

Statsmodels 的 kde 单变量在其 fit function 中接收权重.请参阅以下代码的输出。

import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd

df = pd.DataFrame({'x':[1.,2.],'weight':[2,4]})
weighted = sm.nonparametric.KDEUnivariate(df.x)
noweight = sm.nonparametric.KDEUnivariate(df.x)
weighted.fit(fft=False, weights=df.weight)
noweight.fit()

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(noweight.support, noweight.density)
ax2.plot(weighted.support, weighted.density)

ax1.set_title('No Weight')
ax2.set_title('Weighted')

输出: No Weight vs Weighted Densities

注意:关于数组创建的时间问题可能不会因此而得到解决。因为如 source code 中所述:

If FFT is False, then a ‘number_of_obs’ x ‘gridsize’ intermediate array is created

关于python - 使用观察权重绘制密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897813/

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