How to stack (None,1024) tensor into (None,7,7,1024) tensor in keras?

Viewed 105

I have a tensor A of shape (None,1024) and I want to repeat it 49 times to make a matrix tensor of shape (None,7,7,1024). Every (,1024) vector is a copy of the tensor A.

How do I do this?

I tried

A = K.stack([A,A,A,A,A,A,A])
A = K.stack([A,A,A,A,A,A,A])

But this gives me a tensor of shape (7, 7, None, 1024)

1 Answers

First use RepeatVector layer to repeat it for 49 times, then use Reshape layer to reshape it as desired:

r_A = RepeatVector(49)(A)
rsh_A = Reshape((7, 7, -1))(r_A)

Alternatively, you can define a function based on backend functions and wrap it inside a Lambda layer:

from keras import backend as K

def rsh(x):
    y = K.repeat(x, 49)
    return K.reshape(y, (-1, 7, 7, K.int_shape(y)[-1]))

rsh_A = Lambda(rsh)(A)
Related