How to init None shape for output tensor in Tensorflow custom layer?

Viewed 517

I have custom layer:

  class ConvCustom(tf.keras.layers.Layer):
        def __init__(self, kernel):
            super(ConvCustom, self).__init__()
            self.w = tf.convert_to_tensor(kernel, dtype=tf.float32)

    def call(self, inputs):
        np_res = np.zeros((1, 24, FEATURE_MAP_HEIGHT, FEATURE_MAP_WIDTH))

        if (inputs.shape[0] == None):
            self.result = tf.convert_to_tensor(np_res, dtype=tf.float32) # TODO How to build Tensor with None shape?
            return self.result

        size = inputs.shape[0]

        np_res = np.zeros((size, 24, FEATURE_MAP_HEIGHT, FEATURE_MAP_WIDTH))

        for dim in range(0, size):
            for i in range(0,24):
                new_kernel = self.__recombinate_kernel(self.w, i)
                np_res[dim, i,:,:] = tf.math.multiply(inputs[dim, :, :], new_kernel)


        self.result = tf.convert_to_tensor(np_res, dtype=tf.float32)

        return self.result

    def __recombinate_kernel(self, kernel, i):
        k_n = np.zeros((FEATURE_MAP_HEIGHT, FEATURE_MAP_WIDTH))

        for l in range(0, 24):
            j = l

            sh_1 = j + (12 - i)
            sh_2 = j - (12 + i)

            if j < 12:
                k_n[:, j] = kernel[:, sh_1]
            else: 
                k_n[:, j] = kernel[:, sh_2]


        return k_n

inp = tf.keras.layers.Input(shape=(90,24))
conv = ConvCustom(all_medians_parall)(inp)

test_model = tf.keras.models.Model(inp, conv)

test_model.summary()

It produce output:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_42 (InputLayer)        [(None, 90, 24)]          0         
_________________________________________________________________
conv_custom_56 (ConvCustom)     (1, 24, 90, 24)           0         
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0

Custom layer get (None, 90, 24) shape without fitting and I need that output shape to be contains None shape too: (None, 24, 90, 24) instead (1, 24, 90, 24) How to do it? I not found solution for creating Tensor with None shape.

1 Answers

I think you can use

tf.shape(inputs)[0]

instead of

inputs.shape[0]

to get the actual size of the batch when processing it, eliminating the need to deal with None.

Related