python實現(xiàn)Canopy算法

Canopy聚類

前兩個月在做項目突然發(fā)現(xiàn)Canopy算法發(fā)現(xiàn)網上直接用python實現(xiàn)的不多,因為Mahout已經包含了這個算法,需要使用的時候僅需要執(zhí)行Mahout幾條命令即可,并且多數(shù)和MapReduce以及Hadoop分布式框架一起使用,感興趣的可以在網上查閱。但出于學習和興趣的態(tài)度,我更想嘗試用python來親自實現(xiàn)一些底層算法。

簡介

The canopy clustering algorithm is an unsupervised pre-clustering algorithm introduced by Andrew McCallum, Kamal Nigam and Lyle Ungar in 2000.[1]
It is often used as preprocessing step for the K-means algorithm or the Hierarchical clustering algorithm. It is intended to speed up clustering operations on large data sets, where using another algorithm directly may be impractical due to the size of the data set.
以上面出自于維基百科.

Canopy算法是2000年由Andrew McCallum, Kamal Nigam and Lyle Ungar提出來的,它是對k-means聚類算法和層次聚類算法的預處理。眾所周知,kmeans的一個不足之處在于k值需要通過人為的進行調整,后期可以通過肘部法則(Elbow Method)輪廓系數(shù)(Silhouette Coefficient)來對k值進行最終的確定,但是這些方法都是屬于“事后”判斷的,而Canopy算法的作用就在于它是通過事先粗聚類的方式,為k-means算法確定初始聚類中心個數(shù)和聚類中心點。

Canopy算法過程:
The algorithm proceeds as follows, using two thresholds
T1 (the loose distance) and T2(the tight distance), whereT1>T2[1][2]
1.Begin with the set of data points to be clustered.
2.Remove a point from the set, beginning a new 'canopy'.
3.For each point left in the set, assign it to the new canopy if the distance less than the loose distance T1.
4.If the distance of the point is additionally less than the tight distance T2, remove it from the original set.
5.Repeat from step 2 until there are no more data points in the set to cluster.
6.These relatively cheaply clustered canopies can be sub-clustered using a more expensive but accurate algorithm.

中文說明可以參考Canopy聚類算法(經典,看圖就明白)

代碼實現(xiàn)

使用的包:

# -*- coding: utf-8 -*-
# @Author: Alan Lau
# @Date: 2017-09-05 22:56:16
# @Last Modified by:   Alan Lau
# @Last Modified time: 2017-09-05 22:56:16

import math
import random
import numpy as np
from datetime import datetime
from pprint import pprint as p
import matplotlib.pyplot as plt

1.首先我在算法中預設了一個二維(為了方便后期畫圖呈現(xiàn)在二維平面上)數(shù)據(jù)dataset。當然也可以使用高緯度的數(shù)據(jù),并且我將canopy核心算法寫入了類中,后期可以通過直接調用的方式對任何維度的數(shù)據(jù)進行處理,當然只是小批量的,大批量的數(shù)據(jù)可以移步Mahout和Hadoop了,反正我的算法肯定沒它們好哈哈。

# 隨機生成500個二維[0,1)平面點
dataset = np.random.rand(500, 2)

2.然后生成個類,類的屬性如下

class Canopy:
    def __init__(self, dataset):
        self.dataset = dataset
        self.t1 = 0
        self.t2 = 0

加入設定t1和t2初始值以及判斷大小函數(shù)

    # 設置初始閾值
    def setThreshold(self, t1, t2):
        if t1 > t2:
            self.t1 = t1
            self.t2 = t2
        else:
            print('t1 needs to be larger than t2!')

3.距離計算,各個中心點之間的距離計算方法我使用的歐式距離。

# 使用歐式距離進行距離的計算
    def euclideanDistance(self, vec1, vec2):
        return math.sqrt(((vec1 - vec2)**2).sum())

4.再寫個從dataset中根據(jù)dataset的長度隨機選擇下標的函數(shù)

# 根據(jù)當前dataset的長度隨機選擇一個下標
    def getRandIndex(self):
        return random.randint(0, len(self.dataset) - 1)

5.核心算法

def clustering(self):
        if self.t1 == 0:
            print('Please set the threshold.')
        else:
            canopies = []  # 用于存放最終歸類結果
            while len(self.dataset) != 0:
                rand_index = self.getRandIndex()
                current_center = self.dataset[rand_index]  # 隨機獲取一個中心點,定為P點
                current_center_list = []  # 初始化P點的canopy類容器
                delete_list = []  # 初始化P點的刪除容器
                self.dataset = np.delete(
                    self.dataset, rand_index, 0)  # 刪除隨機選擇的中心點P
                for datum_j in range(len(self.dataset)):
                    datum = self.dataset[datum_j]
                    distance = self.euclideanDistance(
                        current_center, datum)  # 計算選取的中心點P到每個點之間的距離
                    if distance < self.t1:
                        # 若距離小于t1,則將點歸入P點的canopy類
                        current_center_list.append(datum)
                    if distance < self.t2:
                        delete_list.append(datum_j)  # 若小于t2則歸入刪除容器
                # 根據(jù)刪除容器的下標,將元素從數(shù)據(jù)集中刪除
                self.dataset = np.delete(self.dataset, delete_list, 0)
                canopies.append((current_center, current_center_list))
        return canopies

為了方便后面的數(shù)據(jù)可視化,我這里的canopies定義的是一個數(shù)組,當然也可以使用dict。
6.main()函數(shù)

def main():
    t1 = 0.6
    t2 = 0.4
    gc = Canopy(dataset)
    gc.setThreshold(t1, t2)
    canopies = gc.clustering()
    print('Get %s initial centers.' % len(canopies))
    #showCanopy(canopies, dataset, t1, t2)

Canopy聚類可視化代碼

def showCanopy(canopies, dataset, t1, t2):
    fig = plt.figure()
    sc = fig.add_subplot(111)
    colors = ['brown', 'green', 'blue', 'y', 'r', 'tan', 'dodgerblue', 'deeppink', 'orangered', 'peru', 'blue', 'y', 'r',
              'gold', 'dimgray', 'darkorange', 'peru', 'blue', 'y', 'r', 'cyan', 'tan', 'orchid', 'peru', 'blue', 'y', 'r', 'sienna']
    markers = ['*', 'h', 'H', '+', 'o', '1', '2', '3', ',', 'v', 'H', '+', '1', '2', '^',
               '<', '>', '.', '4', 'H', '+', '1', '2', 's', 'p', 'x', 'D', 'd', '|', '_']
    for i in range(len(canopies)):
        canopy = canopies[i]
        center = canopy[0]
        components = canopy[1]
        sc.plot(center[0], center[1], marker=markers[i],
                color=colors[i], markersize=10)
        t1_circle = plt.Circle(
            xy=(center[0], center[1]), radius=t1, color='dodgerblue', fill=False)
        t2_circle = plt.Circle(
            xy=(center[0], center[1]), radius=t2, color='skyblue', alpha=0.2)
        sc.add_artist(t1_circle)
        sc.add_artist(t2_circle)
        for component in components:
            sc.plot(component[0], component[1],
                    marker=markers[i], color=colors[i], markersize=1.5)
    maxvalue = np.amax(dataset)
    minvalue = np.amin(dataset)
    plt.xlim(minvalue - t1, maxvalue + t1)
    plt.ylim(minvalue - t1, maxvalue + t1)
    plt.show()
可視化結果

我把每個點都染上了其歸屬聚類中心點的顏色,還是挺漂亮的,這就是所謂的數(shù)據(jù)之美吧...

當然也有人問,t1和t2的初始值如何設定,后期的聚類中心點完全依賴這兩個值的變化。t1和t2可以通過交叉驗證的方式獲得,具體怎么做,得視乎數(shù)據(jù)以及用戶的需求,具體可以參考相關的論文。

Github鏈接

CanopyByPython

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容

  • 小A又發(fā)朋友圈了,她好像每天都過得很滋潤,老公總是送花送禮物,朋友似乎也一大堆,總有時間出去玩,還有,他們公司的獎...
    蜜小簡閱讀 354評論 0 0
  • 可這一切都不及他對妻子超脫的渴望! “赤云榴心,怎么一直找不到?”東伯雪鷹有些焦急,“再等些日子,如果實在不行,只...
    im喵小姐閱讀 169評論 0 0
  • 小人心實在可怖 君子腹也令人生畏 有些時候即使你明了他人的小心思卻還是不會拆穿看著他演或者陪著他演 這是人的本性嗎...
    蹩驢鬧性子閱讀 404評論 0 1