至少有 3 个可用于 python 的高质量内核密度估计实现:
我的个人排名是 statsmodels > scikit-learn > scipy(最好到最差),但这取决于您的用例。
一些随机评论:
- scikit-learn 免费提供来自已安装 KDE 的采样 (
kde.sample(N))
- scikit-learn 提供了良好的基于网格搜索或随机搜索的交叉验证功能(强烈推荐交叉验证)
- statsmodels 提供基于优化的交叉验证方法(对于大数据集可能会很慢;但准确度非常高)
还有更多差异,其中一些差异在 Jake VanderPlas 的这个非常好的 blog post 中进行了分析。下表摘自这篇文章:
来自:https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/(作者:Jake VanderPlas)
下面是一些使用 scikit-learn 的示例代码:
from sklearn.datasets import make_blobs
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import numpy as np
# Create test-data
data_x, data_y = make_blobs(n_samples=100, n_features=2, centers=7, cluster_std=0.5, random_state=0)
# Fit KDE (cross-validation used!)
params = {'bandwidth': np.logspace(-1, 2, 30)}
grid = GridSearchCV(KernelDensity(), params)
grid.fit(data_x)
kde = grid.best_estimator_
bandwidth = grid.best_params_['bandwidth']
# Resample
N_POINTS_RESAMPLE = 1000
resampled = kde.sample(N_POINTS_RESAMPLE)
# Plot original data vs. resampled
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(100):
axs[0,0].scatter(*data_x[i])
axs[0,1].hexbin(data_x[:, 0], data_x[:, 1], gridsize=20)
for i in range(N_POINTS_RESAMPLE):
axs[1,0].scatter(*resampled[i])
axs[1,1].hexbin(resampled[:, 0], resampled[:, 1], gridsize=20)
plt.show()
输出: