gpt4 book ai didi

python - R 相当于 Python 的 3D 数组的 np.dot

转载 作者:行者123 更新时间:2023-11-28 20:37:41 29 4
gpt4 key购买 nike

我正在将一些涉及 3D 矩阵的代码从 Python 翻译成 R。这很棘手,因为我对 Python 或矩阵代数知之甚少。总之,在 Python 代码中我有一个矩阵 dot.product,如下所示:np.dot(A, B)。矩阵 A 的维度为 (10, 4),而 B 的维度为 (2, 4, 2)。 (这些尺寸可能会有所不同,但始终会在第二个维度上匹配)。所以 np.dot 从文档中看没有问题:

"For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:"

因此它沿 A=4 的第二个轴和 B=4 的中间轴相乘并输出一个 (10,2,2) 矩阵。 => 没问题。然而在 R 中,%*% 没有这种行为并抛出“不一致数组”错误。

r 中的玩具示例:

A <- matrix( rnorm(10*4), nrow=10, ncol=4)
B <- array( rnorm(2*4*2), c(2,4,2))
A %*% B
Error in A %*% B : non-conformable arrays

如何解决这个问题以实现与 np.dot 相同的计算?

最佳答案

我们可以使用 aperm()tensor::tensor 来做到这一点。使用@SandipanDey 的示例。

设置数组(你需要aperm来获取合适的B,我在这里称之为B2):

A <- matrix(0:39,ncol=4,byrow=TRUE)
B <- array(0:15,dim=c(2,4,2))
B2 <- aperm(B,c(2,1,3),resize=TRUE)

tensor::tensor 进行了正确的计算,但我们需要 reshape 结果:

library(tensor)
C <- tensor(A,B2,2,1)
aperm(C,c(3,2,1),resize=TRUE)

关于python - R 相当于 Python 的 3D 数组的 np.dot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158198/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com