首页 > 解决方案 > 如何在张量流中用 3d 张量对 2d 张量进行 matmul?

问题描述

numpy您可以将 2d 数组与 3d 数组相乘,如下例所示:

>>> X = np.random.randn(3,5,4) # [3,5,4]
... W = np.random.randn(5,5) # [5,5]
... out = np.matmul(W, X) # [3,5,4]

据我了解np.matmul()W沿X. 但在tensorflow其中是不允许的:

>>> _X = tf.constant(X)
... _W = tf.constant(W)
... _out = tf.matmul(_W, _X)

ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_1' (op: 'MatMul') with input shapes: [5,5], [3,5,4].

那么np.matmul()上面的内容是否有等价物tensorflowtensorflow将 2d 张量与 3d 张量相乘的最佳做法是什么?

标签: pythontensorflow

解决方案


在乘法之前尝试使用tf.tile来匹配矩阵的维度。numpy 的自动广播功能似乎没有在tensorflow 中实现。您必须手动完成。

W_T = tf.tile(tf.expand_dims(W,0),[3,1,1])

这应该可以解决问题

import numpy as np
import tensorflow as tf

X = np.random.randn(3,4,5)
W = np.random.randn(5,5)

_X = tf.constant(X)
_W = tf.constant(W)
_W_t = tf.tile(tf.expand_dims(_W,0),[3,1,1])

with tf.Session() as sess:
    print(sess.run(tf.matmul(_X,_W_t)))

推荐阅读