![](/img/trans.png)
[英]In a 3d array in numpy. How can I extract indices of max element in third dimension?
[英]How can I calculate the correlation coefficients on the third dimension of an array?
说,我有一个三维数组,其中项目作为行,项目作为列,参与者作为第三维,共现计数值。 还要注意,每个数组“切片”(= item x item矩阵)都是对称的(因为它们是共存计数!)。
像这样:
a <- structure(c(17L, 1L, 0L, 1L, 1L, 17L, 0L, 1L, 0L, 0L, 17L, 0L, 1L, 1L, 0L, 17L, 16L, 0L, 0L, 1L, 0L, 16L, 0L, 0L, 0L, 0L, 16L, 0L, 1L, 0L, 0L, 16L, 18L, 1L, 2L, 3L, 1L, 18L, 1L, 2L, 2L, 1L, 18L, 0L, 3L, 2L, 0L, 18L), .Dim = c(4L, 4L, 3L), .Dimnames = structure(list(items = c("but-how", "encyclopedia", "alien", "comma"), items = c("but-how", "encyclopedia", "alien", "comma"), people = c("Julius", "Tashina", "Azra")), .Names = c("items", "items", "people")))
我现在想要参与者x参与者的相关系数矩阵,即Julius
, Tashina
和Azra
的相应系数。 为此,我只想关联两个矩阵中它们各自的单元,因此对于Azra
和Tashina
,我要关联它们各自的上(或下)三角形。
对我而言,如何执行此操作并不明显,因为cor()
和朋友不接受数组。
我可以通过下面的一些apply()
和upper.tri()
动作来破解它,但是我猜想必须有一种更有效,矩阵神奇的方式来做到这一点,对吗?
这是我现在执行此操作的方式。 不要笑
loosedat <- apply(X = a, MARGIN = c(3), FUN = function(x) {
x <- x[upper.tri(x = x, diag = FALSE)] # must kill diagonal, will otherwise inflate results
})
cor(loosedat)
让我得到我想要的东西,但是我觉得这很肮脏。
Julius Tashina Azra
Julius 1.0000000 0.4472136 0.522233
Tashina 0.4472136 1.0000000 0.700649
Azra 0.5222330 0.7006490 1.000000
怎么样
n <- dim(a)[3L] ## number of people
m <- dim(a)[1L] ## square table dimension
id <- dimnames(a)[[3L]] ## name of people
uptri <- upper.tri(diag(m)) ## upper triangular index
loosedat <- matrix(as.numeric(a)[uptri], ncol = n, dimnames = list(NULL, id))
# Julius Tashina Azra
#[1,] 1 0 1
#[2,] 0 0 2
#[3,] 0 0 1
#[4,] 1 1 3
#[5,] 1 0 2
#[6,] 0 0 0
cor(loosedat)
# Julius Tashina Azra
#Julius 1.0000000 0.4472136 0.522233
#Tashina 0.4472136 1.0000000 0.700649
#Azra 0.5222330 0.7006490 1.000000
您可以将上面的代码压缩为一行。 但是为了便于阅读,我采用了逐步的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.