# 비계층적 군집분석
# 군집 수를 알고 있는 상태에서 군집분석을 함 -k-means clustering
iris.s <- scale(iris[-5]) #꽃 종류(spacies)는 뺌
head(iris.s) #정규화가 됨
#군집갯수 결정
install.packages("NbClust") #NbClust 를 사용 해서 k 값을 얻을수 있다.
library(NbClust)
nc <-NbClust(iris.s,min.nc = 2,max.nc = 10,method = 'kmeans')
nc
plot(table(nc$Best.nc[1,]))
#k-means모델
iris.k <- kmeans(iris.s, centers = 3, iter.max =100 ) # centers = 3(best number) iter.max =(최대 반복수)
iris.k
#confusion matrix
table(iris$Species,iris.k$cluster)
#시각화
#k-means 결과
plot(iris[-5],col=iris.k$cluster)
#실제값
plot(iris[-5],col=iris$Species)
par(mfrow=c(1,1)) #그래프 1개만 보기 혹은 2개 보기
#k-means 결과
plot(iris[c("Sepal.Length","Sepal.Width")],col=iris.k$cluster)
#실제값
plot(iris[c("Sepal.Length","Sepal.Width")],col=iris$Species)
#PAM k-means 가 아웃라이너에 민감해서 만든것이 pam이다.
library(cluster)
iris.p <- pam(iris.s,3)
iris.p
# 세분류로 나눔
table(iris.p$clustering,iris$Species)
clusplot(iris.p)
#일반적으로 보던 방법
plot(iris[c("Sepal.Length","Sepal.Width")],col=iris.p$clustering)
댓글 영역