reshape tensor between two layers

144 views Asked by At

I have a neural network in which I built my own layer and it gives result with the shape A = [10, 5].

I want to feed the result to another layer which takes input with shape B = [10, 9, 5].

The input B is based on the previous result A, for example, selecting 9 different rows from A for 10 times,making a new tensor with the shape [10, 9, 5].

Is there a way to do that?

2

There are 2 answers

2
prometeu On

Convert the tensor A (output of the layer) into a numpy array with:

a=sess.run(A.eval())

For the sake of the example I'll use:

a=np.random.uniform(0,5,[10])

Then:

#choose wich element will be left out
out = np.random.randint(5, size=[10])

#array of different output layers without one random element
b=[]
for i in range(10):
  b.append(np.delete(a,out[i]))

#Stack them all together
B = tf.stack(b[:])
1
Tianjin Gu On

for loop will do:

a = tf.constant([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

tensor_list = []
pick_times = 3
for i in range(pick_times):
    pick_rows = [j  for j in range(pick_times) if i != j]
    tensor_list.append(tf.gather(a, pick_rows))

concated_tensor = tf.concat(tensor_list, 0)
result = tf.reshape(concated_tensor, [3, 2, 3])