【问题标题】:Plot density using observation weights使用观察权重绘制密度
【发布时间】:2015-01-09 22:40:54
【问题描述】:

有没有办法使用具有观察权重的数据来绘制密度?

我有一个观察向量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) 在绘制直方图时允许观察权重。是否有任何等效的计算和绘制密度?

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

另外,我对其他软件包持开放态度。

【问题讨论】:

  • 您只需要根据观测结果生成密度吗?
  • 对不起,我想在stackoverflow.com/questions/4150171/…中绘制密度
  • 据我了解,您只需要创建一个称为histogram 的列表并将其发送到建议的包之一。您是从观察中创建该列表有困难,还是您有一个列表并且您在使用包时遇到问题?还是两者兼而有之?
  • 我说我知道允许使用观察权重绘制直方图的函数。另一方面,我不知道允许使用这些权重绘制密度的函数。鉴于密度在某种程度上是直方图的极限情况,因此我进行了比较。我不知道能够使用直方图绘制密度。
  • 啊,现在我明白了……!抱歉,帮不了你太多:)

标签: python matplotlib scikits


【解决方案1】:

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')

输出:

注意:您对创建数组的时间问题可能无法解决。因为正如source code 中所述:

如果 FFT 为 False,则为 ‘number_of_obs’ x ‘gridsize’ 中间值 创建数组

【讨论】:

  • 使用 ax1.plot(noweight.support, noweight.density) 获得正确的 x 轴值。另外,请注意,权重必须是一个 numpy 数组(或 pandas 中的一列),否则您将看到代码抱怨它无法做到weights.sum()
猜你喜欢
  • 2016-12-10
  • 2019-11-06
  • 2016-09-29
  • 2023-04-02
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
相关资源
最近更新 更多