使用python实现3D聚类图示例代码

 更新时间:2024年08月20日 10:47:06   作者:兜里没有一毛钱  
这篇文章主要介绍了使用python实现3D聚类图效果,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

实验记录,在做XX得分预测的实验中,做了一个基于Python的3D聚类图,水平有限,仅供参考。

一、以实现三个类别聚类为例

代码:

import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 读取数据
data = pd.read_csv('E:\\shujuji\\Goods\\man.csv')
# 选择用于聚类的列
features = ['Weight', 'BMI', 'Lung Capacity Score', '50m Running Score',   
            'Standing Long Jump Score', 'Sitting Forward Bend Score',   
            '1000m Running Score', 'Pulling Up Score', 'Total Score']
X = data[features]
# 处理缺失值
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X)
# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_imputed)
# 应用PCA降维到3维
pca = PCA(n_components=3)
X_pca = pca.fit_transform(X_scaled)
# 执行K-means聚类
# 假设我们想要3个聚类
kmeans = KMeans(n_clusters=9, random_state=0).fit(X_pca)
labels = kmeans.labels_
# 将聚类标签添加到原始DataFrame中
data['Cluster'] = labels
# 3D可视化聚类结果
fig = plt.figure(1, figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
unique_labels = set(labels)
colors = ['r', 'g', 'b']
for k, c in zip(unique_labels, colors):
    class_member_mask = (labels == k)
    xy = X_pca[class_member_mask]
    ax.scatter(xy[:, 0], xy[:, 1], xy[:, 2], c=c, label=f'Cluster {k}')
ax.set_title('PCA of Fitness Data with K-means Clustering')
ax.set_xlabel('Principal Component 1')
ax.set_ylabel('Principal Component 2')
ax.set_zlabel('Principal Component 3')
plt.legend()
plt.show()
# 打印每个聚类的名称和对应的数据点数量
cluster_centers = kmeans.cluster_centers_
for i in range(3):
    cluster_data = data[data['Cluster'] == i]
    print(f"Cluster {i}: Count: {len(cluster_data)}")
# 评估聚类效果
from sklearn import metrics
print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X_pca, labels))

实现效果:

二、实现3个聚类以上,以9个类别聚类为例

import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 读取数据
data = pd.read_csv('E:\\shujuji\\Goods\\man.csv')
# 选择用于聚类的列
features = ['Weight', 'BMI', 'Lung Capacity Score', '50m Running Score',   
            'Standing Long Jump Score', 'Sitting Forward Bend Score',   
            '1000m Running Score', 'Pulling Up Score', 'Total Score']
X = data[features]
# 处理缺失值
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X)
# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_imputed)
# 应用PCA降维到3维
pca = PCA(n_components=3)
X_pca = pca.fit_transform(X_scaled)
# 执行K-means聚类
# 假设我们想要9个聚类
kmeans = KMeans(n_clusters=9, random_state=0).fit(X_pca)
labels = kmeans.labels_
# 将聚类标签添加到原始DataFrame中
data['Cluster'] = labels
# 3D可视化聚类结果
fig = plt.figure(1, figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
unique_labels = set(labels)
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'orange', 'purple']
for k, c in zip(unique_labels, colors):
    class_member_mask = (labels == k)
    xy = X_pca[class_member_mask]
    ax.scatter(xy[:, 0], xy[:, 1], xy[:, 2], c=c, label=f'Cluster {k}')
ax.set_title('PCA of Fitness Data with K-means Clustering')
ax.set_xlabel('Principal Component 1')
ax.set_ylabel('Principal Component 2')
ax.set_zlabel('Principal Component 3')
plt.legend()
plt.show()
# 打印每个聚类的名称和对应的数据点数量
cluster_centers = kmeans.cluster_centers_
for i in range(9):
    cluster_data = data[data['Cluster'] == i]
    print(f"Cluster {i}: Count: {len(cluster_data)}")
# 评估聚类效果
from sklearn import metrics
print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X_pca, labels))

实现效果;

到此这篇关于使用python实现3D聚类图的文章就介绍到这了,更多相关python 3D聚类图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • django 实现编写控制登录和访问权限控制的中间件方法

    django 实现编写控制登录和访问权限控制的中间件方法

    今天小编就为大家分享一篇django 实现编写控制登录和访问权限控制的中间件方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Pandas日期处理之生成工作日与节假日

    Pandas日期处理之生成工作日与节假日

    Python中的Pandas 提供了许多日期处理功能,使得处理时间序列数据变得容易。本文将介绍如何使用 Pandas 生成工作日和节假日,感兴趣的小伙伴可以收藏一下
    2023-05-05
  • python操作注册表的方法实现

    python操作注册表的方法实现

    Python提供了winreg模块,可以用于操作Windows注册表,本文就来介绍一下python操作注册表的方法实现,主要包括打开注册表、读取注册表值、写入注册表值和关闭注册表,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • Python安装图文教程 Pycharm安装教程

    Python安装图文教程 Pycharm安装教程

    这篇文章主要为大家详细介绍了Pycharm及Python安装图文教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • 一文详解Python中的subprocess模块

    一文详解Python中的subprocess模块

    subprocess模块是Python标准库的一部分,提供了一个跨平台的方法来生成新进程、连接其输入/输出/错误管道,并获取其返回码,本文小编将和大家一起深入理解Python中的subprocess模块,感兴趣的小伙伴跟着小编一起来看看吧
    2024-08-08
  • 如何使用python的pillow库生成图像验证码

    如何使用python的pillow库生成图像验证码

    Pillow库是一个强大的Python图像处理库,用于生成图像验证码,通过初始化图像大小、验证码字符长度和字体大小,生成随机字符串、颜色、线和点,最终生成验证码图像
    2025-01-01
  • Python NumPy随机抽模块介绍及方法

    Python NumPy随机抽模块介绍及方法

    这篇文章主要介绍了Python NumPy随机抽模块介绍及方法,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-09-09
  • Python中pyserial 实现模拟串口通信的示例详解

    Python中pyserial 实现模拟串口通信的示例详解

    Python通过 pyserial 库提供了强大的串口通信支持,使得开发者能够快速实现串口数据的发送与接收,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-06-06
  • Python二叉搜索树与双向链表转换实现方法

    Python二叉搜索树与双向链表转换实现方法

    这篇文章主要介绍了Python二叉搜索树与双向链表转换实现方法,涉及Python二叉搜索树的定义、实现以及双向链表的转换技巧,需要的朋友可以参考下
    2016-04-04
  • Django用户认证系统如何实现自定义

    Django用户认证系统如何实现自定义

    这篇文章主要介绍了Django用户认证系统如何实现自定义,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11

最新评论