【问题标题】:Python PCA Plot (Parametric Ellipse) - Identify and Label OutliersPython PCA 图(参数椭圆) - 识别和标记异常值
【发布时间】:2020-08-18 17:44:44
【问题描述】:

我正在使用 sklearn 库对一些数据进行 PCA 分析。然后,我正在绘制我的 PC1 和 PC2 分数的散点图,并使用此链接上的答案作为我的参考 PCA Hotelling's 95% Python 在同一图上添加 95% 置信椭圆,然后我使用 pyplot 绘制它,如下所示: PCA plot with confidence ellipse output

正如您所见,代码可以正常工作并按预期绘制我的数据,因为标签重叠很多。我想只标记我的异常值(两个参数方程定义的椭圆外的点),因为这些是我真正感兴趣的唯一点。

有什么方法可以先识别我的异常值,然后只标记它们?

下面是我的代码示例(继承自上面的链接):

label_buff = pca_raw.iloc[:,2]
labels = label_buff.tolist()

#Calculate ellipse bounds and plot with scores
theta = np.concatenate((np.linspace(-np.pi, np.pi, 50), np.linspace(np.pi, -np.pi, 50)))
circle = np.array((np.cos(theta), np.sin(theta)))
#Where c and d are PC1 and PC2 training score subset for constructing ellipse
sigma = np.cov(np.array((c, d)))
ed = np.sqrt(scipy.stats.chi2.ppf(0.95, 2))
ell = np.transpose(circle).dot(np.linalg.cholesky(sigma) * ed)
c, d = np.max(ell[: ,0]), np.max(ell[: ,1]) #95% ellipse bounds
t = np.linspace(0, 2 * np.pi, 100)
ellipsecos = c * np.cos(t)
ellipsesin = d * np.sin(t) 
# a and b are my PC1 and PC2 raw data scores
plt.scatter(a, b, color = "orange")
for i, txt in enumerate(labels):
    plt.annotate(txt, (a[i], b[i]), textcoords ='offset points', ha='right', va='bottom' )
plt.plot(ellipsecos, ellipsesin, color = 'black');
plt.show();

我尝试了什么 - 如果 ellipsecos 和 ellipsesin 包含定义椭圆的所有点,那么 a 和 b 必须大于那些点才能位于椭圆之外,但我没有得到预期的结果(所以我认为我没有能够正确建立异常值条件)。我更熟悉笛卡尔系统(有可能评估椭圆方程以检查点是在椭圆内还是在椭圆外)如果有人可能帮助我使用两个参数方程建立异常值条件,将不胜感激。:

    #where a and b are PC1 and PC2 scores calculated using sklearn library
for a, b in zip(a, b):
    color = 'red'  # non-outlier color
    if (a > ellipsecos.all()  & (b > ellipsesin.all()) ):  # condition for being an outlier
        color = 'orange'  # outlier color
    plt.scatter(a, b, color=color)
plt.show()

将不胜感激。

【问题讨论】:

    标签: python pca ellipse


    【解决方案1】:

    pca 库可能很有用,因为它使用 Hotelling T2 和 SPE/DmodX 方法提供异常值检测。

    此处演示了一个示例:https://stackoverflow.com/a/63043840/13730780。 如果您只想检测异常值,可以使用特定功能,例如:

    import pca
    outliers_hot = pca.hotellingsT2(PCs, alpha=0.05)
    outliers_spe = pca.spe_dmodx(PCs, n_std=2)
    

    【讨论】:

    • 埃尔多甘特,非常感谢!我跟进了链接,这是一个非常详细的答案!干杯。
    • 太棒了!玩得开心!
    猜你喜欢
    • 2013-11-10
    • 2019-06-08
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多