Reputation: 145
The numpy version of hstack for a single matrix
c=np.array([[[2,3,4],[4,5,6]],[[20,30,40],[40,50,60]]])
np.hstack(c)
output:
array([[ 2, 3, 4, 20, 30, 40],
[ 4, 5, 6, 40, 50, 60]])
I am hoping to achieve the same behavior in TF.
c_t=tf.constant(c)
tf.stack(c_t,axis=1).eval()
I am getting the error
TypeError: Expected list for 'values' argument to 'pack' Op, not <tf.Tensor 'Const_14:0' shape=(2, 2, 3) dtype=int64>.
So I tried
tf.stack([c_t],axis=1).eval()
The output
array([[[[ 2, 3, 4],
[ 4, 5, 6]]],
[[[20, 30, 40],
[40, 50, 60]]]])
I am not looking for the behaviour. tf.reshape
and tf.concat
are not helping me either.
Upvotes: 2
Views: 619
Reputation: 61375
If you want to do it the manual way at the atomic level, then the below approach would as well work.
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]])
Upvotes: 1
Reputation: 221584
We can swap/permute axes and reshape -
tf.reshape(tf.transpose(c_t,(1,0,2)),(c_t.shape[1],-1))
Relevant - Intuition and idea behind reshaping 4D array to 2D array in NumPy
Upvotes: 2
Reputation: 6509
One way to make it work is first unstack the tensor into a list, and then concatenate the tensors in list on first axis:
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]])
Upvotes: 1