Nip*_*tra 4 python numpy matrix matrix-multiplication tensorflow
我试图在NumPy/Tensorflow中执行张量乘法.
我有3个张量 - A (M X h), B (h X N X s), C (s X T)
.
我认为A X B X C
应该产生张量D (M X N X T)
.
这是代码(使用numpy和tensorflow).
M = 5
N = 2
T = 3
h = 2
s = 3
A_np = np.random.randn(M, h)
C_np = np.random.randn(s, T)
B_np = np.random.randn(h, N, s)
A_tf = tf.Variable(A_np)
C_tf = tf.Variable(C_np)
B_tf = tf.Variable(B_np)
# Tensorflow
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(A_tf)
p = tf.matmul(A_tf, B_tf)
sess.run(p)
Run Code Online (Sandbox Code Playgroud)
这将返回以下错误:
ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_2' (op: 'MatMul') with input shapes: [5,2], [2,2,3].
Run Code Online (Sandbox Code Playgroud)
如果我们只使用numpy矩阵尝试乘法,我们会得到以下错误:
np.multiply(A_np, B_np)
ValueError: operands could not be broadcast together with shapes (5,2) (2,2,3)
Run Code Online (Sandbox Code Playgroud)
但是,我们可以使用np.tensordot
如下:
np.tensordot(np.tensordot(A_np, B_np, axes=1), C_np, axes=1)
Run Code Online (Sandbox Code Playgroud)
在TensorFlow中是否有相同的操作?
在numpy,我们会做如下:
ABC_np = np.tensordot(np.tensordot(A_np, B_np, axes=1), C_np, axes=1)
Run Code Online (Sandbox Code Playgroud)
在tensorflow中,我们将执行以下操作:
AB_tf = tf.tensordot(A_tf, B_tf,axes = [[1], [0]])
AB_tf_C_tf = tf.tensordot(AB_tf, C_tf, axes=[[2], [0]])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
ABC_tf = sess.run(AB_tf_C_tf)
Run Code Online (Sandbox Code Playgroud)
np.allclose(ABC_np, ABC_tf)
回来True
.
尝试
tf.tensordot(A_tf, B_tf,axes = [[1], [0]])
Run Code Online (Sandbox Code Playgroud)
例如:
x=tf.tensordot(A_tf, B_tf,axes = [[1], [0]])
x.get_shape()
TensorShape([Dimension(5), Dimension(2), Dimension(3)])
Run Code Online (Sandbox Code Playgroud)
这是tensordot文档,这里是相关的github存储库.