什么是聚类?聚类的分类和例子
时间: 2024-02-26 19:36:35 浏览: 29
聚类是一种无监督学习的算法,其目标是将样本分成若干个群组,让同一组中的样本彼此相似,不同组之间的样本尽可能不同。常见的聚类算法包括K-means、DBSCAN、层次聚类等。例如,如果我们要对一个公司的客户进行聚类,可以根据他们的购买行为、地理位置、社交网络等因素将其分为不同的群组,以便于针对不同群组制定不同的营销策略。
相关问题
k-means聚类例子
假设我们有以下数据集:
```
X = [[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]]
```
我们想要将这些数据分为两个簇。以下是使用k-means聚类算法的Python代码:
```python
from sklearn.cluster import KMeans
# 定义聚类数为2
kmeans = KMeans(n_clusters=2)
# 将数据拟合到模型中
kmeans.fit(X)
# 获取聚类结果
labels = kmeans.labels_
print(labels)
```
输出:
```
[1 1 1 0 0 0]
```
可以看到,k-means算法将数据集分成了两个簇,标签为0和1。我们还可以通过以下代码获取簇的中心:
```python
centers = kmeans.cluster_centers_
print(centers)
```
输出:
```
[[4. 2. ]
[1. 2. ]]
```
其中,第一个簇的中心为[4, 2],第二个簇的中心为[1, 2]。
kmeans聚类算法matlab例子
以下是一个基于MATLAB的K-means聚类算法的例子:
```matlab
data = [1 1; 2 1; 1 2; 2 2; 4 4; 5 4; 4 5; 5 5]; % 数据集
cluster_num = 2; % 聚类数量
[m, n] = size(data);
cluster = data(randperm(m, cluster_num), :); % 随机选择聚类中心
epoch_max = 1000; % 最大迭代次数
therad_lim = 0.001; % 中心变化阈值
epoch_num = 0;
while(epoch_num < epoch_max)
epoch_num = epoch_num + 1;
% 计算每个点到各聚类中心的欧氏距离
distance1 = sqrt(sum((data - reshape(cluster, 1, cluster_num, n)).^2, 3));
[~, index_cluster] = min(distance1, [], 2); % 分配到最近的聚类中心
% 计算新的聚类中心
for j = 1:cluster_num
cluster_new(j, :) = mean(data(index_cluster == j, :));
end
% 如果新的聚类中心和上一轮的聚类中心之间的距离和大于阈值,则更新聚类中心;否则算法结束
if (sqrt(sum((cluster_new - cluster).^2)) > therad_lim)
cluster = cluster_new;
else
break;
end
end
% 输出结果
index_cluster
cluster
```