Barry Barry - 9 months ago 54
Python Question

How do I split a tensor and then concatenate it?

My input data is of the form [None, 2, 100], basically I have a bunch of 2 cell arrays that each contain vectors of size 100. I want to run each vector through a separate input layer, and after that layer concatenate the results into one vector.

My questions are as follows:
Given a tensor of shape [None, 2, 100], how do I transform it to be of size [None, 100]?
Then, give two tensors, of size [None, 50], how do I concatenate them to be of size [None, 100]?

Thanks in advance.

Answer Source
  1. You can use numpy-like indexing, tf.slice or tf.unpack

    c = tf.placeholder(tf.int32, shape=[None, 2, 100])
    d = c[:,0,:]
    e = tf.squeeze(tf.slice(c, [0,1,0], [-1, 1, -1]), squeeze_dims=[1])
    [d, e] = tf.unpack(c, axis=1)
  2. concatenation:

    a = tf.placeholder(tf.int32, shape=[None, 50])
    b = tf.placeholder(tf.int32, shape=[None, 50])
    tf.concat(1, [a,b]).get_shape()
    TensorShape([Dimension(None), Dimension(100)])