【问题标题】:How to treat batch of inputs in keras?如何处理 keras 中的批量输入?
【发布时间】:2021-05-28 03:57:26
【问题描述】:

我有一个接受形状(None,128,128,1)(灰度图像)输入训练的 CNN。我想在另一个模型中使用这个模型权重作为基础来提取特征(不训练第一个模型),它接受两个形状为[(None,128,128,10), (None,10,8)] 的输入,这里10 是单个样本中的图像数量。 基本上它接受10 形状(128,128) 的图像。我将每个图像视为通道,因为 keras 中的 Conv 层接受 4D 输入。

我的模型看起来像这样

def create_model():

    trajectory_input = Input(shape=(10, 8), name='trajectory_input')
    image_input  = Input(shape=(128, 128, 10), name='image_input')
    
    x_aware = (Conv2D(32, kernel_size=(3, 3), weights=model1_weights, activation='relu'))(image_input)

    x = concatenate([trajectory_input , x_aware])
    x_reg = (Dense(8, activation='relu', kernel_regularizer=regularizers.l2(0.001)))(x)
    model = Model(inputs=[trajectory_input, image_input], outputs=[x_reg])

在从模型 1(此处为 x_aware 层)提取特征时,keras 中是否有任何方法可以将此单个样本视为一批图像而不是单个样本?

【问题讨论】:

    标签: python keras conv-neural-network


    【解决方案1】:

    假设您最后想要一个 [None, 126, 126, 32, 10] 大小的张量,您需要为此定义一个自定义层。

    class CustomLayer(tf.keras.layers.Layer):
    
      def __init__(self, conv_layer):
        super(CustomLayer, self).__init__()
        self.conv_layer = conv_layer
    
      def build(self, input_shape):
        pass
      
      def call(self, x):
        return tf.stack([self.conv_layer(tf.expand_dims(t, axis=-1)) for t in tf.unstack(x, axis=-1)], axis=-1)
    

    并将其称为,

    x_aware = CustomLayer(conv_layer)(image_input)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      相关资源
      最近更新 更多