【问题标题】:How to build a pretrained CNN-LSTM network with Keras如何使用 Keras 构建预训练的 CNN-LSTM 网络
【发布时间】:2019-09-27 16:23:27
【问题描述】:

我正在尝试使用带有 Keras 的 CNN-LSTM 网络来分析视频。我阅读了它并遇到了TimeDistributed 函数和一些示例。

实际上,我尝试了下面描述的网络,它实际上是由卷积层和池化层,然后是循环层和密集层组成。

model = Sequential()
model.add(TimeDistributed(Conv2D(2, (2,2), activation= 'relu' ), input_shape=(None, IMG_SIZE, IMG_SIZE, 3)))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(50))
model.add(Dense(50, activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam' , metrics = ['acc'])

我没有正确测试模型,因为我的数据集太小。然而,在训练过程中,网络在 4-5 个 epoch 内达到 accuracy 0.98(可能是过度拟合,但现在还不是问题,因为我希望以后能得到一个合适的数据集)。

然后,我阅读了如何使用预训练的卷积网络(MobileNet、ResNet 或 Inception)作为 LSTM 网络的特征提取器,因此我使用了以下代码:

inputs = Input(shape = (frames, IMG_SIZE, IMG_SIZE, 3))
cnn_base = InceptionV3(include_top = False, weights='imagenet', input_shape = (IMG_SIZE, IMG_SIZE, 3))

cnn_out = GlobalAveragePooling2D()(cnn_base.output)
cnn = Model(inputs=cnn_base.input, outputs=cnn_out)
encoded_frames = TimeDistributed(cnn)(inputs)
encoded_sequence = LSTM(256)(encoded_frames)

hidden_layer = Dense(1024, activation="relu")(encoded_sequence)
outputs = Dense(50, activation="softmax")(hidden_layer)
model = Model([inputs], outputs)

在这种情况下,在训练模型时,它总是显示准确度 ~0.02(它是基线的 1/50)。

由于第一个模型至少学到了任何东西,我想知道在第二种情况下网络的构建方式是否有任何错误。

有人遇到过这种情况吗?有什么建议吗?

谢谢。

【问题讨论】:

  • 由于您的数据集较小,您应该尝试冻结 InceptionV3 的某些层。剩下的层将学习这些特征并产生更好的准确性。

标签: tensorflow keras conv-neural-network recurrent-neural-network


【解决方案1】:

原因是您的数据量非常少,需要重新训练完整的 Inception V3 权重。要么你必须用更多的数据来训练模型,要么用更多的 epoch 和超参数调整来训练模型。你可以找到更多关于超参数训练的信息here

理想的方法是通过base_model.trainable = False 冻结基础模型,然后只训练您在 Inception V3 层之上添加的新层。

解冻基础模型的顶层(Inception V3 层)并将底层设置为不可训练。您可以按以下方式进行 -

# Let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(base_model.layers))

# Fine-tune from this layer onwards
fine_tune_at = 100

# Freeze all the layers before the `fine_tune_at` layer
for layer in base_model.layers[:fine_tune_at]:
  layer.trainable =  False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多