结合 CNN 和 LSTM

时间:2021-04-08 22:01:57

标签: python tensorflow keras neural-network tflearn

我希望将 RNN 与 CNN 一起实现,以便基于两张图像而不是单独使用 CNN 进行预测。 我正在尝试修改 alexnet 模型代码:

def alexnet(width, height, lr, output=3):
    network = input_data(shape=[None, width, height, 1], name='input')
    network = conv_2d(network, 96, 11, strides=4, activation='relu')
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 256, 5, activation='relu')
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 384, 3, activation='relu')
    network = conv_2d(network, 384, 3, activation='relu')
    network = conv_2d(network, 256, 3, activation='relu')
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = fully_connected(network, 4096, activation='tanh')
    network = dropout(network, 0.5)
    network = fully_connected(network, 4096, activation='tanh')
    network = dropout(network, 0.5)
    network = fully_connected(network, output, activation='softmax')
    network = regression(network, optimizer='momentum',
                         loss='categorical_crossentropy',
                         learning_rate=lr, name='targets')

    model = tflearn.DNN(network, checkpoint_path='model_alexnet',
                        max_checkpoints=1, tensorboard_verbose=0, tensorboard_dir='log')

    return model

我的图像在一个 np 数组中,其中每个元素都是一个图像的像素数据。我在使用 RNN 实现使用两个图像的功能时遇到问题。

我已经看到了 tflearn 的 reshape 和 lstm 方法,我认为它们应该放在最终的完全连接层之前,但不确定如何指定要使用的图像数量。

另外,使用 Keras 会更容易实现吗?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要执行以下操作。设 model 为网络,将一系列图像作为输入并返回预测。使用功能 API,其示意图如下所示:

    def create_model():
        input_data = keras.Input(shape=(number-of-images,shape-of-images))
        ### processing part ###
        model = keras.Model(input_images, your-predictions)
        return model
    model = create_model()

processing part 中,您希望获得每个图像的编码,然后使用 RNN 将它们分析为一个序列。

作为第一步,您需要获取所有图像的编码。让 encoder 成为为单个图像进行编码的网络,返回 enc_dim 维编码。为了有效地获得所有图像的编码,请注意在训练期间 model 处理形状为 (batch-size,number-of-images,shape-of-images) 的数据。因此,您总共拥有 total-number-of-images=(batch-size) x (number-of-images) 个图像。要处理它们,请将 input_data 整形为具有尺寸 (total-number-of-images,shape-of-images),如下所示:

    input_data_reshaped = tf.reshape(input_data, (-1,shape-of-images)),

并通过 encoder 传递它们:

    image_encodings_flatterned = encoder(input_data_reshaped).

这将产生 (total-number-of-images,enc_dim) 形式的输出。要处理编码,您需要恢复batch-size 维度。这很容易做到:

    image_encodings = tf.reshape(image_encodings_flatterned, (-1,number-of-images,enc_dim))

正如预期的那样,它将数据重塑为(batch-size,number-of-images,enc_dim)。这些数据可以很容易地由 RNN 层或其组合处理。例如,对于单个 LSTM 层,

    rnn_analyzer = tf.keras.layers.LSTM(parameters)

预测结果如下:

    rnn_encodings = rnn_analyzer(image_encodings).

rnn_encodings 可以被密集层进一步用于进行最终预测。

将上述内容放在 processing partmodel 中,您将达到目标。