如何知道keras中的特定层索引

时间:2018-08-11 12:27:09

标签: keras

在我在喀拉拉邦的CNN模型中,我想知道特定层的层数或索引,例如卷积层的索引。 model.summary()将告诉模型细节,而model.layer将告诉模型层。例如,我的模型如下:

model.add(Conv2D(32,(2,2),input_shape=input_shape,activation='linear'))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha=.1))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Conv2D(32, (2,2),activation='linear'))

然后在上述模型Conv2D层索引中为0和5。这是我想知道的事情。

1 个答案:

答案 0 :(得分:1)

每一层的索引就是model.layers中该层的索引。如果您明确需要它,可以使用dict comprehensions创建映射:

{i: v for i, v in enumerate(model.layers)}

给予

{0: <keras.layers.convolutional.Conv2D at 0x7f182bcd1710>,
 1: <keras.layers.normalization.BatchNormalization at 0x7f1840981828>,
 2: <keras.layers.advanced_activations.LeakyReLU at 0x7f184154b5c0>,
 3: <keras.layers.pooling.MaxPooling2D at 0x7f184154be10>,
 4: <keras.layers.core.Dropout at 0x7f184154be80>,
 5: <keras.layers.convolutional.Conv2D at 0x7f18800593c8>}

反之亦然:

{v: i for i, v in enumerate(model.layers)}

给予

{<keras.layers.convolutional.Conv2D at 0x7f182bcd1710>: 0,
 <keras.layers.normalization.BatchNormalization at 0x7f1840981828>: 1,
 <keras.layers.advanced_activations.LeakyReLU at 0x7f184154b5c0>: 2,
 <keras.layers.pooling.MaxPooling2D at 0x7f184154be10>: 3,
 <keras.layers.core.Dropout at 0x7f184154be80>: 4,
 <keras.layers.convolutional.Conv2D at 0x7f18800593c8>: 5}

如果为图层指定显式名称,则可能更有用:

model = Sequential()
model.add(Conv2D(32,(2,2),input_shape=(32,32,3),activation='linear', name='one'))
model.add(BatchNormalization(name='second'))
model.add(LeakyReLU(alpha=.1, name='third'))
model.add(MaxPooling2D(pool_size=(2, 2), name='four'))
model.add(Dropout(0.1, name='five'))
model.add(Conv2D(32, (2,2),activation='linear', name='six'))
dictionary = {v.name: i for i, v in enumerate(model.layers)}

给予

{'one': 0, 'second': 1, 'third': 2, 'four': 3, 'five': 4, 'six': 5}

您可以用来按层名称查找层的索引。