将千层面转换为Keras代码(CNN>LSTM)

2024-09-27 00:16:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想转换这个宽面条代码:

et = {}
net['input'] = lasagne.layers.InputLayer((100, 1, 24, 113))
net['conv1/5x1'] = lasagne.layers.Conv2DLayer(net['input'], 64, (5, 1))
net['shuff'] = lasagne.layers.DimshuffleLayer(net['conv1/5x1'], (0, 2, 1, 3))
net['lstm1'] = lasagne.layers.LSTMLayer(net['shuff'], 128)

在Keras代码中。现在我想到了这个:

^{pr2}$

但是我得到了一个错误:Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4


Tags: 代码inputnetlayersetlasagne面条ndim
1条回答
网友
1楼 · 发布于 2024-09-27 00:16:48

解决方案

from keras.layers import Input, Conv2D, LSTM, Permute, Reshape

multi_input = Input(shape=(1, 24, 113), name='multi_input')
print(multi_input.shape)  # (?, 1, 24, 113)

y = Conv2D(64, (5, 1), activation='relu', data_format='channels_first')(multi_input)
print(y.shape)  # (?, 64, 20, 113)

y = Permute((2, 1, 3))(y)
print(y.shape)  # (?, 20, 64, 113)

# This line is what you missed
# ==================================================================
y = Reshape((int(y.shape[1]), int(y.shape[2]) * int(y.shape[3])))(y)
# ==================================================================
print(y.shape)  # (?, 20, 7232)

y = LSTM(128)(y)
print(y.shape)  # (?, 128)

解释

我把千层面和Keras的文件放在这里,这样你就可以交叉引用了:

Lasagne

Recurrent layers can be used similarly to feed-forward layers except that the input shape is expected to be (batch_size, sequence_length, num_inputs)

Keras

Input shape

3D tensor with shape (batch_size, timesteps, input_dim).


基本上API是相同的,但是Lasagne可能会为您重新塑造(我需要稍后检查源代码)。所以你得到了这个错误:

^{pr2}$

,因为Conv2D后面的张量形状是ndim=4(?, 64, 20, 113)

因此,解决方案是将其重塑为(?, 20, 7232)。在

编辑

确认了千层面source code,它为您提供了窍门:

^{3}$

所以正确的张量形状作为LSTM的输入是(?, 20, 64 * 113)=(?, 20, 7232)


注意

Permute在Keras中是多余的,因为您无论如何都要重塑形状。我之所以把它放在这里的原因是有一个“完整的翻译”从宽面条到Keras,它做了DimshuffleLaye在宽面条中的作用。在

然而,宽面条需要DimshuffleLaye,因为我在编辑中提到的原因,宽面条LSTM创建的新维度来自于“最后两个”维度的乘法。在

相关问题 更多 >

    热门问题