python 编写聚类指标purity纯度和jaccard函数

自编purity纯度和jaccard函数,最后运算速度都挺快的,另外,似乎用scipy中的混淆矩阵也可以编写scipy,而且要比我写的jaccard简便一些,可能是把我写的一些封装了吧。

from sklearn import datasets
from sklearn.utils.linear_assignment_ import linear_assignment
import seaborn as sns
import matplotlib.pyplot as plt
import copy
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.cluster import KMeans
import pandas as pd
import numpy as np

纯度

def purity(cluster, label):
    cluster = np.array(cluster)
    label = np. array(label)
    indedata1 = {}
    for p in np.unique(label):
        indedata1[p] = np.argwhere(label == p)
    indedata2 = {}
    for q in np.unique(cluster):
        indedata2[q] = np.argwhere(cluster == q)

    count_all = []
    for i in indedata1.values():
        count = []
        for j in indedata2.values():
            a = np.intersect1d(i, j).shape[0]
            count.append(a)
        count_all.append(count)

    return sum(np.max(count_all, axis=0))/len(cluster)

jaccard

def jaccard(cluster, label):
    dist_cluster = np.abs(np.tile(cluster, (len(cluster), 1)) -
                          np.tile(cluster, (len(cluster), 1)).T)
    dist_label = np.abs(np.tile(label, (len(label), 1)) -
                        np.tile(label, (len(label), 1)).T)
    a_loc = np.argwhere(dist_cluster+dist_label == 0)
    n = len(cluster)
    a = (a_loc.shape[0]-n)/2
    same_cluster_index = np.argwhere(dist_cluster == 0)
    same_label_index = np.argwhere(dist_label == 0)
    bc = same_cluster_index.shape[0]+same_label_index.shape[0]-2*n-2*a
    return a/(a+bc)
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值