FKNN-DPC 【论文解读】Density peaks clustering based on fuzzy weighted K-nearest neighbors.2027.Information Science. - Call fit_transform (only needs to handle features)
FKNN-DPC 【论文解读】Density peaks clustering based on fuzzy weighted K-nearest neighbors.2016.Information Science.
Robust clustering by detecting density peaks and assigning points based on fuzzy weighted K-nearest neighbors
基于模糊加权K-近邻的密度峰值聚类(FKNN-DPC)
目录
一、引言二、算法思想1、基于 KNN 的密度核2、标签分配策略2.1 分配策略 1:基于 KNN 的标签分配2.2 分配策略 2:基于模糊加权 KNN 的标签分配
三、总结1、算法流程2、优缺点分析
四、代码实现(Python)
一、引言
前面提到,密度峰值聚类(Density peak clustering,DPC)1 在参数敏感性、标签分配方面具有一定缺陷,为解决这些问题,大量学者提出了各自的改进手段。
注意到原始 DPC 具有的参数敏感性是由截断距离
d
c
d_c
dc 带来的(这个距离的放缩会在数据集中影响相当数量的样本的局部密度),为此,杜2 等人通过采取K 近邻 (KNN) 的方式来改进计算各样本的局部密度,这在一定程度上降低了参数敏感性(该研究表面,基于 K 近邻的 DPC 算法(KNN-DPC)确实能有效提高 DPC 的聚类效果)。此时,计算密度的参数就由
d
c
d_c
dc 转变为 K 近邻的 K 值。
从这项工作之后,大量对 DPC 的改进算法研究都以 KNN 作为基础。本文介绍的模糊加权K-近邻的密度峰值聚类(FKNN-DPC 3)也是在 KNN 的基础上,通过分阶段的聚类来改善了 DPC 在标签分配策略上的不足。
二、算法思想
FKNN-DPC 对 DPC 的改进主要在以下两方面
采用基于 KNN 的密度核函数替换 DPC 基于截断距离
d
c
d_c
dc 的。采用两步标签分配策略替换 DPC 的一步分配。
1、基于 KNN 的密度核
基于截断距离的密度核会因为
d
c
d_c
dc 的轻微浮动而导致密度发生巨大变化。下图展示了这一情况(基于截断核
ρ
=
∑
j
∈
D
,
j
≠
i
χ
(
d
i
j
−
d
c
)
\rho=\sum_{j\in D,j\neq i}\chi\left(d_{ij}-d_c\right)
ρ=∑j∈D,j=iχ(dij−dc)):
因此,在实际应用中(无监督学习情况下),
d
c
d_c
dc 是一个极不稳定的因素,它会因为密度度量的不准确而影响簇心选取和标签分配,从而给最终的聚类结果带来非常大的影响。
FKNN-DPC的局部密度计算公式如下:
ρ
i
=
∑
j
∈
K
N
N
(
i
)
exp
(
−
d
i
j
)
\rho_i=\sum_{j\in KNN(i)}\text{exp}(-d_{ij})
ρi=j∈KNN(i)∑exp(−dij)
其中,
K
N
N
(
i
)
KNN(i)
KNN(i) 表示样本
i
i
i 的 K 近邻集合,
d
i
j
d_{ij}
dij 表示样本
i
i
i 和
j
j
j 之间的欧氏距离。该定义可以保证利用样本点
i
i
i 的 K 近邻分布信息来计算点
i
i
i 的局部密度;而原始 DPC 在基于截断距离
d
c
d_c
dc 计算局部密度时,不能保证样本点
i
i
i 在随
d
c
d_c
dc 变化时其周围的样本点个数能较为平稳地改变。更重要的是,确定参数 K 比中确定截止距离
d
c
d_c
dc 更容易。
从上图可以很明显地看出,尽管
K
K
K 值发生了较大变化,但是其计算密度时依然选择了距离较近的样本作为参考,因此得到的局部密度总体处于一个较为合理的区间。所以,这在一定程度上降低了参数敏感性。
2、标签分配策略
FKNN-DPC 通过构造与DPC相同的决策图,并利用
γ
=
ρ
δ
\gamma=\rho\delta
γ=ρδ 找到聚类中心,然后分别提出基于 KNN(第一分配阶段)和模糊加权 KNN(第二分配阶段)的两种策略,将剩余点分配到合适的聚类中。
为了避免由于离群点的影响而错误地将两个簇合并为一个簇,FKNN-DPC 的第一分配阶段仅针对非离群点进行,第二阶段则针对第一阶段尚未被分配标签的非离群点和离群点进行。在应用这两种分配策略后,若仍然存在未被分配标签的点,则视这些点为噪声点,FNKK-DPC 会将它们被分配到最近的已被分配标签邻居的类簇中。
FKNN-DPC 关于离群点(Outliers)的定义如下:
δ
i
K
=
max
j
∈
K
N
N
(
i
)
d
i
j
\delta_i^K=\text{max}_{j\in KNN(i)} d_{ij}
δiK=maxj∈KNN(i)dij
τ
=
1
n
∑
i
=
1
n
δ
i
K
\tau=\frac{1}{n}\sum_{i=1}^n\delta_i^K
τ=n1i=1∑nδiK
O
u
t
l
i
e
r
s
=
{
o
∣
δ
o
K
>
τ
}
Outliers=\{o \mid \delta_o^K > \tau\}
Outliers={o∣δoK>τ}
其中,
n
n
n 表示数据集
D
D
D 中包含的样本数量。
2.1 分配策略 1:基于 KNN 的标签分配
FKNN-DPC在这一阶段的标签分配主要是基于 K 近邻关系进行的,具体来说,其步骤如下:
遍历类簇中心向量
C
e
n
t
e
r
s
Centers
Centers ,从中选出一个簇心样本
c
i
c_i
ci;将
c
i
c_i
ci 的 K 近邻全部聚类至
c
i
c_i
ci 所属簇,并将这些样本依次压入一个队列
Q
Q
Q 中;从队列
Q
Q
Q 弹出队头样本
h
h
h,计算
h
h
h 与其 K 近邻的距离均值
r
r
r。接下来遍历
h
h
h 的 K 个近邻,对于其中的某个样本
q
q
q,如果满足条件: (1) 未被分配标签;(2) 为非离群点;(3)
h
h
h 与
q
q
q 的距离小于
r
r 拼多多帮助力入口
r,则将
q
q
q 分配到
h
h
h 所在簇中,并将
q
q
q 压入队列
Q
Q
Q 中。若队列
Q
Q
Q 非空,则转 3。
这一阶段将对数据集中的大部分非离群点完成标签分配。
2.2 分配策略 2:基于模糊加权 KNN 的标签分配
FKNN-DPC在这一阶段的标签分配采用了模糊加权 KNN 和半监督学习(即尽可能充分利用策略 1 已经获得的样本分配信息以对策略 1 未分配的样本和离群点进行标签分配)。FKNN-DPC 在这一阶段进行标签分配的关键是学习样本点
i
i
i 属于类簇
c
c
c 的概率,即样本
i
i
i 属于类簇
c
c
c 的隶属度
p
i
c
p_i^c
pic,然后根据
p
i
c
p_i^c
pic 值分配样本
i
i
i 到最相似的类簇
c
c
c,即
p
i
c
p_i^c
pic 值大的类簇。
为了定义样本
i
i
i 属于类簇
c
c
c 的隶属度
p
i
c
p_i^c
pic,我们先定义样本间的相似度
w
w
w:
w
i
j
=
1
1
+
d
i
j
w_{ij}=\frac{1}{1+d_{ij}}
wij=1+dij1
可以看出,样本间的距离
d
i
j
d_{ij}
dij 越小,它们就越相似。
样本
i
i
i 属于类簇
c
c
c 的隶属度
p
i
c
p_i^c
pic 用样本
i
i
i 的 K 近邻的类簇信息计算。样本
i
i
i 的 K 近邻中属于类簇
c
c
c 的样本
j
j
j 越多,且样本
i
i
i 和样本
j
j
j 越相似(
w
i
j
w_{ij}
wij 值越大),那么样本
i
i
i 属于类簇
c
c
c 的概率越大(
p
i
c
p_i^c
pic 的值也越大)。样本
i
i
i 属于类簇
c
c
c 的隶属度
p
i
c
p_i^c
pic 为:
p
i
c
=
∑
j
∈
K
N
N
i
,
y
j
=
c
ξ
i
j
∗
w
i
j
p_i^c=\sum_{j\in KNN_i, y_j=c}\xi_{ij}*w_{ij}
pic=j∈KNNi,yj=c∑ξij∗wij
其中,
ξ
i
j
=
w
i
j
∑
l
∈
K
N
N
j
w
l
j
\xi_{ij}=\frac{w_{ij}}{\sum_{l\in KNN_jw_{lj}}}
ξij=∑l∈KNNjwljwij,
y
j
y_j
yj 是样本
j
j
j 的标签,
ξ
i
j
\xi_{ij}
ξij是由
w
i
j
w_{ij}
wij被样本
j
j
j 与其 K 近邻样本的相似度之和标准化得到。
ξ
i
j
∗
w
i
j
\xi_{ij}*w_{ij}
ξij∗wij 项是样本
j
j
j 对
p
i
c
p_i^c
pic 的加权贡献,它的值不仅依赖于样本
i
i
i 和样本
j
j
j 间的相似度,也依赖于样本
j
j
j 的 K 近邻的样本分布。
FKNN-DPC 的样本分配策略 2 依据模糊加权 KNN 中的量高隶属度
p
i
c
p_i^c
pic 来分配样本
i
i
i。模糊加权 KNN 规则比传统 KNN 规则对 K 值更鲁棒,而且错误率更低。
FKNN-DPC 的样本分配策略 2 的详细步骤如下:
对每一个未被分配样本
i
i
i,根据上式计算样本
i
i
i 属于类簇
c
(
c
=
1
,
⋯
,
N
C
)
c (c=1,\cdots,NC)
c(c=1,⋯,NC) 的隶属度
p
i
c
p_i^c
pic,得到一个
1
×
N
C
1\times NC
1×NC 的向量,所有未被分配样本(设规模为
m
m
m)将构成
m
×
N
C
m\times NC
m×NC 一个的识别矩阵
A
A
A(
N
C
NC
NC 表示给定数据集的类簇数量)。构造长度为
m
m
m 的向量
V
A
VA
VA 和
V
P
VP
VP,分别用来存储从识别矩阵
A
A
A 中选出的每个样本
i
i
i 的隶属度
p
i
c
p_i^c
pic 中最大隶属度和最可能的所属类簇。
V
A
[
i
]
=
max
{
p
i
c
∣
c
=
1
,
⋯
,
N
C
}
,
V
P
[
i
]
=
argmax
c
{
p
i
c
∣
c
=
1
,
⋯
,
N
C
}
VA[i]=\text{max}\{p_i^c \mid c=1,\cdots,NC\}, VP[i]=\text{argmax}_c\{p_i^c \mid c=1,\cdots,NC\}
VA[i]=max{pic∣c=1,⋯,NC},VP[i]=argmaxc{pic∣c=1,⋯,NC}
如果
V
A
VA
VA 中有元素大于零,从中选择具有最大隶属度的样本
p
p
p,将其分配到可能属于的类簇中,即
V
P
[
p
]
VP[p]
VP[p] 所保存的类簇并转 4,否则结束策略 2。更新识别短阵
A
A
A 和向量
V
A
,
V
P
VA, VP
VA,VP,令
V
A
[
p
]
=
0
,
V
P
[
p
]
=
−
1
VA[p]=0, VP[p]=-1
VA[p]=0,VP[p]=−1。对于
K
N
N
(
p
)
KNN(p)
KNN(p) 中没有分配的样本
q
q
q,更新
A
[
q
]
[
c
]
A[q][c]
A[q][c],即样本
q
q
q 对于类簇
c
c
c 的隶属度
p
q
c
p_q^c
pqc,修改
p
q
c
p_q^c
pqc,令
p
q
c
=
p
q
c
+
ξ
q
p
×
w
q
p
p_q^c=p_q^c+\xi_{qp}\times w_{qp}
pqc=pqc+ξqp×wqp;更新
V
A
[
q
]
=
max
{
p
q
c
∣
c
=
1
,
⋯
,
N
C
}
VA[q]=\text{max}\{p_q^c \mid c=1,\cdots,NC\}
VA[q]=max{pqc∣c=1,⋯,NC} 和
V
P
[
q
]
=
argmax
c
{
p
q
c
∣
c
=
1
,
⋯
,
N
C
}
VP[q]=\text{argmax}_c\{p_q^c \mid c=1,\cdots,NC\}
VP[q]=argmaxc{pqc∣c=1,⋯,NC}。若无样本需要分配,则结束策略 2,否则转 3。
这一阶段将对数据集中的大部分样本点完成标签分配。此时,若仍存在未被分配标签的样本,则将这些样本分配至已被分配标签的最近邻居所在簇中。
三、总结
1、算法流程
FKNN-DPC 算法的执行流程如下:
对输入数据进行预处理(如归一化、缺失值处理);计算数据集中各点的欧氏距离(得到距离矩阵);基于距离矩阵计算各样本的近邻信息(包括 K 近邻矩阵,K 近邻距离矩阵);计算各样本点的局部密度
ρ
i
\rho_i
ρi 和相对距离
δ
i
\delta_i
δi;绘制决策图,并选取簇心;执行聚类(分配策略 1、分配策略 2)。
2、优缺点分析
FKNN-DPC 解决了 DPC 算法的局部密度定义缺陷和标签分配策略带有的 “多米诺效应”,在大量数据集上都表现出了非常好的效果(在后来出现的众多改进算法中,都鲜有超过该算法的)。但是,FKNN-DPC 在具有高密度差异的数据集上表现并不是很好,并且它也需要人工参与选取簇心。
四、代码实现(Python)
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from queue import Queue
'''
Density peak clustering based fuzzy weighted K Nearest Neighbours
'''
class FKNNDPC:
def __init__(self, X, y, k, K):
'''
Constructor
:param X: The feature matrix of dataset
:param y: Label of dataset
:param k: The number of sub clusters in the dataset
:param K: The number of nearest neighbors for each sample
'''
# Feature matrix
self.X = X
# Label vector
self.y = y
# The number of clusters to be clustered
self.NC = k
# The number of nearest neighbors for each sample
self.K = K
# The number of samples included in the dataset
self.Size = len(self.y)
# The number of features in the dataset
self.FN = X.shape[1]
# Distance matrix
self.DistanceMatrix = []
# K-nearest neighbor matrix of the sample
self.KNNMatrix = []
# The K-nearest neighbor distance matrix of the sample
self.KNNDMatrix = []
# Local density vector
self.Density = []
# The object sample vector of a sample
self.Object = np.zeros(self.Size, dtype=int)
# Relative distance 훿
self.RelativeDistance = np.zeros(self.Size, dtype=float)
# Decision value
self.DecisionValue = np.zeros(self.Size, dtype=float)
# Cluster centers
self.ClusterCenters = []
# Get outliers
self.Outlier = []
# Predictive labels
self.Labels = np.zeros(self.Size, dtype=int)
def __Normalization(self, X):
'''
Standardize the feature matrix
:param X: feature matrix
:return: Standardized feature matrix
'''
# 1. Instantiation converter (feature_range is the normalized range, i.e. minimum maximum)
transfer = MinMaxScaler(feature_range=(0, 1))
# 2. Call fit_transform (only needs to handle features)
return transfer.fit_transform(X)
def __getDistanceMatrix(self):
'''
Calculate the distance matrix of the sample (if there are discrete attributes, calculate the mixed distance)
:return:
'''
# Initialize a distance matrix
self.DistanceMatrix = np.zeros((self.Size, self.Size), dtype=float)
# Normalize the input data
self.X = self.__Normalization(self.X)
# Calculate distance matrix (based on Euclidean distance)
for i in range(self.Size - 1):
for j in range(i + 1, self.Size):
dis = np.sum(np.power(self.X[i] - self.X[j], 2)) ** 0.5
self.DistanceMatrix[i][j] = self.DistanceMatrix[j][i] = dis
def __getKNNInfomation(self):
'''
Calculate the K-nearest neighbor information of the sample
:return:
'''
# Calculate the K-nearest neighbor matrix of the sample
self.KNNMatrix = np.argsort(self.DistanceMatrix)[:, 1: self.K + 1]
# Calculate the K-nearest neighbor distance matrix of the sample
self.KNNDMatrix = np.sort(self.DistanceMatrix)[:, 1: self.K + 1]
def __getLocalDensity(self):
'''
Calculate the local density of each sample
'''
self.Density = np.sum(np.exp(-self.KNNDMatrix), axis=1)
def __getRelativeDistance(self):
'''
Calculate the relative distance between each sample
'''
# Sort density in descending order
sortDensityIndex = np.argsort(self.Density)[::-1]
# Set the relative distance of the sample with the highest density (which must be the cluster center)
self.RelativeDistance[sortDensityIndex[0]] = np.max(self.DistanceMatrix)
# Calculate relative distance and object sample
for i in range(1, self.Size):
tempIndex = sortDensityIndex[i]
self.Object[tempIndex] = sortDensityIndex[
np.argmin(self.DistanceMatrix[tempIndex][sortDensityIndex[:i]])]
self.RelativeDistance[tempIndex] = self.DistanceMatrix[tempIndex][self.Object[tempIndex]]
def __getClusterCenter(self):
'''
Calculate decision values for each sample and get the cluster centers
'''
self.DecisionValue = np.multiply(self.Density, self.RelativeDistance)
# Initialize cluster center:
# Select n samples with the highest decision value as cluster centers
self.ClusterCenters = np.argsort(self.DecisionValue)[-self.NC:][::-1]
# Assign different label values to the selected initial cluster center: 1, 2, 3,... (positive integer)
for i in range(self.NC):
self.Labels[self.ClusterCenters[i]] = i + 1
def __getOutlier(self):
'''
Calculate the set of outliers
:return:
'''
# Calculate the distance of the K-th nearest neighbor for each sample
KthNNDistance = self.KNNDMatrix[:,self.K-1]
# Calculate outlier threshold
OutlierThreshold = np.mean(KthNNDistance)
# Get outliers
self.Outlier = np.arange(self.Size)[KthNNDistance > OutlierThreshold]
def __LabelAllocation1(self):
'''
Label allocation strategy 1: Assign to non outlier points
:return:
'''
q = Queue()
# Traverse cluster centers
for center in self.ClusterCenters:
# Push all K-nearest neighbor samples at the center of the current cluster into queue q
# (and classify them into the cluster to which this sample belongs)
for neighbor in self.KNNMatrix[center]:
self.Labels[neighbor] = self.Labels[center]
q.put(neighbor)
# The requirement for determining whether there are still samples that can be classified in each nearest neighbor is:
# 1 Unassigned
# 2 Non outlier points
# 3 The distance between the current sample r and a certain point p in its K-nearest neighbor sample is
# less than the mean distance between the sample point r and its K-nearest neighbor
while not q.empty():
r = q.get()
Radius = np.mean(self.KNNDMatrix[r])
for p in self.KNNMatrix[r]:
if (self.Labels[p] == 0) and (p not in self.Outlier) and (self.DistanceMatrix[r][p] <= Radius):
self.Labels[p] = self.Labels[r]
q.put(p)
def __LabelAllocation2(self):
'''
Label allocation strategy 2: Assign to outliers and non outliers that have not been assigned after strategy 1
:return:
'''
# Calculate sample similarity matrix
self.SimilarMatrix = 1 / (1 + self.DistanceMatrix)
# Calculate the sum of K-nearest neighbor similarity for each sample (used to calculate weighted membership)
KNNSimilarSumVector = np.sum(1 / (1 + self.KNNDMatrix), 1)
#Define the recognition matrix
# (this structure is a dictionary, where the key corresponds to the sample number, and the value corresponds to
# the K-nearest neighbor classification of the sample, which is a list)
identifyMatrix = {}
# Initialize recognition matrix (h * C):
# Calculate the membership degree of each unassigned sample belonging to the cluster Ci
for index in range(self.Size):
# Skip allocated samples
if self.Labels[index] > 0:
continue
# Defining K-nearest neighbor classification vectors for samples
# Note: Due to the fact that the identification of sample clusters starts from 1 and the array index
# starts from 0, the number of columns in the initial construction of the recognition matrix should be +1
neighborClassVector = np.zeros(self.NC + 1, dtype=float)
# Calculate the membership degree of the current sample on various clusters (requiring traversal of its neighbors)
for neighbor in self.KNNMatrix[index]:
if self.Labels[neighbor] > 0:
neighborClassVector[self.Labels[neighbor]] += self.SimilarMatrix[index][neighbor]**2 / KNNSimilarSumVector[neighbor]
# Add statistical results to the identification matrix
identifyMatrix[index] = neighborClassVector
# Constructing recognition vectors: selecting the maximum membership degree of each sample from the recognition matrix
# This vector has a dictionary structure: key: sample index, value: [membership degree, corresponding class cluster number]
identifyVector = {}
for index in identifyMatrix:
# Extract the K-nearest neighbor classification vector of the specified sample from the dictionary
npary = np.array(identifyMatrix[index])
# Calculate the maximum membership degree and corresponding cluster number from the K-nearest neighbor classification vector
identifyVector[index] = [np.max(npary), np.argmax(npary)]
# Assign labels based on recognition vectors
while len(identifyVector) > 0:
# Select a sample with the highest membership degree from it
object = max(identifyVector, key=identifyVector.get)
# If the nearest neighbors of the current extracted sample have not been classified, it indicates that
# the sample is in an extremely isolated small cluster, and the loop is exited
if identifyVector[object][0] == 0:
break
# Classify the sample into the cluster indicated by its maximum membership degree
self.Labels[object] = identifyVector[object][1]
# Determine if there are any unassigned samples in the K-nearest neighbors of this sample,
# and update the membership degree of the unassigned samples corresponding to this sample
# Note: The original author of FKNN_DPC made this processing based on the assumption that if sample x is
# the nearest neighbor of sample y, then y is also the nearest neighbor of x
for neighboor in self.KNNMatrix[object]:
if self.Labels[neighboor] == 0:
# Update recognition matrix
identifyMatrix[neighboor][identifyVector[object][1]] += self.SimilarMatrix[neighboor][object]**2 / KNNSimilarSumVector[neighboor]
# Update the recognition vector (note: do not continue updating data that is no longer
# in the recognition vector, otherwise it may lead to falling into a dead cycle)
identifyVector[neighboor] = [np.max(identifyMatrix[neighboor]), np.argmax(identifyMatrix[neighboor])]
# Pop up the current sample from the recognition matrix and vector
identifyMatrix.pop(object)
identifyVector.pop(object)
def __LabelAllocation3(self):
'''
For extremely isolated samples, there may be a situation where mutual exclusion cannot be broken,
so it is necessary to cluster them separately
Cluster criterion: Merge unclassified samples into the cluster of the closest assigned sample
:return:
'''
for index in range(self.Size):
if self.Labels[index] == 0:
# Calculate the nearest neighbor vector of the current sample
NearstNeighbors = np.argsort(self.DistanceMatrix[index])[1:]
# Traverse neighbors to classify the current sample into the cluster where the most recently allocated sample is located
for neighbor in NearstNeighbors:
if self.Labels[neighbor] > 0:
self.Labels[index] = self.Labels[neighbor]
break
def fit(self):
self.__getDistanceMatrix()
self.__getKNNInfomation()
self.__getLocalDensity()
self.__getRelativeDistance()
self.__getClusterCenter()
self.__getOutlier()
self.__LabelAllocation1()
self.__LabelAllocation2()
self.__LabelAllocation3()
说明
所提供的 FKNN-DPC 代码是基于 “决策值准则” 选择簇心的。即,直接对决策值进行排序,然后选择具有最大决策值的前
N
C
NC
NC(需要提前给出的表示待聚类目标簇数量参数)个样本作为最终选择的簇心。
如果想直接拿来做实验,请移步 GitHub 链接 传送门(提供了完整的数据预处理、聚类结果展示、聚类评价指标等相关类)。下面是上述的 FKNN-DPC 代码在部分二维数据集上的实验结果:
下面是对应的聚类评价指标:
Rodriguez A, Laio A. Clustering by fast search and find of density peaks[J]. science, 2014, 344(6191): 1492-1496. ↩︎ Du M, Ding S, Jia H. Study on density peaks clustering based on k-nearest neighbors and principal component analysis[J]. Knowledge-Based Systems, 2016, 99: 135-145. ↩︎ Xie J, Gao H, Xie W, et al. Robust clustering by detecting density peaks and assigning points based on fuzzy weighted K-nearest neighbors[J]. Information Sciences, 2016, 354: 19-40. ↩︎
FKNN-DPC 【论文解读】Density peaks clustering based on fuzzy weighted K-nearest neighbors.2016.Information Science.
相关阅读