层次聚类

一、层次聚类法

层次聚类法。先计算样本之间的距离。每次将距离最近的点合并到同一个类。然后,再计算类与类之间的距离,将距离最近的类合并为一个大类。不停的合并,直到合成了一个类。其中类与类的距离的计算方法有:最短距离法,最长距离法,中间距离法,类平均法等。比如最短距离法,将类与类的距离定义为类与类之间样本的最段距离。

r语言中使用dist(x, method = "euclidean",diag = FALSE, upper = FALSE, p = 2) 来计算距离。其中x是样本矩阵或者数据框。method表示计算哪种距离。method的取值有:
euclidean 欧几里德距离,就是平方再开方。
maximum 切比雪夫距离
manhattan 绝对值距离
canberra Lance 距离
minkowski 明科夫斯基距离,使用时要指定p值
binary 定性变量距离.
定性变量距离: 记m个项目里面的 0:0配对数为m0 ,1:1配对数为m1,不能配对数为m2,距离=m1/(m1+m2);
diag 为TRUE的时候给出对角线上的距离。upper为TURE的时候给出上三角矩阵上的值。


data(iris)
attach(iris)
data=iris[,-5]
dist.e=dist(data,method='euclidean')
heatmap(as.matrix(dist.e),labRow = F, labCol = F)


r语言中使用hclust(d, method = "complete", members=NULL) 来进行层次聚类。
其中d为距离矩阵。
method表示类的合并方法,有:
single 最短距离法
complete 最长距离法
median 中间距离法
mcquitty 相似法
average 类平均法
centroid 重心法
ward 离差平方和法


iris.hc <- hclust( dist.e,"single")
plclust( iris.hc, labels = FALSE, hang = -1)
#hang小于0时,树将从底部画起
re <- rect.hclust(iris.hc, k = 3)
iris.id <- cutree(iris.hc, 3)
table(iris.id, Species)


#ggplot2画树状图
library(colorspace)
library(amap)
require(ggplot2, quietly=TRUE)
require(ggdendro, quietly=TRUE)
ddata <- dendro_data(iris.hc, type="rectangle")
g <- ggplot(segment(ddata))
g <- g + geom_segment(aes(x = y, y = x, xend = yend, yend = xend))#将x和y互换,即将树的形状转90度
g <- g + scale_y_discrete(labels = ddata$label$label)#y轴的显示,即x的值,等
g <- g + labs(x="X轴", y="Y轴")#x和y轴的label
print(g)

#ggplot2画散点图
mds=cmdscale(dist.e,k=2,eig=T)
x = mds$points[,1]
y = mds$points[,2]
library(ggplot2)
p=ggplot(data.frame(x,y),aes(x,y))
p+geom_point(size=3,alpha=0.8,aes(colour=factor(result),shape=iris$Species))

#结果导出
table(iris$Species,model$cluster)
data.frame(data,x,y,result,iris$Species)



二. K-Means 动态聚类

层次聚类,在类形成之后就不再改变。而且数据比较大的时候更占内存。
动态聚类,先抽几个点,把周围的点聚集起来。然后算每个类的重心或平均值什么的,以算出来的结果为分类点,不断的重复。直到分类的结果收敛为止。r语言中主要使用kmeans(x, centers, iter.max = 10, nstart = 1,algorithm =c("Hartigan-Wong", "Lloyd","Forgy", "MacQueen"))来进行聚类。centers是初始类的个数或者初始类的中心。iter.max是最大迭代次数。nstart是当centers是数字的时候,随机集合的个数。algorithm是算法,默认是第一个。

model <- kmeans(scale(iris[1:4]),3)
table(iris$Species,model$cluster)
plot(newiris[c("Sepal.Length","Sepal.Width")],col=model$cluster)
data.frame(x,y,result,iris$Species)


三. 系统聚类

动态聚类往往聚出来的类有点圆形或者椭圆形。基于密度扫描的算法能够解决这个问题。思路就是定一个距离半径,定最少有多少个点,然后把可以到达的点都连起来,判定为同类。在r中的实现

dbscan(data, eps, MinPts, scale, method, seeds, showplot, countmode)

其中eps是距离的半径,minpts是最少多少个点。 scale是否标准化(我猜) ,method 有三个值raw,dist,hybird,分别表示,数据是原始数据避免计算距离矩阵,数据就是距离矩阵,数据是原始数据但计算部分距离矩阵。showplot画不画图,0不画,1和2都画。countmode,可以填个向量,用来显示计算进度。

使用fpc包

library(fpc)
newiris <- iris[1:4]
model <- dbscan(newiris,1.5,5,scale=T,showplot=T,method="raw")

posted @ 2019-12-29 11:13  HISAK  阅读(518)  评论(0)    收藏  举报