概念
核密度估計(Kernel Density Estimation,簡稱 KDE)是一種非參數統計方法,用于估計隨機變量的概率密度函數(Probability Density Function,PDF)。它通過在每個數據點周圍放置核函數(通常是一個正態分布),然后將這些核函數疊加起來來估計概率密度函數。核密度估計常用于數據分布的可視化和平滑。
代碼實現
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from sklearn.neighbors import KernelDensity# 生成一組模擬觀測數據
np.random.seed(42)
data = np.random.normal(5, 2, 100)# 創建一組測試點用于繪制估計的概率密度函數
x = np.linspace(min(data), max(data), 1000).reshape(-1, 1)# 使用scikit-learn的KernelDensity進行核密度估計
kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(data.reshape(-1, 1))
log_dens = kde.score_samples(x)# 繪制原始數據和估計的概率密度函數
plt.hist(data, bins=20, density=True, alpha=0.5, color='blue', label='Histogram')
plt.plot(x, np.exp(log_dens), color='red', label='Kernel Density Estimation')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend()
plt.title('Kernel Density Estimation')
plt.show()