首页 > 解决方案 > 如何处理 keras 中的批量输入?

问题描述

我有一个接受形状输入(None,128,128,1)(灰度图像)训练的 CNN。我想在另一个模型中使用这个模型权重作为基础来提取特征(不训练第一个模型),[(None,128,128,10), (None,10,8)]这里接受两个形状输入10是单个样本中的图像数量。基本上它接受10shape 的图像(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])

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

标签: pythonkerasconv-neural-network

解决方案


假设你最后想要一个[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)

推荐阅读