三维k-means聚类分析python
时间: 2025-04-27 13:33:52 浏览: 22
### 如何在 Python 中实现三维数据的 K-Means 聚类分析
#### 准备工作
为了处理三维数据,可以使用 `numpy` 来创建或导入三维的数据集。对于可视化部分,则依赖于 `matplotlib` 的三维绘图功能。
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 导入用于绘制3维图形的支持包[^2]
# 创建示例三维数据
np.random.seed(42) # 设置随机种子以获得可重复的结果
X = np.vstack([
(np.random.randn(100, 3) * 0.75 + [-2, -2, -2]),
(np.random.randn(100, 3) * 0.5 + [2, 2, 2])
]) # 合并两个不同分布的数据点形成混合体
```
#### 执行 K-Means 聚类
利用 `scikit-learn` 提供的功能来执行聚类操作:
```python
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
print("Cluster labels:", labels)
print("Centroids:\n", centroids)
```
#### 可视化结果
通过三维散点图展示原始数据及其对应的分类情况:
```python
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
colors = ['r', 'g']
for i in range(len(colors)):
xs = X[labels == i][:, 0]
ys = X[labels == i][:, 1]
zs = X[labels == i][:, 2]
ax.scatter(xs, ys, zs, c=colors[i], marker='o')
# 绘制质心位置
ax.scatter(
centroids[:, 0],
centroids[:, 1],
centroids[:, 2],
s=250,
alpha=0.75,
color="yellow",
label="Centroids"
)
plt.title('K Means Clustering on 3-D Data')
ax.set_xlabel('X Label ')
ax.set_ylabel('Y Label ')
ax.set_zlabel('Z Label ')
plt.legend()
plt.show()
```
此段代码展示了如何准备三维数据、应用 K-Means 算法进行聚类,并最终将这些信息直观地呈现出来[^3]。
阅读全文
相关推荐



















