numpy的矩阵和张量乘法

时间:2018-11-06 06:24:20

标签: python numpy

我正在尝试使用张量进行矩阵乘法,但是我不确定如何使用Numpy进行乘法。我一直在尝试与np.tensordot()合作,但未能成功

以一种更简单的方式,如果我们要进行矩阵乘法,并且有一个向量v(Nx1)和一个矩阵S(NxN),我们就可以进行运算

v ^ TS V =>(1xN)(NxN)(Nx1)=>一个数字

v = np.ones((3,1))
S = np.ones((3,3))
y = v.T.dot(S).dot(v)
y.shape = (1) or ()

现在,我要执行以下操作:

让矩阵M(3x5)和张量Z(5x3x3)可以使我拥有
M ^ T Z M
其中(M ^ T Z)产生一个(5x3)矩阵,而M ^ T Z M产生一个(1x5)向量

M = np.ones((3,5))
Z = np.ones((5,3,3))
Y = <?> M.T * Z * M <?>
Y.shape = (5,) or (1,5)

有人知道如何在不使用Tensorflow的情况下使用Numpy吗?

1 个答案:

答案 0 :(得分:0)

我认为这可以计算出您想要的:

import numpy as np

M = np.ones((3, 5))
Z = np.ones((5, 3, 3))
# Multiply (5, 1, 3) x (5, 3, 3) x (5, 3, 1)
result = (M.T[:, np.newaxis] @ Z @ M.T[:, :, np.newaxis]).squeeze()
print(result)

输出:

[9. 9. 9. 9. 9.]

为了方便起见,我使用了@运算符,但是如果您更喜欢它或使用的是旧版Python,则可以将其替换为np.matmul

result = np.matmul(np.matmul(M.T[:, np.newaxis], Z), M.T[:, :, np.newaxis]).squeeze()