如何在Tensorflow自定义层中为输出张量初始化None形状?

时间:2020-05-19 07:44:37

标签: tensorflow tensorflow2.0 keras-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()

它产生输出:

_________________________________________________________________
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

自定义层获取不适合的(None,90,24)形状,我也需要该输出形状也包含None形状:(None,24,90,24)代替(1、24、90、24) 怎么做?我找不到创建无形状Tensor的解决方案。

1 个答案:

答案 0 :(得分:0)

我认为您可以使用

tf.shape(inputs)[0]

代替

inputs.shape[0]

在处理批次时获得批次的实际大小,从而无需处理None。