1. 层次聚类
分离的层次聚类:分裂,求相似性,相似性达到了,停止,没有达到则继续分裂…
样本中有层次的包含关系(如省,市,县)适合用层次聚类,如果用层次聚类,人们一般用凝聚的层次聚类
如上图,d,e被聚在一个县里(de),c也是一个县,这两个县被聚在一个市(cde),而a,b这两个县被聚在另一个市(ab),这两个市又被聚在一个省里(abcde)
2. 密度聚类
像上图中有形状的样本用k-Means就不太好,k-Means是会画一个圈进行聚类
而密度聚类,把挨得密的聚在一起
2.1 密度聚类的计算方法
密度聚类典型的算法是DBSCAN:
上图中,阈值为5的意思就是圈内有5个点
q内有7个点,p内有3个,所以q就是核心对象
所以阈值是用来确定核心对象的,只有核心对象才有资格取圈别的点
如果不是核心对象,那么它的圈就不是了,
总结:密度聚类就是有几个核心对象(圈),根据密度可达规则去圈别的点,直到最后没有更多点加进来,则扫描结束。核心对象圈出来的点就是和核心对象是一个类别的,没有被密度可达的点并且也不是核心对象的话,这个点就是噪声点了。
所以密度聚类可能会使有些点没有类别
2.2 代码实现DBSCAN
# !/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as ds
import matplotlib.colors
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
def expand(a, b):
d = (b - a) * 0.1
return a-d, b+d
if __name__ == "__main__":
N = 1000
centers = [[1, 2], [-1, -1], [1, -1], [-1, 1]]
# 根据上面4个中心点生成100个样本, cluster_std是方差
data, y = ds.make_blobs(N, n_features=2, centers=centers, cluster_std=[0.5, 0.25, 0.7, 0.5], random_state=0)
# 标准归一化:先均值归一化后方差归一化
data = StandardScaler().fit_transform(data)
# 数据的参数:(epsilon, min_sample) 半径和阈值
params = ((0.2, 5), (0.2, 10), (0.2, 15), (0.3, 5), (0.3, 10), (0.3, 15))
matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(12, 8), facecolor='w')
plt.suptitle(u'DBSCAN聚类', fontsize=20)
# 对比6组超参数
for i in range(6):
eps, min_samples = params[i]
model = DBSCAN(eps=eps, min_samples=min_samples)
model.fit(data)
y_hat = model.labels_
core_indices = np.zeros_like(y_hat, dtype=bool)
core_indices[model.core_sample_indices_] = True
y_unique = np.unique(y_hat)
n_clusters = y_unique.size - (1 if -1 in y_hat else 0)
print(y_unique, '聚类簇的个数为:', n_clusters)
plt.subplot(2, 3, i+1)
clrs = plt.cm.Spectral(np.linspace(0, 0.8, y_unique.size))
print(clrs)
for k, clr in zip(y_unique, clrs):
cur = (y_hat == k)
if k == -1:
plt.scatter(data[cur, 0], data[cur, 1], s=20, c='k')
continue
plt.scatter(data[cur, 0], data[cur, 1], s=30, c=clr, edgecolors='k')
plt.scatter(data[cur & core_indices][:, 0], data[cur & core_indices][:, 1], s=60, c=clr, marker='o', edgecolors='k')
x1_min, x2_min = np.min(data, axis=0)
x1_max, x2_max = np.max(data, axis=0)
x1_min, x1_max = expand(x1_min, x1_max)
x2_min, x2_max = expand(x2_min, x2_max)
plt.xlim((x1_min, x1_max))
plt.ylim((x2_min, x2_max))
plt.grid(True)
plt.title(u'epsilon = %.1f m = %d,聚类数目:%d' % (eps, min_samples, n_clusters), fontsize=16)
plt.tight_layout()
plt.subplots_adjust(top=0.9)
plt.show()
运行结果:黑色点是噪声