Python:密度峰值聚类DPCA,分裂两簇(版本:2)

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from scipy.spatial.distance import pdist,squareform
from collections import OrderedDict

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

def getGammaLeader(X,y,rho,distMatrix,Block):
    blockLength = len(Block)
    blockRho = rho[Block]
    blockRhoOrdIndex = np.flipud(np.argsort(blockRho))
    blockDelta = np.zeros(blockLength,dtype=float)
    blockLeader = np.ones(blockLength,dtype=int) * (-1)
    maxdist = 0
    for ele in Block:     ####对于Block中的每个样本,计算与密度最大点的距离
        if distMatrix[Block[blockRhoOrdIndex[0]],ele] > maxdist:     ##########需要转化为原始索引才能用distMatrix
            maxdist = distMatrix[Block[blockRhoOrdIndex[0]],ele]
    blockDelta[blockRhoOrdIndex[0]] = maxdist        #当前块的Delta 使用当前索引
    blockLeader[blockRhoOrdIndex[0]] = -1
    for i in range(1,blockLength):
        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      #当前块内索引
    blockGamma = blockDelta * blockRho
    blockGammaOrdIndex = np.flipud(np.argsort(blockGamma))

    # EE = X[blockGammaOrdIndex[:3]]
    # plt.scatter(X[:,0],X[:,1],c = y,marker='o')
    # plt.scatter(EE[:,0],EE[:,1],marker='*',c='k',s=100)
    # plt.show()
    return blockLeader,blockGammaOrdIndex,blockRhoOrdIndex

def getInformationBlock(X,y,Block,rho,distMatrix,blockNum):
    blockLeader, blockGammaOrdIndex, blockRhoOrdIndex = getGammaLeader(X,y,rho,distMatrix,Block)
    Length = len(Block)
    blockClusterIndex = np.ones(Length,dtype=int) * (-1)
    for i in range(blockNum):
        blockClusterIndex[blockGammaOrdIndex[i]] = i
    for i in range(1,Length):
        if blockClusterIndex[blockRhoOrdIndex[i]] == -1:
            # LD = blockLeader[blockRhoOrdIndex[i]]
            blockClusterIndex[blockRhoOrdIndex[i]] = blockClusterIndex[blockLeader[blockRhoOrdIndex[i]]]
    leftBlock = []
    rightBlock = []
    if len(set(blockClusterIndex)) != blockNum:
        print("密度峰值聚类环节出错了:类簇索引不是两个:",set(blockClusterIndex))
    for i in range(Length):
        if blockClusterIndex[i] == 0:
            leftBlock.append(Block[i])
        elif blockClusterIndex[i] == 1:
            rightBlock.append(Block[i])
        else:
            print("出错了:没有分配类簇标记")
    return leftBlock,rightBlock


if __name__ == "__main__":
    # iris = datasets.load_iris()
    # X = iris.data
    # y = iris.target
    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,currentBlock,rho,distMatrix,blockNum)
    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,leftBlock,rho,distMatrix,blockNum)
    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()

非常规写法,读者慎用!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeniuHe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值