R中的字符串簇序列

参见英文答案 >
Text clustering with Levenshtein distances                                    4个

我必须遵循以下数据:

attributes <- c("apple-water-orange", "apple-water", "apple-orange", "coffee", "coffee-croissant", "green-red-yellow", "green-red-blue", "green-red","black-white","black-white-purple")
attributes 

           attributes 
1  apple-water-orange
2         apple-water
3        apple-orange
4              coffee
5    coffee-croissant
6    green-red-yellow
7      green-red-blue
8           green-red
9         black-white
10 black-white-purple

我想要的是另一个专栏,根据观察相似性为每一行分配一个类别.

category <- c(1,1,1,2,2,3,3,3,4,4)
df <- as.data.frame(cbind(df, category))

       attributes     category
1  apple-water-orange        1
2         apple-water        1
3        apple-orange        1
4              coffee        2
5    coffee-croissant        2
6    green-red-yellow        3
7      green-red-blue        3
8           green-red        3
9         black-white        4
10 black-white-purple        4

它在更广泛的意义上是聚类,但我认为大多数聚类方法仅用于数字数据,而单热编码有很多缺点(这就是我在互联网上阅读的内容).

有谁知道如何完成这项任务?也许有些词匹配方法?

如果我可以根据参数调整相似度(粗略与体面的“聚类”)也会很棒.

提前感谢任何想法!

最佳答案 所以我掀起了两种可能性.选项1:使用“单热编码”,只要苹果/苹果与苹果/橙子等同,就可以简单直接.我使用Jaccard索引作为距离度量,因为它在重叠集合方面做得相当好.选项2:使用局部序列比对算法,对苹果/苹果与苹果/橙子之类的东西应该非常强大,它还会有更多的调整参数,这些参数可能需要时间来优化您的问题.

library(reshape2)
library(proxy)

attributes <- c("apple-water-orange", "apple-water", "apple-orange", "coffee", 
                "coffee-croissant", "green-red-yellow", "green-red-blue", 
                "green-red","black-white","black-white-purple")
dat <- data.frame(attr=attributes, row.names = paste("id", seq_along(attributes), sep=""))
attributesList <- strsplit(attributes, "-")

df <- data.frame(id=paste("id", rep(seq_along(attributesList), sapply(attributesList, length)), sep=""), 
                 word=unlist(attributesList))

df.wide <- dcast(data=df, word ~ id, length)
rownames(df.wide) <- df.wide[, 1] 
df.wide <- as.matrix(df.wide[, -1])

df.dist <- dist(t(df.wide), method="jaccard")
plot(hclust(df.dist))
abline(h=c(0.6, 0.8))
heatmap.2(df.wide, trace="none", col=rev(heat.colors(15)))

res <- merge(dat, data.frame(cat1=cutree(hclust(df.dist), h=0.8)), by="row.names")
res <- merge(res, data.frame(cat2=cutree(hclust(df.dist), h=0.6)), by.y="row.names", by.x="Row.names")
res

您将看到可以通过调整剪切树形图的位置来控制分类的粒度.

《R中的字符串簇序列》

《R中的字符串簇序列》

这是使用“Smith-Waterman”对齐(局部)对齐的方法

Biostrings是Bioconductor project的一部分.SW算法找到两个序列(字符串)的最佳局部(非端到端)对齐.在这种情况下,您可以再次使用cutree设置类别,但您也可以调整scoring function以满足您的需求.

library(Biostrings)
strList <- lapply(attributes, BString)

swDist <- matrix(apply(expand.grid(seq_along(strList), seq_along(strList)), 1, function(x) {
  pairwiseAlignment(strList[[x[1]]], strList[[x[2]]], type="local")@score
}), nrow = 10)

heatmap.2(swDist, trace="none", col = rev(heat.colors(15)),
          labRow = paste("id", 1:10, sep=""), labCol = paste("id", 1:10, sep=""))

《R中的字符串簇序列》

点赞