将KDE与来自scipy.Integrate.quad的奇怪行为和设置的带宽进行集成 [英] Integration of KDE with strange behavior of from scipy.integrate.quad and the setted bandwith

查看:0
本文介绍了将KDE与来自scipy.Integrate.quad的奇怪行为和设置的带宽进行集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来从绘制的分布中获得平均值(期望值),我使用该分布来拟合scipy.stats.Gauss_kde的核密度估计。我记得在我的统计课程中,期望值就是pdf(X)*x从-无穷大到无穷大的积分:

我在代码中使用了scipy.Integrate.quad函数来执行此任务,但我遇到了这种明显奇怪的行为(这可能与KDE中的band with参数有关)。

问题

import matplotlib.pyplot as plt
import numpy as np
import random
from scipy.stats import norm, gaussian_kde
from scipy.integrate import quad
from sklearn.neighbors import KernelDensity

np.random.seed(42)

# Generating sample data
test_array = np.concatenate([np.random.normal(loc=-10, scale=.8, size=100),
np.random.normal(loc=4,scale=2.0,size=500)])


kde = gaussian_kde(test_array,bw_method=0.5)


X_range = np.arange(-16,20,0.1)

y_list = []

for X in X_range:

    pdf = lambda x : kde.evaluate([[x]])
    y_list.append(pdf(X))

y = np.array(y_list)    

_ = plt.plot(X_range,y)


# Integrate over pdf * x to obtain the mean
mean_integration_low_bw = quad(lambda x: x * pdf(x), a=-np.inf, b=np.inf)[0]

# Calculate the cdf at point of the mean
zero_int_low = quad(lambda x: pdf(x), a=-np.inf, b=mean_integration_low_bw)[0]

print("The mean after integration: {}
".format(round(mean_integration_low_bw,4)))

print("F({}): {}".format(round(mean_integration_low_bw,4),round(zero_int_low,4)))

plt.axvline(x=mean_integration_low_bw,color ="r")
plt.show()

如果我执行此代码,我会得到积分平均值和计算平均值点处的累积分布函数的结果的奇怪行为:

第一个问题: 在我看来,它应该总是显示:F(均值)=0.5,或者我错了?(这是否仅适用于对称分布?)

第二个问题: 更奇怪的是,对于带宽参数,积分平均值的值不变。在我看来,如果基础分布的形状不同,平均值也应该改变。如果我将带宽设置为5,我会得到以下图表:

如果曲线现在具有不同的形状(由于带宽较宽),为什么平均值仍然相同?

我希望这些问题不仅仅是因为我对统计的理解有缺陷;)

推荐答案

您的初始数据在此处生成

# Generating sample data
test_array = np.concatenate([np.random.normal(loc=-10, scale=.8, size=100),
                             np.random.normal(loc=4,scale=2.0,size=500)])

因此,您有500样本来自平均值4分布,100样本来自平均值-10分布,您可以预测预期平均值(500*4-10*100)/(500+100) = 1.66666...。这与您的代码给出的结果非常接近,也与使用第一个绘图获得的结果非常一致。

这篇关于将KDE与来自scipy.Integrate.quad的奇怪行为和设置的带宽进行集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆