获取 KDE 的稀疏区域

Get sparse region of KDE

我有一个 20k 实数数组,我使用 pd.DataFrame(scores).plot.kde(figsize=(24,8)) 得到下面的核密度估计。我怎样才能纯粹以编程方式 select 稀疏区域或密集区域的索引?

我目前的方法是 np.where(scores > np.percentile(scores, 99))[0] 的形式,我非常喜欢 99 这样的硬编码,因为它在生产中可能不太好用。我不确定如何处理的潜在解决方案是 selecting 密度低于 20,000

的指数

将哪个区域视为“稀疏”区域以及哪个区域“密集”可能是非常主观的。它还在很大程度上取决于数据的意义。一个想法是决定一些 cut-off 个百分位数。下面的示例使用最低的 0.1 % 和最高的 99.9 %.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({'score': np.random.randn(2000, 10).cumsum(axis=0).ravel()})
df['score'].quantile([.01, .99])
ax = df.plot.kde(figsize=(24, 8))
ax.axvline(df['score'].quantile(.001), color='crimson', ls=':')
ax.axvline(df['score'].quantile(.999), color='crimson', ls=':')
ax.set_ylim(ymin=0) # avoid the kde "floating in the air"
plt.show()