kmeans聚类算法matlab python
时间: 2023-08-31 17:05:20 浏览: 95
K-means聚类算法在Matlab和Python中都有实现,以下是两种语言的示例代码:
Matlab代码:
```matlab
% 加载数据
load fisheriris
% 设置聚类数目
k = 3;
% 运行k-means算法
[idx, C] = kmeans(meas, k);
% 绘制聚类结果
figure
gscatter(meas(:,1), meas(:,2), idx)
hold on
plot(C(:,1), C(:,2), 'kx', 'MarkerSize', 15, 'LineWidth', 3)
legend({'Cluster 1', 'Cluster 2', 'Cluster 3', 'Centroids'}, 'Location', 'NW')
title 'Fisher''s Iris Data'
hold off
```
Python代码:
```python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
# 加载数据
iris = load_iris()
X = iris.data
# 设置聚类数目
k = 3
# 运行k-means算法
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)
labels = kmeans.predict(X)
centroids = kmeans.cluster_centers_
# 绘制聚类结果
plt.scatter(X[:,0], X[:,1], c=labels)
plt.scatter(centroids[:,0], centroids[:,1], marker='x', s=150, linewidths=3, color='r')
plt.title('Iris Data')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
```
两种语言的代码基本相似,都需要加载数据、设置聚类数目、运行k-means算法,并绘制聚类结果。Matlab和Python都提供了方便的工具箱和库来实现k-means聚类算法。
阅读全文