r - 在 R 中编程层次聚类算法的教学方法

标签 r algorithm data-manipulation hierarchical-clustering

我正在准备关于 R 机器学习的讲座,我想参加 hierarchical clustering作为一个例子。我在这里找到了这个非常有启发性的页面:http://home.deib.polimi.it/matteucc/Clustering/tutorial_html/hierarchical.html

它从以下距离表开始(读入数据时请注意 NA 作为列/行名称,另见下文):

enter image description here

MITO 之间的最短距离是 138,所以我们想将这些列和行合并到一个新的列/行中 MI/TO 这个新的复合对象 MI/TO 到所有剩余城市的距离等于原始城市之一的最短距离 MITO,例如MI/TORM564(来自 MI),因为它比 669 短>(从 TO)。 (这种聚合方式称为 single-linkage clustering )。所以我们有一个新表:

enter image description here

我的问题
我开始用 R 对此进行编码,很快发现代码变得越来越困惑——远非初出茅庐的程序员可以轻松理解的东西。您是否知道可以使用一种方法或包以自然直观的方式进行此类数据操作?


所以这是 R 中的起始表:

D <- matrix(c(0,662,877,255,412,996,
              662,0,295,468,268,400,
              877,295,0,754,564,138,
              255,468,754,0,219,869,
              412,268,564,219,0,669,
              996,400,138,869,669,0), ncol=6, byrow=T)

rownames(D) <- colnames(D) <- c("BA","FI","MI","Na","RM","TO")

D
##     BA  FI  MI  Na  RM  TO
## BA   0 662 877 255 412 996
## FI 662   0 295 468 268 400
## MI 877 295   0 754 564 138
## Na 255 468 754   0 219 869
## RM 412 268 564 219   0 669
## TO 996 400 138 869 669   0

最佳答案

内置函数“hclust”已经是一个很好用的函数。

hc1 = hclust(as.dist(D), method = "single")
hc1$merge
plot(hc1)

如果你想澄清,我可以详细描述。

按照hclust的逻辑,你可以试试:

savemat = list()
D1 = D; diag(D1) = Inf # a trick to make zero a infinity
m = 1
while(dim(D1)[1] > 2) {
    # get the location of minimum distance
    minloc = which(D1 == min(D1), arr.ind = T)[1,]
    # make a two-column matrix then find out the minimum value of each row
    u = apply(cbind(D1[minloc[2],],D1[minloc[1],]),1,min)
    # updating the matrix
    D1[minloc[2],] = u 
    D1[,minloc[2]] = u
    u = paste0(rownames(D1)[minloc[2]],'/',rownames(D1)[minloc[1]])
    rownames(D1)[minloc[2]] = u
    colnames(D1)[minloc[2]] = u
    # deleting the merged column/row
    D1 = D1[-minloc[1],-minloc[1]]
    diag(D1) = Inf
    # save the steps into a list element mth
    savemat[[m]] = D1
    m = m + 1
}
savemat

关于r - 在 R 中编程层次聚类算法的教学方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32266666/

相关文章:

R 与自身合并

r - 在 Ubuntu 中升级到 R 3.4.0 和最新的 rstudio 后,rstudio 崩溃, "r error 4"

回程数据的 R 组列

c - 试图用C制作帐篷和树木游戏

algorithm - 新近度是次要优先级的优先级队列?

r - 根据分组从列中减去值

r - 如何使用 R 4.1 中的 Octave?

r - R语言中 "I"的含义

java - 具有多个升序值列表的数字排序

删除数据集中的行出错