我正在使用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();
我试过的-如果椭圆ecos和椭圆esin包含定义椭圆的所有点,那么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()
谢谢你的帮助
pca库可以使用,因为它使用Hotelling T2和SPE/DmodX方法提供异常值检测
这里演示了一个示例:https://stackoverflow.com/a/63043840/13730780。 如果只需要异常值检测,可以使用特定功能,例如:
相关问题 更多 >
编程相关推荐