【问题标题】:Combining CNN with LSTM using Tensorflow Keras使用 Tensorflow Keras 将 CNN 与 LSTM 相结合
【发布时间】:2019-03-02 16:22:34
【问题描述】:

我正在使用预训练的 ResNet-50 模型,并希望将倒数第二层的输出提供给 LSTM 网络。这是我只包含 CNN (ResNet-50) 的示例代码:

N = NUMBER_OF_CLASSES
#img_size = (224,224,3)....same as that of ImageNet    
base_model = ResNet50(include_top=False, weights='imagenet',pooling=None)
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(1024, activation='relu')(x)
model = Model(inputs=base_model.input, outputs=predictions)

接下来,我想把它喂给一个LSTM网络,如下...

final_model = Sequential()
final_model.add((model))
final_model.add(LSTM(64, return_sequences=True, stateful=True))
final_model.add(Dense(N, activation='softmax'))

但我很困惑如何将输出重塑为 LSTM 输入。我的原始输入是 (224*224*3) 到 CNN。 另外,我应该使用 TimeDistributed 吗?

感谢任何形式的帮助。

【问题讨论】:

  • 您是否使用 imageDataGenerator 来准备图像序列?
  • @TheJokerAEZ 不,我没有使用 ImageDataGenerator。改为使用预先保存的路径...

标签: python tensorflow neural-network keras lstm


【解决方案1】:

在 CNN 之后添加 LSTM 没有多大意义,因为 LSTM 主要用于时间/序列信息,而您的数据似乎只是空间数据,但是如果您仍然喜欢使用它,只需使用它

x = Reshape((1024,1))(x)

这会将其转换为具有 1 个特征的 1024 个样本序列

如果你说的是时空数据,在 Resnet 层上使用Timedistributed,然后你可以使用convlstm2d

【讨论】:

  • 谢谢,你给我指明了方向......你的第一个建议很完美,但我正在考虑你所说的事实 - 这没有多大意义。事实上,是的,我有时空数据。但是我该如何使用TimeDistributed,请您详细说明一下我的理解。我在link 看到了这个答案。响应建议“复制 ResNet 的代码并将 TimeDistributed 添加到所有层,然后从我定制的 ResNet 上的“基本”ResNet 加载权重。”那我应该执行这个吗?
  • 没错,类似input_layer = Input(shape); base_model = ResNet50(weights='imagenet', include_top=False); x = TimeDistributed(base_model)(input_layer); x = convlstm2d(params)(x);....; x = TimeDistributed(Dense(N))(x);
【解决方案2】:

将预训练网络与 LSTM 结合使用的示例:

inputs = Input(shape=(config.N_FRAMES_IN_SEQUENCE, config.IMAGE_H, config.IMAGE_W, config.N_CHANNELS))
cnn = VGG16(include_top=False, weights='imagenet', input_shape=(config.IMAGE_H, config.IMAGE_W, config.N_CHANNELS))
x = TimeDistributed(cnn)(inputs)
x = TimeDistributed(Flatten())(x)
x = LSTM(256)(x)

【讨论】:

  • 你测试过这个吗?它返回一个尺寸错误。 VGG16 期望输入形状为 (batch_size, width, height, dimension),而 LSTM 期望一个序列 (batch_size,timestep, width, height, dimension)。我现在正面临这个问题。
猜你喜欢
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2017-06-17
  • 2016-10-19
相关资源
最近更新 更多