1. Collective Intelligence
Chapter 3. 군집 발견(Discovering Groups)
Kwang Woo Nam
Department of Computer and Information Engineering
Kunsan National University
Textbook: Programming in Collective Intelligence, Toby Segaran
2. 데이터 클러스터링(군집화,Data Clustering) 개요
군집 분석(Clustering Analysis)
모집단 또는 범주에 대한 사전 정보가 없는 경우, 주어진 관측값들 사이의 거리 또는 유사성
을 이용하여, 전체를 몇 개의 집단으로 그룹화 하는 분석법
– 각 집단의 성격을 파악함으로써 데이터 전체의 구조에 대한 이해를 돕고자 하는 분석법
– 분류 분석(Classification Analysis,9장)과는 달리 목표 변수를 설정하지 않음.
– 따라서, 분류는 supervised learning[감독학습]이라고 하고, 군집분석은 unsupervised
learning[무감독학습]이라고도 함
활용 예: 문서 분류, 고객세분화를 통한 타겟 마케팅 등
데이터마이닝 : Collective Intelligence 2
3. 데이터 클러스터링(군집화,Data Clustering) 개요
데이터 군집화를 위한 변수의 예
인구통계적 변수 (성별, 나이, 거주지, 직업, 소득, 교육, 종교 등)
구매패턴 변수 (상품, 주기, 거래액 등)
생활패턴 변수 (라이프스타일, 성격, 취미, 가치관 등)
– 변수간의 거리 또는 유사성으로 군집화
주요 군집 분석 알고리즘
K-Means
EM(Expectation Maximization)
군집분석의 특징
군집분석은 자료의 사전정보 없이 자료를 파악하는 방법으로, 분석자의 주관에 결과가
달라질 수 있음
특이값을 갖는 개체의 발견, 결측값의 보정 등에 사용될 수 있음
변수의 선택이 중요
데이터마이닝 : Collective Intelligence 3
5. 데이터 클러스터링(군집화,Data Clustering) 개요
군집 분석의 적용 예 : IRIS 데이터
오픈소스 데이터마이닝 툴 Weka에서 기본적으로 지원하는 데이터
– Iris(붓꽃)의 꽃받침과 꽃잎 등 모양의 관찰이 기록된 데이터
– 군집화의 예 : 꽃받침과 꽃잎 너비 변수를 이용한 군집화
K-Mean을 이용한
Clustering 결과
EM을 이용한
Clustering 결과
데이터마이닝 : Collective Intelligence 5
6. 데이터 클러스터링(군집화,Data Clustering) 개요
In this book,
블로그 군집화
– 블로그의 특정 주제 또는 그들이 사용한 특별한 단어들의 사용방법을 이용한 군집화 방법
선호도 군집(zebo.com 데이터 분석)
– 갖고 싶은 물건 목록 웹사이트(zebo.com) 데이터의 분석
데이터마이닝 : Collective Intelligence 6
7. 블로거 군집화 : 단어 벡터
블로거 데이터
상위 120명의 블로거
각 블로그안에 출현하는 특정단어들의 횟수
생성해야 할 데이터의 예 : 블로거와 블로그 단어의 빈도수 데이터
만들어진 실 데이터의 예 : https://github.com/cataska/programming-collective-intelligence-
code/blob/master/chapter3/blogdata.txt
데이터마이닝 : Collective Intelligence 7
8. 블로거 군집화 : 단어 벡터
블로그 군집화의 단계
URL의
데이터를
가져와서
Word Count
blogdata.txt
데이터마이닝 : Collective Intelligence 8
Feedlist.txt
Rss
url 목록
파일
고빈도/저빈도
단어 필터링
Web
RSS
블로그-단어
행렬을 저장
블로그-
단어벡터
데이터
generatefeedvector.py
계층적
군집화 알고리즘
clusters.py 적용
9. 블로거 군집화 : RSS
RSS란?
"Really Simple Syndication"
– 그러나 종종 "Rich Site Summary”로 사용됨
웹사이트에 새롭게 생성되는 정보들(뉴스)을 쉽게 배포/구독할 수 있도록 하는 일종의
컨텐츠 전송 규칙으로 Netscape의 NetCente에서 출발한 개념
RSS 리더들
– 구글 리더 : http:// www.rssreader.com
– HanRSS : http://www.hanrss.com/
데이터마이닝 : Collective Intelligence 9
10. 블로거 군집화 : 피드 내 단어 수 세기
블로그 데이터 가져오기
RSS 피드를 이용하여 가져온 데이터를 파싱 하는 방법
Feedparser 설치는
Chapter2. ppt 24page
– Feedparser를 이용하여 블로그 페이지 내의 단어 출현 횟수를 카운트
– Rss url을 입력하면, 해당 url 문서의 summary와 title 내의 단어 출현 빈도수를 카운트
• generatefeedvector.py에 추가
import feedparser
import re
# Returns title and dictionary of word counts for an RSS feed
def getwordcounts(url):
# Parse the feed
d=feedparser.parse(url)
wc={}
# Loop over all the entries
for e in d.entries:
if 'summary' in e: summary=e.summary
else: summary=e.description
# Extract a list of words
words=getwords(e.title+' '+summary)
for word in words:
wc.setdefault(word,0)
wc[word]+=1
return d.feed.title,wc
def getwords(html):
# Remove all the HTML tags
txt=re.compile(r'<[^>]+>').sub('',html)
# Split words by all non-alpha characters
words=re.compile(r'[^A-Z^a-z]+').split(txt)
# Convert to lowercase
return [word.lower() for word in words if word!='']
데이터마이닝 : Collective Intelligence 10
11. 블로거 군집화 : 피드 내 단어 수 세기
블로그 목록 만들기
RSS 피드 주소들이 있는 목록을 만들어야 함
– 예제용 파일 : feedlist.txt
• https://github.com/cataska/programming-collective-intelligence-code/
blob/master/chapter3/feedlist.txt
• Feedlist에 원하는 rss url을 추가/변경 할수 있음
feedlist.txt의 예
데이터마이닝 : Collective Intelligence 11
12. 블로거 군집화 : 피드 내 단어 수 세기
블로그 목록 로딩
Feedlist.txt 파일로 부터 url을 가져와서, word count를 수행
– generatefeedvector.py 끝에 추가
apcount={}
wordcounts={}
feedlist=[line for line in file('feedlist.txt')]
for feedurl in feedlist:
try:
title,wc=getwordcount(feedurl)
wordcounts[title]=wc
for word,count in wc.items()
apcount.setdefault(word,0)
if count>1:
apcount[word]+=1
except:
print 'Failed to parse feed %s' % feedurl
이 예제 소스는 의도적으로 에러를
포함하고 있습니다.
직접 수정해서 돌리십시오.
데이터마이닝 : Collective Intelligence 12
13. 블로거 군집화 : 피드 내 단어 수 세기
고빈도/저빈도 단어 필터링
단어 필터링의 이유
– 고빈도 단어 : the, a 등
• 모든 블로그에 거의 공통적으로 나타나는 단어는 군집화 변수가 되기 어려움
– 저빈도 단어 : slang 또는 특수어
• 거의 한두번의 출현 빈도를 갖는 단어들은 다른 블로그와 유사성을 판단하기 어려움
필터링 factor
– 다음 예제에서는 10%이상 50%이하로 주고 있으나, 환경에 따라 변경 가능
– generatefeedvector.py 끝에 추가
wordlist=[]
for w,bc in apcount.items():
frac=float(bc)/len(feedlist)
if frac>0.1 and frac<0.5:
wordlist.append(w)
데이터마이닝 : Collective Intelligence 13
14. 블로거 군집화 : 피드 내 단어 수 세기
블로그-단어 벡터의 저장
각 블로그의 단어 출현 횟수를 갖는 행렬 텍스트 파일을 작성
– generatefeedvector.py 끝에 추가
• Blogdata1.txt 파일에 저장
out=file('blogdata1.txt','w')
out.write('Blog')
for word in wordlist: out.write('t%s' % word)
out.write('n')
for blog,wc in wordcounts.items():
print blog
out.write(blog)
for word in wordlist:
if word in wc: out.write('t%d' % wc[word])
else: out.write('t0')
out.write('n')
실행 예
c:codeblogcluster>python generatefeedvector.py
데이터마이닝 : Collective Intelligence 14
15. 블로거 군집화 : 계층적 군집화
계층적 군집화란
가장 유사한 그룹을 계속 병합하여 그룹 계층을 만드는 방법
– 가까운 관측값들 끼리 묶는 병합(agglomeration)방법과 먼 관측값들을 나누어가는
분할(division) 방법이 존재
– 계층적 군집에서는 주로 병합 방법이 사용됨
데이터마이닝 : Collective Intelligence 15
16. 블로거 군집화 : 계층적 군집화
계층적 군집화의 실행 모습과 결과 계통도
계층적 군집화 실행 모습
계층적 군집화의 결과 계층도
데이터마이닝 : Collective Intelligence 16
17. 블로거 군집화 : 계층적 군집화
단어 벡터 파일 읽기
블로그-단어 벡터 파일(blogdata.txt) 파일을 읽어서 반환
– clusters.py 파일을 만들고 추가
def readfile(filename):
lines=[line for line in file(filename)]
# First line is the column titles
colnames=lines[0].strip().split('t')[1:]
rownames=[]
data=[]
for line in lines[1:]
p=line.strip().split('t')
# First column in each row is the rowname
rownames.append(p[0])
# The data for this row is the remainder of the row
data.append([float(x) for x in p[1:]])
return rownames,colnames,data
rownames
colnames
data
이 예제 소스는 의도적으로
에러를 포함하고 있습니다.
직접 수정해서 돌리십시오.
데이터마이닝 : Collective Intelligence 17
18. 블로거 군집화 : 계층적 군집화
유사성 거리 계산
Pearson 계수를 이용한 상관 점수 계산
– 1.0이면 완전 유사, 0이면 전혀 관계없음, -1.0이면 완전 반대
from math import sqrt
def pearson(v1,v2):
# Simple sums
sum1=sum(v1)
sum2=sum(v2)
# Sums of the squares
sum1Sq=sum([pow(v,2) for v in v1])
sum2Sq=sum([pow(v,2) for v in v2])
# Sum of the products
pSum=sum([v1[i]*v2[i] for I n range(len(v1))])
# Calculate r (Pearson score)
num=pSum-(sum1*sum2/len(v1))
den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1)))
if den==0: return 0
return 1.0-num/den
이 예제 소스는 의도적으로
에러를 포함하고 있습니다.
직접 수정해서 돌리십시오.
데이터마이닝 : Collective Intelligence 18
19. 블로거 군집화 : 계층적 군집화
군집화 알고리즘
rows
rows[1]
rows[2]
…
bicluster:clust
clust[1] = rows[1]
clust[2] = rows[2]
clust[3] = rows[3]
clust[4] = rows[4]
clust[5]
…
최소 distance 쌍을 찾는 루프
데이터마이닝 : Collective Intelligence 19
초기
Cluster가로줄 생성
각 clust간 Distance 계산
최소 distance 쌍 (1,3)
새로운 군집 생성
bicluster:clust
clust[1] = rows[1]
clust[2] = rows[2]
clust[3] = rows[3]
clust[4] = rows[4]
clust[5]
…
clust[n+1] :
self.left=rows[1]
self.right=rows[3]
20. 블로거 군집화 : 계층적 군집화
군집화 알고리즘 구현
def hcluster(rows,distance=pearson):
distances={}
currentclustid=-1
# 각 가로줄에서 초기 군집들을 생성
clust=[bicluster(rows[i],id=i) for i in range(len(rows))]
while len(clust)>1:
lowestpair=(0,1)
closest=distance(clust[0].vec,clust[1].vec)
# 가장 작은 거리 값을 갖는 쌍을 찾는 루프
for i in range(len(clust)):
for j in range(i+1,len(clust)):
# distances is the cache of distance calculations
if (clust[i].id,clust[j].id) not in distances:
distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)
d=distances[(clust[i].id,clust[j].id)]
if d<closest:
closest=d
lowestpair=(i,j)
class bicluster:
def __init__(self,vec,left=None,right=None,distance=0.0,id=None):
self.left=left
self.right=right
self.vec=vec
self.id=id
self.distance=distance
# 두 군집간의 평균을 계산
mergevec=[
(clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0
for i in range(len(clust[0].vec))]
# 최소 거리 군집을 하나의 군집으로 생성
newcluster=bicluster(mergevec,left=clust[lowestpair[0]],
right=clust[lowestpair[1]],
distance=closest,id=currentclustid)
# cluster ids that weren't in the original set are negative
currentclustid-=1
del clust[lowestpair[1]]
del clust[lowestpair[0]]
clust.append(newcluster)
return clust[0]
데이터마이닝 : Collective Intelligence 20
21. 블로거 군집화 : 계층적 군집화
군집화 알고리즘 실행
$ python
>> import clusters
>> blognames,words,data=clusters.readfile('blogdata.txt')
>> clust=clusters.hcluster(data)
계층 군집 형태로 출력하기
def printclust(clust,labels=None,n=0):
# indent to make a hierarchy layout
for i in range(n): print ' ',
if clust.id<0:
# negative id means that this is branch
print '-'
else:
# positive id means that this is an endpoint
if labels==None: print clust.id
else: print labels[clust.id]
# now print the right and left branches
if clust.left!=None: printclust(clust.left,labels=labels,n=n+1)
if clust.right!=None: printclust(clust.right,labels=labels,n=n+1)
데이터마이닝 : Collective Intelligence 21
22. 블로거 군집화 : 계층도 출력
계층도 출력 jpg 라이브러리
pythonware.com : 파이썬 이미지 라이브러리
이미지 라이브러리 사용하기
From PIL import Image, ImageDraw
이미지 출력을 위한 함수들 : getheight, getdepth
def getheight(clust):
# Is this an endpoint? Then the height is just 1
if clust.left==None and clust.right==None: return 1
# Otherwise the height is the same of the heights of
# each branch
return getheight(clust.left)+getheight(clust.right)
def getdepth(clust):
# The distance of an endpoint is 0.0
if clust.left==None and clust.right==None: return 0
# The distance of a branch is the greater of its two sides
# plus its own distance
return max(getdepth(clust.left),getdepth(clust.right))+clust.distance
데이터마이닝 : Collective Intelligence 22
23. 블로거 군집화 : 계층도 출력
계층도 출력
Drawdendrogram
– 최종 군집마다 높이 20 픽셀과 고정 폭을 갖는 이미지를 생성
def drawdendrogram(clust,labels,jpeg='clusters.jpg'):
# height and width
h=getheight(clust)*20
w=1200
depth=getdepth(clust)
# width is fixed, so scale distances accordingly
scaling=float(w-150)/depth
# Create a new image with a white background
img=Image.new('RGB',(w,h),(255,255 255))
draw=ImageDraw,Draw(img)
draw.line((0,h/2,10,h/2),fill=(255,0,0))
# Draw the first node
drawnode(draw,clust,10,(h/2),scaling,labels)
img.save(jpeg,'JPEG')
이 예제 소스는 의도적으로
에러를 포함하고 있습니다.
직접 수정해서 돌리십시오.
데이터마이닝 : Collective Intelligence 23
24. 블로거 군집화 : 계층도 출력
계층도 출력
Drawnode
– 자식 노드들의 높이를 계산하여 자신의 위치를 계산
def drawnode(draw,clust,x,y,scaling,labels):
if clust.id<0:
h1=getheight(clust.left)*20
h2=getheight(clust.right)*20
top=y-(h1+h2)/2
bottom=y+(h1+h2)/2
# Line length
ll=clust.distance*scaling
# Vertical line from this cluster to children
draw.line((x,top+h1/2,x,bottom-h2/2),fill=(255,0,0))
# Horizontal line to left item
draw.line((x,top+h1/2,x+ll,top+h1/2),fill=(255,0,0))
# Horizontal line to right item
draw.line((x,bottom-h2/2,x+ll,bottom-h2/2),fill=(255,0,0))
# Call the function to draw the left and right nodes
drawnode(draw,clust.left,x+ll,top+h1/2,scaling,labels)
drawnode(draw,clust.right,x+ll,bottom-h2/2,scaling,labels)
else:
# If this is an endpoint, draw the item label
draw.text((x+5,y-7),labels[clust.id],(0,0,0))
데이터마이닝 : Collective Intelligence 24
25. 블로거 군집화 : 계층도 출력
계층도 출력 결과
데이터마이닝 : Collective Intelligence 25
26. 블로거 군집화 : 세로줄 군집화(Column Clustering)
세로줄 군집화
예 : 함께 구매하는 물건 전시 선반 찾기
예 : 블로그간 군집화가 아니라, 블로그-단어간 군집화
def rotatematrix(data):
newdata=[]
for i in range(len(data[0])):
newrow=[data[j][i] for j in range(len(data))]
newdata.append(newrow)
return newdata
>> reload(clusters)
>> rdata=clusters.rotatematrix(data)
>> wordclust=clusters.hcluster(rdata)
>> clusters.drawdendrogram(wordclust,labels=words,jpeg='wordclust.jpg')
데이터마이닝 : Collective Intelligence 26
27. 리포트
국내 블로거 군집화 하기
1) Hanrss의 인기 블로거 리스트에서 군집찾기
– http://www.hanrss.com/directory/index.qst?show=popular
2) Hanrss의 컴퓨터 분야 블로거 리스트에서 군집 찾기
– http://www.hanrss.com/directory/index.qst?tag=%EC%BB%B4%ED%93%A8%E
D%84%B0
– 최소 100 명정도
3) Hanrss의 게임 분야 블로거 리스트에서 군집 찾기
데이터마이닝 : Collective Intelligence 27
28. 리포트
RSS 주소 찾기
28
데이터마이닝 : Collective Intelligence
RSS 주소
29. K-평균 군집화(k-means clustering)
계층적 군집화의 문제점
트리 형태로 계층을 구성하긴 하나, 뚜렷한 그룹으로 분할하진 못함
매우 느리게 동작. 모든 항목마다 계산이 필요하고 항목들이 병합될 때에 재계산 필요
K-평균 군집화의 특징
(wiki)주어진 데이터를 특정 성질에 기초해서 k개의 묶음(cluster)로 나누는 방법중 하나
K개의 사전에 지정된 군집의 개수를 지정하고 군집화하므로 계층적 군집화 보다 빠름
단점
– 전역 최적값을 보장하지 않음 : 맨 처음 나눈 방법에 상당히 의존한 결과를 생성하므로 최적값에
비해 매우 나쁜 값을 얻을 수 있음
• 알고리즘이 빠르기 때문에 서로 다른 초기값으로 여러 번 시도하여 좋은 클러스터를 선택
– 알고리즘을 시작할때 사전 지식없이 k값을 정해주어야 하므로, 데이터가 자연스럽지 안헤
분포되는 결과를 얻을 수 있음
데이터마이닝 : Collective Intelligence 29
30. K-평균 군집화(k-means clustering)
알고리즘
무작위로 선정된 k개의 중심점(centroid)을 선정
이 중심점에서 각 객체들의 거리를 계산하여 결정
최소 거리를 갖는 객체에 기반하여 그룹화
그림 : http://people.revoledu.com/kardi/tutorial/kMean/NumericalExample.htm
데이터마이닝 : Collective Intelligence 30
31. K-평균 군집화(k-means clustering)
K-평균 군집화의 구현
무작위로 선정된 k개의 중심점(centroid)을 선정
# Create k randomly placed centroids
clusters=[
[random.random()*(ranges[i][1]-ranges[i][0])+ranges[i][0]
for i in range(len(rows[0]))]
for j in range(k) ]
이 중심점에서 각 객체들의 거리를 계산하여 결정
lastmatches=None
for t in range(100):
print 'Iteration %d' % t
bestmatches=[[] for i in range(k)]
# Find which centroid is the closest for each row
for j in range(len(rows)):
row=rows[j]
bestmatch=0
for i in range(k):
d=distance(clusters[i],row)
if d<distance(clusters[bestmatch],row): bestmatch=i
bestmatches[bestmatch].append(j)
# If the results are the same as last time, this is complete
if bestmatches==lastmatches: break
lastmatches=bestmatches
1
2
데이터마이닝 : Collective Intelligence 31
32. K-평균 군집화(k-means clustering)
K-평균 군집화의 구현
최소 거리를 갖는 객체에 기반하여 그룹화
# 중심점을 멤버들의 평균으로 이동함
for i in range(k):
avgs=[0.0]*len(rows[0])
if len(bestmatches[i])>0:
for rowid in bestmatches[i]:
for m in range(len(rows[rowid])):
avgs[m]+=rows[rowid][m]
for j in range(len(avgs)):
avgs[j]/=len(bestmatches[i])
clusters[i]=avgs
3
데이터마이닝 : Collective Intelligence 32
33. K-평균 군집화(k-means clustering)
K-평균 군집화의 구현
def kcluster(rows,distance=pearson,k=4):
# Determine the minimum and maximum values for each point
ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows]))
for i in range(len(rows[0]))]
# k개의 군집 랜덤 생성
clusters=[[random.random()*(ranges[i][1]-ranges[i][0])+ranges[i][0]
for i in range(len(rows[0]))] for j in range(k)]
1
lastmatches=None
for t in range(100):
print 'Iteration %d' % t
bestmatches=[[] for i in range(k)]
# 가장 근접한 객체 찾기
for j in range(len(rows)):
2
row=rows[j]
bestmatch=0
for i in range(k):
d=distance(clusters[i],row)
if d<distance(clusters[bestmatch],row): bestmatch=i
bestmatches[bestmatch].append(j)
# If the results are the same as last time, this is complete
if bestmatches==lastmatches: break
lastmatches=bestmatches
# 군집을 찾아 중심점을 옮기기
for i in range(k):
avgs=[0.0]*len(rows[0])
if len(bestmatches[i])>0:
for rowid in bestmatches[i]:
for m in range(len(rows[rowid])):
avgs[m]+=rows[rowid][m]
for j in range(len(avgs)):
avgs[j]/=len(bestmatches[i])
clusters[i]=avgs
return bestmatches
3
데이터마이닝 : Collective Intelligence 33
34. K-평균 군집화(k-means clustering)
K-평균 군집화의 실행
>> reload(clusters)
>> kclust=clusters.kcluster(data,k=10)
Iteration 0
...
>> [rownames[r] for r in k[0]]
['The Viral Garden', 'Copyblogger', 'Creating Passionate Users', 'Oilman',
'ProBlogger Blog Tips', "Seth's Blog"]
>> [rownames[r] for r in k[1]]
etc..
데이터마이닝 : Collective Intelligence 34
35. 2차원으로 데이터 보기
다차원 비례 축소법(multidimensional scaling)
데이터의 유사성이나 비유사성을 탐색하기 위하여 자료와의 적합도가 유지되는 한도내에서
2-3차원의 도표로 차원을 낮추어 보여주기위한 테크닉들의 집합(wiki)
– 군집화 변수 등은 여러 개의 요소에 의해 결정되므로 사람이 쉽게 인식가능한 2-3차원 도표로
표현하기 어려움
정보 가시화(information visualization)에서 사용되며, 다차원 비례 축소법에 의해
그려지는 지도를 다차원 인식지도(perceptual map)이라고 함
다차원 비례 축소법(multidimensional scaling)의 예
– 상품과 상품 간의 관계 factor => 날씨, 일자, 온도, 고객 성향 등 다양 => 가시화 문제 발생
• 주요 factor를 단순화하여 2-3차원으로 변환하여 visualization
데이터마이닝 : Collective Intelligence 35
36. 2차원으로 데이터 보기
인식지도(perceptual map)
경쟁 차종간 인식지도(wiki)
온라인 게임 사이트 인식지도
제품간 인식지도
데이터마이닝 : Collective Intelligence 36
37. 2차원으로 데이터 보기
피어슨 상관 계수를 이용한 Visualization
상품간 피어슨 계수 거리 행렬
2D 가시화 : 임의의 위치에 값들을 뿌림
데이터마이닝 : Collective Intelligence 37
38. 2차원으로 데이터 보기
피어슨 상관 계수를 이용한 Visualization
항목간 거리 도표
– 모든 항목간의 거리를 계산하고, 모든 항목 쌍에 대하여 실제값에 비례하여 이동
모든 항목들의 위치를 조정하여, 전체 오차값이 줄어들지 않을 때까지 반복 수행
데이터마이닝 : Collective Intelligence 38
39. 2차원으로 데이터 보기
구현
def scaledown(data,distance=pearson,rate=0.01):
n=len(data)
# The real distances between every pair of items
realdist=[[distance(data[i],data[j]) for j in range(n)]
for i in range(0,n)]
# Randomly initialize the starting points of the locations in 2D
loc=[[random.random(),random.random()] for i in range(n)]
fakedist=[[0.0 for j in range(n)] for i in range(n)]
lasterror=None
for m in range(0,1000):
# Find projected distances
for i in range(n):
for j in range(n):
fakedist[i][j]=sqrt(sum([pow(loc[i][x]-loc[j][x],2)
# Move points
grad=[[0.0,0.0] for i in range(n)]
totalerror=0
for k in range(n):
for j in range(n):
if j==k: continue
# The error is percent difference between the distances
errorterm=(fakedist[j][k]-realdist[j][k])/realdist[j][k]
# Each point needs to be moved away from or towards the other
# point in proportion to how much error it has
grad[k][0]+=((loc[k][0]-loc[j][0])/fakedist[j][k])*errorterm
grad[k][1]+=((loc[k][1]-loc[j][1])/fakedist[j][k])*errorterm
# Keep track of the total error
totalerror+=abs(errorterm)
print totalerror
데이터마이닝 : Collective Intelligence 39
40. 2차원으로 데이터 보기
구현
# If the answer got worse by moving the points, we are done
if lasterror and lasterror<totalerror: break
lasterror=totalerror
# Move each of the points by the learning rate times the gradient
for k in range(n):
loc[k][0]-=rate*grad[k][0]
loc[k][1]-=rate*grad[k][1]
return loc
def draw2d(data,labels,jpeg='mds2d.jpg'):
img=Image.new('RGB',(2000,2000),(255,255,255))
draw=ImageDraw.Draw(img)
for i in range(len(data)):
x=(data[i][0]+0.5)*1000
y=(data[i][1]+0.5)*1000
draw.text((x,y),labels[i],(0,0,0))
img.save(jpeg,'JPEG')
데이터마이닝 : Collective Intelligence 40
41. 2차원으로 데이터 보기
실행
>> reload(clusters)
>> blognames,words,data=clusters.readfile('blogdata.txt')
>> coords=clusters.scaledown(data)
...
>> clusters.draw2d(coords,blognames,jpeg='blogs2d.jpg')
데이터마이닝 : Collective Intelligence 41
42. Advanced Report
Clustering Real Map Data
USA North East Dataset (rtreeportal)
– 123,593 postal addresses
– three metropolitan areas (New York, Philadelphia and Boston)
– Three Cluster :
• a lot of noise,
• distributed rural areas and smaller population centers
데이터마이닝 : Collective Intelligence 42
43. Advanced Report
Clustering Real Map Data
Spatiotemporal(Trajectory) Datasets
– Download : (rtreeportal)
– Bus : trajectories of 145 objects
– Truck : trajectories of 276 objects
데이터마이닝 : Collective Intelligence 43
44. Advanced Report
참고논문
Survey
– Trends in Spatial Data Mining,
http://www.spatial.cs.umn.edu/paper_ps/dmchap.pdf
– Spatial Data Mining: A Database Approach,
http://eprints.kfupm.edu.sa/66096/1/66096.pdf
Spatial Clustering
– Efficient and effective clustering methods for spatial data mining
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.95.4297&rep=rep1&typ
e=pdf
Trajectory Clustering
– Trajectory clustering: a partition-and-group framework,
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.76.8098&rep=rep1&typ
e=pdf
– http://eprints.kfupm.edu.sa/73056/1/73056.pdf
데이터마이닝 : Collective Intelligence 44