单个 matrix/tensor 的 tensorflow 上 numpy 的 hstack

numpy's hstack on tensorflow for a single matrix/tensor

单个矩阵的 hstack 的 numpy 版本

c=np.array([[[2,3,4],[4,5,6]],[[20,30,40],[40,50,60]]])

np.hstack(c)

输出:

array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])

我希望在 TF 中实现相同的行为。

c_t=tf.constant(c)
tf.stack(c_t,axis=1).eval()

我遇到错误

TypeError: Expected list for 'values' argument to 'pack' Op, not <tf.Tensor 'Const_14:0' shape=(2, 2, 3) dtype=int64>.

所以我尝试了

tf.stack([c_t],axis=1).eval()

输出

array([[[[ 2,  3,  4],
         [ 4,  5,  6]]],


       [[[20, 30, 40],
         [40, 50, 60]]]])

我不是在寻找行为。 tf.reshapetf.concat 也没有帮助我。

使其工作的一种方法是首先将张量拆分为列表,然后在第一个轴上连接列表中的张量:

new_c = tf.concat(tf.unstack(c_t), axis=1)
sess.run(new_c)

array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])

我们可以 swap/permute 轴并重塑 -

tf.reshape(tf.transpose(c_t,(1,0,2)),(c_t.shape[1],-1))

相关 -

如果您想在原子级别手动执行此操作,那么以下方法也可以。

In [132]: c=np.array([[[2,3,4],[4,5,6]],[[20,30,40],[40,50,60]]])
In [133]: tfc = tf.convert_to_tensor(c) 

In [134]: slices = [tf.squeeze(tfc[:1, ...]), tf.squeeze(tfc[1:, ...])]  
In [135]: stacked = tf.concat(slices, axis=1) 
In [136]: stacked.eval()           
Out[136]: 
array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])