Python 中的凸包

在本教程中,我们将在凸包的帮助下逐步实现不同且独特的聚类方法。但在直接进入代码之前理解这个概念总是很重要的!那么让我们了解一下什么是凸包。


凸包简介

Convex object 是内角不大于 180 度的物体。Hull 表示物体形状的外部。convex hull 包含一组点,它充当簇边界,有助于确定簇内的所有点。这是牛凸包的简单现实生活插图。您可以看到外面的船体将整头牛包围在船体内部。

凸包演示

凸包的代码实现

我们将首先在 sci-kit learn 库的帮助下创建本教程的示例数据集。我们将使用该 make_blobs 功能。我们将为 5 个不同的集群创建数据。看下面的代码。

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
from sklearn.datasets import make_blobs
 
# center points for the clusters
centers = [[0, 1, 0], [1.5, 1.5, 1], [1, 1, 1],[1,1,3],[2,2,2]]
# standard deviations for the clusters
stds = [0.13, 0.12, 0.12,0.15,0.14]
 
# create dataset using make_blobs - assign centers, standard deviation and the number of points
X, labels_true = make_blobs(n_samples=1000, centers=centers, cluster_std=stds, random_state=0)
point_indices = np.arange(1000)

总的来说,我们生成了 1000 分配给 five 不同集群的数据点。接下来,我们将尝试可视化数据。由于我们的数据集是 3 维形式,因此我们将为数据绘制 3D 图。请观察下面的代码。我们将绘制所有数据点,并为绘图指定颜色以表示聚类。看看剧情有多精彩!

另请阅读:使用 Matplotlib 在 Python 中绘制 3 维绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 号
import matplotlib.pyplot as plt
plt.style.use('seaborn')
 
x,y,z = X[:,0],X[:,1],X[:,2]
 
fig = plt.figure(figsize = (20,10),facecolor="w")
ax = plt.axes(projection="3d")
 
list_colours = ["red", "green", "blue","magenta","brown"]
cluster_colors = [list_colours[i] for i in labels_true]
 
scatter_plot = ax.scatter3D(x,y,z,c =cluster_colors,marker ='o')
plt.title("Scatter plot of the dataset",fontsize=30)
ax.set_xlabel('X_values', fontweight ='bold'
ax.set_ylabel('Y_values', fontweight ='bold')
 
plt.show()
绘制数据集 ConvexHull

我们将从  模块 导入ConvexHull 和 凸包绘图函数 我们将为生成的数据集分配凸包点。spatialscipy

1
2
3
from scipy.spatial import ConvexHull, convex_hull_plot_2d
rng = np.random.default_rng()
hull = ConvexHull(X)

让我们使用下面的代码可视化空间中的凸包。我们将使用 simplices 创建的外壳对象的函数来绘制凸包的边界。

1
2
3
4
fig = plt.figure(figsize = (20,10),facecolor="w")
ax = plt.axes(projection="3d")
for simplex in hull.simplices:
    ax.plot3D(X[simplex, 0], X[simplex, 1],X[simplex, 2], 's-')
绘制凸包 1

看看凸包在 3D 空间中看起来有多神奇。

为了让事情变得更有趣,让我们使用下面提到的代码将集群和船体绘制在一个图中。

1
2
3
4
5
fig = plt.figure(figsize = (20,10),facecolor="w")
ax = plt.axes(projection="3d")
scatter_plot = ax.scatter3D(x,y,z,c =cluster_colors,marker ='o')
for simplex in hull.simplices:
    ax.plot3D(X[simplex, 0], X[simplex, 1],X[simplex, 2], 's-')
绘制凸包 2

看起来棒极了对吧?!


结论

恭喜!现在您知道如何为您的绘图绘制这些令人惊叹的凸包边界。我希望您喜欢本教程并发现它内容丰富且有趣!如果您喜欢本教程,我会向您推荐以下教程:

  1. Python:检测轮廓
  2. 使用 Python 进行图像边缘检测
  3. Python 中的图像处理 – 边缘检测、调整大小、腐蚀和膨胀

快乐的编码和绘图!😃