본문 바로가기

if (IR or NLP)

NLTK(Natural Language Tool Kit)을 이용한 K-means 클러스터링

아래는 NLTK를 이용한 K-means 클러스터링 예제이다.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from nltk import cluster
from nltk.cluster.util import *

# d0 = "김태호 탈세"
# d1 = "이주호 탈세"
# d2 = "신재민 위장전입 부동산투기"
# d3 = "진수희 탈세"
# d4 = "이현동 위장전입"
# d5 = "유정복 탈세"
# d6 = "이재훈 부동산투기"

# features = [김태호, 이주호, 신재민, 진수희, 이현동, 유정복, 이재훈, 탈세, 위장전입, 부동산투기]
d = [None] * 7 
d[0] = [1, 0, 0, 0, 0, 0, 0, 1, 0, 0]
d[1] = [0, 1, 0, 0, 0, 0, 0, 1, 0, 0]
d[2] = [0, 0, 1, 0, 0, 0, 0, 0, 1, 1]
d[3] = [0, 0, 0, 1, 0, 0, 0, 1, 0, 0]
d[4] = [0, 0, 0, 0, 1, 0, 0, 0, 1, 0]
d[5] = [0, 0, 0, 0, 0, 1, 0, 1, 0, 0]
d[6] = [0, 0, 0, 0, 0, 0, 1, 0, 0, 1]

vectors = [numpy.array(f) for f in d]
# 초기 mean vector = [탈세], [위장전입], [부동산투기]
means = [[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] 

k = 3 
clusterer = cluster.KMeansClusterer(k, euclidean_distance, initial_means=means)
clusters = clusterer.cluster(vectors, True, trace = False)

for i in xrange(len(clusters)) :
    print 'd[%d] = cluster %d' %  (i, clusters[i])

실행 결과
d[0] = cluster 0
d[1] = cluster 0
d[2] = cluster 1
d[3] = cluster 0
d[4] = cluster 1
d[5] = cluster 0
d[6] = cluster 2