![](/img/trans.png)
[英]Python's scipy.integrate.quad with complex integration bounds
[英]Integration of KDE with strange behavior of from scipy.integrate.quad and the setted bandwith
我正在尋找一種從繪制分布中獲取平均值(期望值)的方法,該分布用於擬合來自scipy.stats.gaussian_kde的 Kernel 密度估計。 我記得從我的統計數據 class 中,期望值只是 pdf(x) * x 從 -infinity 到無窮大的積分:
我使用scipy.integrate.quad function 在我的代碼中執行此任務,但我遇到了這種明顯奇怪的行為(這可能與 KDE 中的帶寬參數有關)。
問題
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: {}\n".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()
如果我執行此代碼,我會在計算的平均值處得到積分平均值和累積分布 function 的結果的奇怪行為:
第一個問題:在我看來,它應該總是顯示:F(Mean) = 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)])
因此,您有來自平均值為4
的分布的500
樣本和來自平均值為-10
的分布的100
樣本,您可以預測預期平均值(500*4-10*100)/(500+100) = 1.66666...
。 這與您的代碼給出的結果非常接近,並且與從第一個 plot 獲得的結果也非常一致。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.