Python语言与信息数据获取和机器学习数据结构和算法分析

聚类算法——层次聚类算法

2018-02-11  本文已影响0人  猫不爱吃鱼

每篇一句:

You must strive to find your own voice. Because the longer you wait to begin, the less likely you are to find it at all.
--你必须努力去寻找自己的声音,因为你越迟开始寻找,找到的可能性越小。


层次聚类算法:

层次聚类算法 (Hierarchical Clustering Method)又称为系统聚类法、分级聚类法。

层次聚类算法又分为两种形式:


凝聚层次聚类:

本文介绍的为第一种形式,即凝聚层次聚类:

思路:每个样本先自成一类,然后按距离准则逐步合并,减少类数。


问题讨论:——类间距离计算准则

在算法描述第一步中提到要计算每个聚类之间的距离,在层次聚类算法中,计算聚类距离间距的计算方法主要有以下五种:


Python 实现:

# coding=utf-8

from max_min_cluster import get_distance


def hierarchical_cluster(data, t):
    # N个模式样本自成一类
    result = [[aData] for aData in data]
    step2(result, t)
    return result


def step2(result, t):

    # 记录类间最小距离
    min_dis = min_distance(result[0], result[1])  # 初始为1,2类之间的距离

    # 即将合并的类
    index1 = 0
    index2 = 1
    
    # 遍历,寻找最小类间距离
    for i in range(len(result)):
        for j in range(i+1, len(result)):
            dis_temp = min_distance(result[i], result[j])
            if dis_temp < min_dis:
                min_dis = dis_temp
                # 记录即将合并的聚类位置下标
                index1 = i
                index2 = j
                
    # 阈值判断
    if min_dis <= t:
        # 合并聚类index1, index2
        result[index1].extend(result[index2])
        result.pop(index2)
        # 迭代计算,直至min_dis>t为止
        step2(result, t)


def min_distance(list1, list2):

    # 计算两个聚类之间的最小距离:
    # 遍历两个聚类的所有元素,计算距离(方法较为笨拙,有待改进)

    min_dis = get_distance(list1[0], list2[0])
    for i in range(len(list1)):
        for j in range(len(list2)):
            dis_temp = get_distance(list1[i], list2[j]) # get_distance()函数见另一篇博文《聚类算法——最大最小距离算法》
            if dis_temp < min_dis:
                min_dis = dis_temp
    return min_dis
    
# 测试hierarchical_cluster
# data = [[0, 3, 1, 2, 0], [1, 3, 0, 1, 0], [3, 3, 0, 0, 1], [1, 1, 0, 2, 0],[3, 2, 1, 2, 1], [4, 1, 1, 1, 0]]
# t = math.sqrt(5.5)
# result = hierarchical_cluster(data, t)

# for i in range(len(result)):
#     print "----------第" + str(i+1) + "个聚类----------"
#     print result[i]

# 结果为:
# ----------第1个聚类----------
# [[0, 3, 1, 2, 0], [1, 3, 0, 1, 0], [1, 1, 0, 2, 0]]
# ----------第2个聚类----------
# [[3, 3, 0, 0, 1]]
# ----------第3个聚类----------
# [[3, 2, 1, 2, 1], [4, 1, 1, 1, 0]]

**注: **


最后:

本文简单的介绍了 聚类算法——层次聚类算法凝聚层次聚类 的相关内容,以及相应的代码实现,如果有错误的或者可以改进的地方,欢迎大家指出。

代码地址:聚类算法——层次聚类算法(码云)

原文地址:聚类算法——层次聚类算法也是本人的CSDN账号,欢迎关注,博客会第一时间在CSDN更新。

上一篇 下一篇

猜你喜欢

热点阅读