isinstance()以检查张量上的Keras层类型

问题描述 投票:1回答:1

我得到模型的预构建Keras层的列表为:

def build_model(layers):

而且我想构建一个Keras Functional API模型:

model = Model(inputs, outputs)

因此,我使用了:

inputs = list()
outputs = list()
for layer in layers:
    if isinstance(layer, keras.layers.Input):
        inputs.append(layer)
    else:
        outputs.append(layer)

但是问题是,预先构建的Keras输入层不再保存数据类型:输入,而是像这样的张量:

Tensor(“ input_1:0”,shape =(None,None,None),dtype = float32)

是否有解决方案?遗憾的是,不能更改函数签名,但是如果有解决方法,请告诉我(真的卡在这里)。

提前感谢。

python tensorflow input keras deep-learning
1个回答
0
投票

由于函数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的前缀为输入

或换句话说,代码,

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>]

希望这会有所帮助。祝您学习愉快!

© www.soinside.com 2019 - 2024. All rights reserved.