함께하는 데이터 분석

[EDA] Hierarchical Clustering with R 본문

통계학과 수업 기록/EDA

[EDA] Hierarchical Clustering with R

JEONGHEON 2022. 2. 2. 01:16

안녕하세요!

 

오늘은 Exploratory Data Analysis 수업에서 배우는 Clustering종류 중

 

Hierarchical Clustering에 대한 간단한 예제를 R코드를 통해 알아보겠습니다!

 

그럼 시작해볼게요!

 

간단한 좌표 설정

set.seed(1234) #rnorm으로 생성된 값 계속쓰기 위해 고정
x <- rnorm(12, mean=rep(c(1, 2, 3), each = 4), sd=rep(0.2, 12)) #1, 2, 3, 
y <- rnorm(12, mean=rep(c(1, 2, 1), each = 4), 0.2)
plot(x, y, col = "blue", pch = 19, cex = 2)
text(x + 0.05, y + 0.05, labels = as.character(1:12))

plot을 살펴보면 3개의 cluster로 묶는 것이 좋아 보이는 것을 알 수 있습니다.

 

Dendrogram 그리기

dataFrame <- data.frame(x=x, y=y) 
hClustering <- hclust(dist(dataFrame))
plot(hClustering, main="Euclidean distance/complete")

위의 좌표에 표시된 숫자대로 묶이는 것을 볼 수 있네요.

 

Cluster 숫자로 쪼개기

dataMatrix <- data.matrix(data.frame(x=x,y=y))
hcluster <- hclust(dist(dataMatrix))
plot(hcluster)
hclust.k2 <- cutree(hcluster, k =2) #cluster 2
table(hclust.k2)
hclust.k2
rect.hclust(hcluster, k=2)

hclust.k3 <- cutree(hcluster, k =3) #cluster 3
table(hclust.k3)
hclust.k3
rect.hclust(hcluster, k=3)

hclust.k4 <- cutree(hcluster, k =4) #cluster 4
table(hclust.k4)
hclust.k4
rect.hclust(hcluster, k=4)

 

Heatmap 이용

install.packages("gplots")
library(gplots)

heatmap.2(dataMatrix, trace='none', notecol='black', 
          cellnote=round(dataMatrix,3), density.info='none')

감사합니다!

'통계학과 수업 기록 > EDA' 카테고리의 다른 글

[EDA] FA with R  (0) 2022.02.06
[EDA] PCA with R  (0) 2022.02.06
[EDA] SVD with R  (0) 2022.02.05
[EDA] K-Means Clustering with R  (0) 2022.02.02