import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from scipy.spatial.distance import pdist,squareform
def getDistCut(distList,distPercent):
maxDist = max(distList)
return maxDist * distPercent / 100
def getRho(n,distMatrix,distCut):
rho = np.zeros(n,dtype=float)
for i in range(n-1):
for j in range(i+1,n):
if distMatrix[i,j] < distCut:
rho[i] += 1
rho[j] += 1
return rho
#############計算當前塊的Gamma和Leader##################
def getinformationBlock(X,y,rho,distMatrix,Block):
m = len(Block)
blockRho = rho[Block]
blockRhoOrdIndex = np.flipud(np.argsort(blockRho))
blockDelta = np.zeros(m,dtype=float)
blockLeader = np.ones(m,dtype=int) * (-1)
#-------計算密度最大點的Delta和Leader-----------#
maxdist = 0
for ele in Block:
if distMatrix[Block[blockRhoOrdIndex[0]],ele] > maxdist:
maxdist = distMatrix[Block[blockRhoOrdIndex[0]],ele]
blockDelta[blockRhoOrdIndex[0]] = maxdist #密度最大點的距離
blockLeader[blockRhoOrdIndex[0]] = -1
# -------計算非密度最大點的Delta和Leader-----------#
for i in range(1,m):
mindist = np.inf
minindex = -1
for j in range(i):
if distMatrix[Block[blockRhoOrdIndex[i]],Block[blockRhoOrdIndex[j]]] < mindist:
mindist = distMatrix[Block[blockRhoOrdIndex[i]],Block[blockRhoOrdIndex[j]]]
# minindex = Block[blockRhoOrdIndex[j]]
minindex = blockRhoOrdIndex[j]
blockDelta[blockRhoOrdIndex[i]] = mindist
blockLeader[blockRhoOrdIndex[i]] = minindex #存儲的是索引,和正常的不一樣
#-------------計算塊中樣本的Gamma------------------#
blockGamma = blockDelta * blockRho
blockGammaOrdIndex = np.flipud(np.argsort(blockGamma))
'''聚類部分:上面的Leader搞不好就極易出錯'''
#--------聚類:生成兩個信息塊-----------------------#
# --------給聚類中心分配簇標籤----------------------#
clusterIndex = np.ones(m,dtype=int) * (-1)
for i in range(2):
clusterIndex[blockGammaOrdIndex[i]] = i
for i in range(1,m):
if clusterIndex[blockRhoOrdIndex[i]] == -1:
clusterIndex[blockRhoOrdIndex[i]] = clusterIndex[blockLeader[blockRhoOrdIndex[i]]]
# --------檢驗:有問題則拋個異常---------------#
if len(set(clusterIndex)) != 2:
print("密度峯值聚類環節出錯了:類簇索引不是兩個:", set(clusterIndex))
leftBlock = []
rightBlock = []
for i in range(m):
if clusterIndex[i] == 0:
leftBlock.append(Block[i])
elif clusterIndex[i] == 1:
rightBlock.append(Block[i])
elif clusterIndex[i] == -1:
print("問題警告:還沒有聚完:有樣本類簇標號爲-1")
else:
print("問題警告:有{-1,0,1}以外的類簇標號")
return leftBlock,rightBlock
if __name__ == "__main__":
X, y = datasets.make_blobs(n_samples=500, n_features=2, centers=3, cluster_std=[1.0, 1.0, 1.0], random_state=100)
n = len(X)
distPercent = 2
blockNum = 2
distList = pdist(X,metric='cityblock')
distMatrix = squareform(distList)
distCut = getDistCut(distList,distPercent)
rho = getRho(n,distMatrix,distCut)
currentBlock = [i for i in range(n)]
leftBlock, rightBlock = getinformationBlock(X,y,rho,distMatrix,currentBlock)
A = X[leftBlock]
B = X[rightBlock]
print("A塊的長度:",len(A),"B塊的長度:",len(B))
plt.scatter(A[:,0],A[:,1],marker='+')
plt.scatter(B[:,0],B[:,1],marker='o')
plt.show()
ll,rr = getinformationBlock(X,y,rho,distMatrix,leftBlock)
C = X[ll]
D = X[rr]
plt.scatter(B[:, 0], B[:, 1], marker='o')
plt.scatter(C[:, 0], C[:, 1], marker='*')
plt.scatter(D[:, 0], D[:, 1], marker='+')
plt.show()
非常規寫法,讀者慎用!