python - 如何修复 statsmodels.nonparametric.kde.kdensity 或 seaborn.kdeplot 中不正确的带宽?
问题描述
我正在将我的一些 R 文件翻译成 Python,并且在使用 Python 中的 Epanechnikov 内核设置 KDE 图中的带宽时遇到了一些问题。
我曾尝试使用函数 seaborn.kdeplot() 以及 statsmodels.nonparametric.kde.kdensity(),但从未得到正确的结果。
直到现在,我还没有找到 Python 中的带宽如何缩放或标准化的模式。此外,如果我使用高斯核,R 和 Python 的图是相同的。那么也许 Epanechnikov Kernel 的计算方式不同?
我使用以下代码在 Python 中创建 KDE 图:
import seaborn as sns
sns.kdeplot(y,kernel = 'epa', bw = 0.1)
和
from statsmodels.nonparametric.kde import kdensity
density = kdensity(y, kernel='epa', bw=0.1)
plt.plot(density[1],density[0], color = 'red')
两者的输出都不是很流畅:https ://user-images.githubusercontent.com/48911472/55010186-1382fc80-4fe4-11e9-999f-263ea9bf62c9.png
但是,它应该看起来像 R 中的输出(或 STATA 中的输出,因为它们是相同的),更平滑:
plot(density(y,bw=0.1, kernel ="epanechnikov"), col="red")
https://user-images.githubusercontent.com/48911472/55010088-e3d3f480-4fe3-11e9-8d84-ebd54c5b8bc9.png
解决方案
尝试在 sns.kdplot 上增加网格大小,默认值为 100,而我相信 R 的密度约为 512。希望它有所帮助