![](/img/trans.png)
[英]Why does numpy.linalg.eig not satisfy "matrix dot eigen vector = eigen value dot eigen vector"?
[英]Eigen Contraction vs Numpy Dot
大家好,我在Numpy中具有以下张量点积:
import numpy as np
tensorA = np.array([[[1,2,3],
[4,5,6],
[7,8,9]],
[[10,11,12],
[13,14,15],
[16,17,18]],
[[19,20,21],
[22,23,24],
[25,26,27]]])
tensorB = np.array([[1,2],
[1,2],
[1,2]])
print tensorA.dot(tensorB)
它给出以下答案:
[[[ 6 12]
[ 15 30]
[ 24 48]]
[[ 33 66]
[ 42 84]
[ 51 102]]
[[ 60 120]
[ 69 138]
[ 78 156]]]
但是,当我在C ++ Eigen中执行相同的操作时:
Eigen::Tensor<float, 3> tensorA(3,3,3);
tensorA.setValues({{{1,2,3},
{4,5,6},
{7,8,9}},
{{10,11,12},
{13,14,15},
{16,17,18}},
{{19,20,21},
{22,23,24},
{25,26,27}}});
Eigen::Tensor<float, 2> tensorB(3,2);
tensorB.setValues({{1,2},
{1,2},
{1,2}});
// Compute the traditional matrix product
Eigen::array<Eigen::IndexPair<float>, 1> product_dims = { Eigen::IndexPair<float>(0, 1) };
Eigen::Tensor<float, 3> AB = tensorA.contract(tensorB, product_dims);
我得到:
D: 3 R: 3 C: 2
[[12.000 24.000 ]
[15.000 30.000 ]
[18.000 36.000 ]
]
R: 3 C: 2
[[39.000 78.000 ]
[42.000 84.000 ]
[45.000 90.000 ]
]
R: 3 C: 2
[[66.000 132.000 ]
[69.000 138.000 ]
[72.000 144.000 ]
]
为什么会这样呢? 我想要一个等于numpy给我的张量点积。 与c ++中的product_dims参数有关吗? 还是涉及其他错误? 基本上,它需要将深度分量乘以3倍。
我无法为您提供C ++代码,但是我可以用麻木的方式确定发生了什么:
In [1]: A=np.arange(1,28).reshape(3,3,3)
In [3]: A
Out[3]:
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])
In [5]: B=np.repeat([[1,2]],3, axis=0)
In [6]: B
Out[6]:
array([[1, 2],
[1, 2],
[1, 2]])
您的句点-记住A的末尾和B的第二末尾:
In [7]: A.dot(B)
Out[7]:
array([[[ 6, 12],
[ 15, 30],
[ 24, 48]],
[[ 33, 66],
[ 42, 84],
[ 51, 102]],
[[ 60, 120],
[ 69, 138],
[ 78, 156]]])
使用einsum
索引,这一点很清楚(至少对我而言):
In [8]: np.einsum('ijk,kl',A,B) # notice the k pair
Out[8]:
array([[[ 6, 12],
[ 15, 30],
[ 24, 48]],
[[ 33, 66],
[ 42, 84],
[ 51, 102]],
[[ 60, 120],
[ 69, 138],
[ 78, 156]]])
但是,如果我将einsum
更改为einsum
都使用第二个,则我会得到您的c ++结果(我认为):
In [9]: np.einsum('ijk,jl',A,B) # notice the j pair
Out[9]:
array([[[ 12, 24],
[ 15, 30],
[ 18, 36]],
[[ 39, 78],
[ 42, 84],
[ 45, 90]],
[[ 66, 132],
[ 69, 138],
[ 72, 144]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.