keras 实现包括batch size所在维度的reshape,使用backend新建一层 针对多输入使用不同batch size折衷解决办法

新建层,可以在此层内使用backend完成想要的功能,如包含batch size维度在内的reshpe:

def backend_reshape(x):
    return backend.reshape(x, (-1, 5, 256))

使用lambda方法调用层:

vision_model.add(Lambda(backend_reshape, output_shape=(5, 256)))

注意指定输出维度

在多输入问题中,有时两个输入具有不同的batch size,但在keras无法直接实现。我所遇到的问题是,我有两个输入分别是图像输入和问题输入,对于图像输入每个样本是一个图像序列。这就要求我们在把图像序列输入到CNN中时是一张一张图像。

我的解决办法是在输入是把图像序列作为一个样本,等输入进去后,通过上述的reshape方法将图像序列重新拆分成一张张图像输入到CNN,然后在后期处理时重新reshape成一个序列样本。代码:

image_seq = 4
def preprocess_reshape(x):
    return K.reshape(x, (-1, 224, 224,3))

def backend_reshape(x):
    return K.reshape(x, (-1, image_seq, 256))
image_input = Input(shape=(image_seq, 224, 224, 3) , name='input_img')
image_re = Lambda(preprocess_reshape, output_shape=(224,224,3))(image_input)
im_pre = Lambda(preprocess_input, name='preprocessing')(image_re)
vision_model.add(Lambda(backend_reshape, output_shape=(image_seq, 256)))
vision_model.add(LSTM(256, kernel_regularizer=l2, recurrent_regularizer=l2))

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/82528731
今日推荐