如何使用R对9000个数字序列进行聚类?

时间:2018-12-19 17:22:04

标签: r cluster-analysis sequence hclust

我有一个csv文件,其中包含大约9000个需要集群的数字序列。 CSV的前6行如下所示:

id, sequence
"1","1 2"
"2","3 4 5 5 6 6 7 8 9 10 11 12 13 8 14 10 10 15 11 12 16"
"3","17 18 19 20 5 5 20 5 5"
"4","20 21"
"5","22 4 23 24 25 26"

我执行聚类的R代码看起来像这样

seqsim <- function(seq1, seq2){
  seq1 <- as.character(seq1)
  seq2 <- as.character(seq2)
  s1 <- get1grams(seq1)
  s2 <- get1grams(seq2)
  intersection <- intersect(s1,s2)
  if(length(intersection)==0){
    return (1)
  }
  else{
    u <- union(s1, s2)
    score = length(intersection)/length(u)
    return (1-score)
  }  
}      
###############   
mydata <- read.csv("sequence.csv")
mydatamatrix <- as.matrix(mydata$sequence) 

# take the data in csv and create dist matrix    
rownames(mydatamatrix) <- mydata$id
distance_matrix <- dist_make(mydatamatrix, seqsim, "SeqSim (custom)")
clusters <- hclust(distance_matrix,  method = "complete")
plot(clusters)
clusterCut <- cutree(clusters, h=0.5)
# clustercut contains the clusterIDs assigned to each sequence or row of the input dataset    
# Number of members in each cluster
table(mydata$id,clusterCut)    
write.csv(clusterCut, file = "clusterIDs.csv")

该代码适用于少量序列,例如大约900个序列,但是我遇到较大数据集的内存问题。

我的问题是:我是否在以正确的方式进行集群?是否有使用R来处理此类数据群集的更快且内存效率更高的方法? 函数seqsim实际上返回的是距离而不是相似度,因为我返回的是1-score。 Seqsim正在调用其他我遗漏的方法,以减少代码的长度。

1 个答案:

答案 0 :(得分:0)

我怀疑/假设瓶颈在于距离计算,而不是聚类本身

这是我的处理方式:

  1. 从距离计算中拆分文本处理(这将防止您多次处理每个字符串)
  2. 使用R的dist函数或使用矩阵运算来计算距离矩阵(即jaccard index)。
  3. 小心尝试对9000个序列进行聚类的结果,肯定会难以理解
  4. 9000 x 9000矩阵将需要大量内存,因此这可能是您需要克服的下一个瓶颈,这取决于我们计算机的内存资源。

代码:

library(arules)
df <- read.table(text='id, sequence
"1","1 2"
"2","3 4 5 5 6 6 7 8 9 10 11 12 13 8 14 10 10 15 11 12 16"
"3","17 18 19 20 5 5 20 5 5"
"4","20 21"
"5","22 4 23 24 25 26"', header=TRUE, sep=",")

seq <- lapply(df$sequence, get1grams) #I am assuming that get1grams produces a vector
names(seq) <- paste0("seq_", df$id)

seqTrans <- as(seq, "transactions") #create a transactions object
seqMat <- as(seqTrans, "matrix") #turn the transactions object into an incidence matrix each row represents a sequence and each column a 1gram each cell presence/absence of the 1gram
seqMat <- +(seqMat) #convert boolean to 0/1
j.dist <- dist(seqMat, method = "binary") #make use of base R's distance function

##Matrix multiplication to calculate the jaccard distance
tseqMat <- t(seqMat)
a <- t(tseqMat) %*% tseqMat
b <- t(matrix(rep(1, length(tseqMat)), nrow = nrow(tseqMat), ncol = ncol(tseqMat))) %*% tseqMat
b <- b - a
c <- t(b)
j <- as.dist(1-a/(a+b+c))

clusters <- hclust(j,  method = "complete")
plot(clusters)
clusterCut <- cutree(clusters, h=0.5)