简体   繁体   English

Plot PCA 和 LDA 中的凸包 plot - Python

[英]Plot the convex hull in PCA and LDA plot - Python

In the code below there is an example of an Principal Components Analysis (PCA) and Linear discriminant analysis (LDA) plots based on the Iris dataset.在下面的代码中,有一个基于 Iris 数据集的主成分分析 (PCA) 和线性判别分析 (LDA) 图的示例。 How can I add to each group its convex hull?如何将其凸包添加到每个组?

Code:代码:

import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

iris = datasets.load_iris()

X = iris.data
y = iris.target
target_names = iris.target_names

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2

for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of IRIS dataset')

plt.figure()
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of IRIS dataset')

plt.show() 

Using SciPy you can plot the convex hull of points quite easily.使用 SciPy 你可以很容易地 plot 点的凸包

hull = ConvexHull(X_r)
for simplex in hull.simplices:
    plt.plot(X_r[simplex, 0], X_r[simplex, 1], 'k-')

If you want to do this for each group individually, you can modify the code and change X_r to the respective subset containing your desired points.如果您想单独为每个组执行此操作,您可以修改代码并将 X_r 更改为包含所需点的相应子集。 This would be the following for your snippet:这将是您的代码段的以下内容:

for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)

    hull = ConvexHull(X_r[y == i])
    for simplex in hull.simplices:
        plt.plot(X_r[y==i][simplex, 0], X_r[y==i][simplex, 1], 'k-')

For your first plot this would give the following result:对于您的第一个 plot 这将给出以下结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM