快速计算邻近矩阵中的平均接近度

时间:2012-10-03 21:04:13

标签: r matrix similarity proximity

我在所有案例之间都有一个相似性矩阵,在一个单独的数据框中,这些案例的类别。我想计算来自同一类的案例之间的平均相似度,这里是来自类j的示例n的等式:

Average proximity between cases

我们必须计算n和所有情况k之间的所有平方近似值之和,它们来自与n相同的类。链接:http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#outliers

我用2 for循环实现了它,但它确实很慢。在R中有更快的方法吗?

感谢。

// DATA(dput)

包含类的数据框:

structure(list(class = structure(c(1L, 2L, 2L, 1L, 3L, 3L, 1L, 
                            1L, 2L, 3L), .Label = c("1", "2", "3", "5", "6", "7"), class = "factor")), .Names = "class", row.names = c(NA, 
            -10L), class = "data.frame")

邻近矩阵(行m和列m对应于上面数据帧的行m中的类):

structure(c(1, 0.60996875, 0.51775, 0.70571875, 0.581375, 0.42578125, 
0.6595, 0.7134375, 0.645375, 0.468875, 0.60996875, 1, 0.77021875, 
0.55171875, 0.540375, 0.53084375, 0.4943125, 0.462625, 0.7910625, 
0.56321875, 0.51775, 0.77021875, 1, 0.451375, 0.60353125, 0.62353125, 
0.5203125, 0.43934375, 0.6909375, 0.57159375, 0.70571875, 0.55171875, 
0.451375, 1, 0.69196875, 0.59390625, 0.660375, 0.76834375, 0.606875, 
0.65834375, 0.581375, 0.540375, 0.60353125, 0.69196875, 1, 0.7194375, 
0.684, 0.68090625, 0.50553125, 0.60234375, 0.42578125, 0.53084375, 
0.62353125, 0.59390625, 0.7194375, 1, 0.53665625, 0.553125, 0.513, 
0.801625, 0.6595, 0.4943125, 0.5203125, 0.660375, 0.684, 0.53665625, 
1, 0.8456875, 0.52878125, 0.65303125, 0.7134375, 0.462625, 0.43934375, 
0.76834375, 0.68090625, 0.553125, 0.8456875, 1, 0.503, 0.6215, 
0.645375, 0.7910625, 0.6909375, 0.606875, 0.50553125, 0.513, 
0.52878125, 0.503, 1, 0.60653125, 0.468875, 0.56321875, 0.57159375, 
0.65834375, 0.60234375, 0.801625, 0.65303125, 0.6215, 0.60653125, 
1), .Dim = c(10L, 10L))

正确的结果:

c(2.44197227050781, 2.21901680175781, 2.07063155175781, 2.52448621289062, 
1.88040830957031, 2.16019295703125, 2.58622273828125, 2.81453253222656, 
2.1031745078125, 2.00542063378906)

1 个答案:

答案 0 :(得分:1)

应该可以。你的表示法并不清楚我们是否会在行或列中找到类似类的成员,所以这个答案在列中有所设定,但如果它们在行中,那么显而易见的修改也会起作用。

colSums(mat^2))  # in R this is element-wise application of ^2 rather than matrix multiplication.

由于两个操作都是矢量化的,因此预计会比for循环快得多。

通过修改并假设矩阵命名为'mat',类 - 数据帧命名为'cldf':

sapply( 1:nrow(mat) , 
           function(r) sum(mat[r, cldf[['class']][r] ==  cldf[['class']] ]^2)  )
[1] 2.441972 2.219017 2.070632 2.524486 1.880408 2.160193 2.586223 2.814533 2.103175 2.005421