【问题标题】:K-means clustering with my own distance function使用我自己的距离函数进行 K 均值聚类
【发布时间】:2013-04-30 16:28:12
【问题描述】:

我已经定义了一个距离函数如下

jaccard.rules.dist <- function(x,y) ({
    # implements feature distance. Feature "Airline" gets a different treatment, the rest
    # are booleans coded as 1/0. Airline column distance = 0 if same airline, 1 otherwise
    # the rest of the atributes' distance is cero iff both are 1, 1 otherwise
    airline.column <- which(colnames(x)=="Aerolinea")
    xmod <- x
    ymod <-y
    xmod[airline.column] <-ifelse(x[airline.column]==y[airline.column],1,0)
    ymod[airline.column] <-1 # if they are the same, they are both ones, else they are different

    andval <- sum(xmod&ymod)
    orval <- sum(xmod|ymod)
    return (1-andval/orval)
})

它修改了表单数据帧的一点点jaccard距离

t <- data.frame(Aerolinea=c("A","B","C","A"),atr2=c(1,1,0,0),atr3=c(0,0,0,1))

现在,我想使用刚刚定义的距离对我的数据集执行一些 k-means 聚类。如果我尝试使用函数 kmeans,则无法指定我的距​​离函数。我尝试使用 hclust,它接受一个 distanca 矩阵,我计算如下

distmat <- matrix(nrow=nrow(t),ncol=nrow(t))
for (i in 1:nrow(t)) 
    for (j in i:nrow(t)) 
        distmat[j,i] <- jaccard.rules.dist(t[j,],t[i,])
distmat <- as.dist(distmat)

然后调用 hclust

hclust(distmat)

Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") : 
missing value where TRUE/FALSE needed

我做错了什么?是否有另一种只接受任意距离函数作为其输入的聚类方法?

提前致谢。

【问题讨论】:

  • 距离矩阵中有缺失值吗?
  • 或者你的矩阵大小是否大于65536?
  • 不,没有缺失值,矩阵是(在上面的例子中)4x4
  • 奇怪的是,当我用 100 行的真实数据框替换问题中显示的测试数据框时,这是一个 (100x100) 的矩阵,它起作用了。

标签: r distance k-means


【解决方案1】:

我认为distmat(来自您的代码)必须是距离结构(与矩阵不同)。试试这个:

require(proxy)
d <- dist(t, jaccard.rules.dist)
clust <- hclust(d=d)
clust@centers

     [,1]         [,2]
[1,]  0.044128322 -0.039518142
[2,] -0.986798495  0.975132418
[3,] -0.006441892  0.001099211
[4,]  1.487829642  1.000431146

【讨论】:

  • 我已将我的矩阵转换为距离 >distmat
猜你喜欢
  • 2017-03-26
  • 2016-03-10
  • 2017-12-09
  • 2017-03-07
  • 2014-06-05
  • 2014-09-30
  • 2015-06-02
  • 1970-01-01
相关资源
最近更新 更多