首页 > 解决方案 > 获取 KDE 的稀疏区域

问题描述

我有一个 20k 实数数组,我用它pd.DataFrame(scores).plot.kde(figsize=(24,8))来获得以下内核密度估计。如何纯粹以编程方式选择稀疏区域的索引,或者相反地选择密集区域的索引?

我目前的方法是这种形式np.where(scores > np.percentile(scores, 99))[0],我非常喜欢这种方式,99因为它在生产中可能效果不佳。我不确定如何解决的一个潜在解决方案是选择密度低于 20,000 的指数

图片

标签: pythondataframescipykernel-densityanomaly-detection

解决方案


考虑哪个区域“稀疏”和哪个“密集”可能是非常主观的。它还很大程度上取决于数据的含义。一个想法是决定一些截止百分位数。下面的示例使用最低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()

示例图


推荐阅读