我有一个案例,两个具有特定维度的矩阵的矩阵乘法在 numpy 中有效,但在 tensorflow 中无效。

x = np.ndarray(shape=(10,20,30), dtype = float) 
y = np.ndarray(shape=(30,40), dtype = float) 
z = np.matmul(x,y) 
print("np shapes: %s x %s = %s" % (np.shape(x), np.shape(y), np.shape(z))) 

这按预期工作并打印:

np shapes: (10, 20, 30) x (30, 40) = (10, 20, 40) 

但是在 tensorflow 中,当我尝试乘以与上面的 numpy 数组相同形状的占位符和变量时,我得到一个错误

x = tf.placeholder(tf.float32, shape=(10,20,30)) 
y = tf.Variable(tf.truncated_normal([30,40], name='w')) 
print("tf shapes: %s x %s" % (x.get_shape(), y.get_shape())) 
tf.matmul(x,y) 

结果

tf shapes: (10, 20, 30) x (30, 40) 
InvalidArgumentError:  
Shape must be rank 2 but is rank 3 for 'MatMul_12'  
(op: 'MatMul') with input shapes: [10,20,30], [30,40]. 

为什么这个操作会失败?

请您参考如下方法:

不知道为什么 tf.matmul 不支持这种乘法(可能是核心开发人员之一可以提供有意义的答案)。

但是,如果您只是想以这种方式乘以张量,请查看 tf.einsum功能。它可以处理任意阶的张量。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

python - 在 python 中以相反的顺序柯里化(Currying)