由于isinstance函数出现问题,我们可以使用Names of Layers来解决这个问题。
例如,让我们使用以下代码构建一个简单的模型:
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Dropout, Input
from tensorflow import keras
x = Input(shape=(32,))
y = Dense(16, activation='softmax')(x)
model = Model(x, y)
让我们使用命令model.summary() 来验证架构,如下所示:
Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 32)] 0
_________________________________________________________________
dense_1 (Dense) (None, 16) 528
=================================================================
Total params: 528
Trainable params: 528
Non-trainable params: 0
如果我们观察层的名称,Input Layer 有一个前缀 input。
或者换句话说,代码,
print('Name of First Layer is ', layers[0].name)
print('Name of Second Layer is ', layers[1].name)
结果
Name of First Layer is input_2
Name of Second Layer is dense_1
所以,我们可以修改我们的逻辑如下图:
layers = model.layers
inputs = []
outputs = []
for layer in layers:
# Check if a Layer is an Input Layer using its name
if 'input' in layer.name:
inputs.append(layer)
else:
outputs.append(layer)
print('Inputs List is ', inputs)
print('Outputs List is ', outputs)
以上代码的输出为:
Inputs List is [<tensorflow.python.keras.engine.input_layer.InputLayer object at 0x7fef788154e0>]
Outputs List is [<tensorflow.python.keras.layers.core.Dense object at 0x7fef78845fd0>]
希望这会有所帮助。快乐学习!