在 PCA 和 LDA 图中绘制凸包 - Python

Plot the convex hull in PCA and LDA plot - Python

在下面的代码中有一个基于 Iris 数据集的主成分分析 (PCA) 和线性判别分析 (LDA) 图的示例。如何向每个组添加其凸包?

代码:

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() 

使用 SciPy 你可以很容易地绘制 convex hull of points

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

如果您想对每个组单独执行此操作,您可以修改代码并将 X_r 更改为包含所需点的相应子集。这将是您的代码段的以下内容:

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-')

对于您的第一个绘图,这将给出以下结果: