使用python實(shí)現(xiàn)3D聚類圖示例代碼
實(shí)驗(yàn)記錄,在做XX得分預(yù)測(cè)的實(shí)驗(yàn)中,做了一個(gè)基于Python的3D聚類圖,水平有限,僅供參考。
一、以實(shí)現(xiàn)三個(gè)類別聚類為例
代碼:
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
# 讀取數(shù)據(jù)
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)
# 數(shù)據(jù)標(biāo)準(zhǔn)化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_imputed)
# 應(yīng)用PCA降維到3維
pca = PCA(n_components=3)
X_pca = pca.fit_transform(X_scaled)
# 執(zhí)行K-means聚類
# 假設(shè)我們想要3個(gè)聚類
kmeans = KMeans(n_clusters=9, random_state=0).fit(X_pca)
labels = kmeans.labels_
# 將聚類標(biāo)簽添加到原始DataFrame中
data['Cluster'] = labels
# 3D可視化聚類結(jié)果
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()
# 打印每個(gè)聚類的名稱和對(duì)應(yīng)的數(shù)據(jù)點(diǎn)數(shù)量
cluster_centers = kmeans.cluster_centers_
for i in range(3):
cluster_data = data[data['Cluster'] == i]
print(f"Cluster {i}: Count: {len(cluster_data)}")
# 評(píng)估聚類效果
from sklearn import metrics
print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X_pca, labels))實(shí)現(xiàn)效果:

二、實(shí)現(xiàn)3個(gè)聚類以上,以9個(gè)類別聚類為例
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
# 讀取數(shù)據(jù)
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)
# 數(shù)據(jù)標(biāo)準(zhǔn)化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_imputed)
# 應(yīng)用PCA降維到3維
pca = PCA(n_components=3)
X_pca = pca.fit_transform(X_scaled)
# 執(zhí)行K-means聚類
# 假設(shè)我們想要9個(gè)聚類
kmeans = KMeans(n_clusters=9, random_state=0).fit(X_pca)
labels = kmeans.labels_
# 將聚類標(biāo)簽添加到原始DataFrame中
data['Cluster'] = labels
# 3D可視化聚類結(jié)果
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()
# 打印每個(gè)聚類的名稱和對(duì)應(yīng)的數(shù)據(jù)點(diǎn)數(shù)量
cluster_centers = kmeans.cluster_centers_
for i in range(9):
cluster_data = data[data['Cluster'] == i]
print(f"Cluster {i}: Count: {len(cluster_data)}")
# 評(píng)估聚類效果
from sklearn import metrics
print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X_pca, labels))實(shí)現(xiàn)效果;

到此這篇關(guān)于使用python實(shí)現(xiàn)3D聚類圖的文章就介紹到這了,更多相關(guān)python 3D聚類圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python使用樹(shù)狀圖實(shí)現(xiàn)可視化聚類詳解
- Python基于紋理背景和聚類算法實(shí)現(xiàn)圖像分割詳解
- python 層次聚類算法圖文示例
- Python K-means實(shí)現(xiàn)簡(jiǎn)單圖像聚類的示例代碼
- Python使用OpenCV和K-Means聚類對(duì)畢業(yè)照進(jìn)行圖像分割
- Python實(shí)現(xiàn)K-means聚類算法并可視化生成動(dòng)圖步驟詳解
- 在Python中使用K-Means聚類和PCA主成分分析進(jìn)行圖像壓縮
- python基于K-means聚類算法的圖像分割
- python聚類算法解決方案(rest接口/mpp數(shù)據(jù)庫(kù)/json數(shù)據(jù)/下載圖片及數(shù)據(jù))
相關(guān)文章
django 實(shí)現(xiàn)編寫控制登錄和訪問(wèn)權(quán)限控制的中間件方法
今天小編就為大家分享一篇django 實(shí)現(xiàn)編寫控制登錄和訪問(wèn)權(quán)限控制的中間件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
python操作注冊(cè)表的方法實(shí)現(xiàn)
Python提供了winreg模塊,可以用于操作Windows注冊(cè)表,本文就來(lái)介紹一下python操作注冊(cè)表的方法實(shí)現(xiàn),主要包括打開(kāi)注冊(cè)表、讀取注冊(cè)表值、寫入注冊(cè)表值和關(guān)閉注冊(cè)表,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
如何使用python的pillow庫(kù)生成圖像驗(yàn)證碼
Pillow庫(kù)是一個(gè)強(qiáng)大的Python圖像處理庫(kù),用于生成圖像驗(yàn)證碼,通過(guò)初始化圖像大小、驗(yàn)證碼字符長(zhǎng)度和字體大小,生成隨機(jī)字符串、顏色、線和點(diǎn),最終生成驗(yàn)證碼圖像2025-01-01
Python中pyserial 實(shí)現(xiàn)模擬串口通信的示例詳解
Python通過(guò)?pyserial?庫(kù)提供了強(qiáng)大的串口通信支持,使得開(kāi)發(fā)者能夠快速實(shí)現(xiàn)串口數(shù)據(jù)的發(fā)送與接收,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-06-06
Python二叉搜索樹(shù)與雙向鏈表轉(zhuǎn)換實(shí)現(xiàn)方法
這篇文章主要介紹了Python二叉搜索樹(shù)與雙向鏈表轉(zhuǎn)換實(shí)現(xiàn)方法,涉及Python二叉搜索樹(shù)的定義、實(shí)現(xiàn)以及雙向鏈表的轉(zhuǎn)換技巧,需要的朋友可以參考下2016-04-04
Django用戶認(rèn)證系統(tǒng)如何實(shí)現(xiàn)自定義
這篇文章主要介紹了Django用戶認(rèn)證系統(tǒng)如何實(shí)現(xiàn)自定義,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11

