如何将1d kde与scipy整合并可视化?

pcrecxhr  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个一维数组,我已经用scipy.stats.gaussian_kde得到了pdf。现在我想计算每个特定数据点的积分,我的代码如下。这有意义吗?如果没有,正确的解决方案是什么?顺便问一下,我该如何可视化pdf和积分函数?谢谢

X=np.array([0.21,0.21,0.21,0.28,0.30,0.30,0.24,0.22,0.19,0.20,0.18,0.23,0.20,0.12,0.14,0.13,0.18,0.15,0.13,0.11,0.12,0.11,0.10,0.13,0.03,0.07,0.17,0.16])
kde=scipy.stats.gaussian_kde(X, bw_method=None, weights=None)
for x in X:
    print(kde.integrate_box_1d(-np.inf, x))
83qze16e

83qze16e1#

为了绘制kde,你需要创建一个x值的密集数组。给定点的积分可以通过散点图绘制。

from matplotlib import pyplot as plt
import  numpy as np
import scipy, scipy.stats

X = np.array([0.21,0.21,0.21,0.28,0.30,0.30,0.24,0.22,0.19,0.20,0.18,0.23,0.20,0.12,0.14,0.13,0.18,0.15,0.13,0.11,0.12,0.11,0.10,0.13,0.03,0.07,0.17,0.16])
kde = scipy.stats.gaussian_kde(X, bw_method=None, weights=None)
xmin = X.min()
xmax = X.max()
# create an array of x values for plotting
xs = np.linspace(xmin - (xmax - xmin) * 0.2, xmax + (xmax - xmin) * 0.2, 500)
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(12, 10), sharex=True)
ax1.plot(xs, kde(xs), color='dodgerblue')
ax1.set_ylim(ymin=0)
ax1.set_title('kde')
ax1.tick_params(axis='x', labelbottom=True)
for x in X:
     ax2.scatter(x, kde.integrate_box_1d(-np.inf, x), color='crimson')
ax2.set_ylim(ymin=0)
ax2.set_title('integral of kde at given X values')

plt.tight_layout()
plt.show()

相关问题