【问题标题】:isinstance() to check Keras Layer Type on Tensorisinstance() 检查张量上的 Keras 层类型
【发布时间】:2020-02-20 14:48:14
【问题描述】:

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

def build_model(layers):

我想构建一个 Keras 功能 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)

有没有办法解决这个问题。不幸的是,函数签名无法更改,但如果有解决方法 - 请告诉我(真的卡在这里)。

提前致谢。

【问题讨论】:

  • 嗨@Ramsha Siddiqui,请提供有关您的模型的更多详细信息以及最低可重现代码。

标签: python tensorflow input keras deep-learning


【解决方案1】:

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

希望这会有所帮助。快乐学习!

【讨论】:

  • 嗨!是的,这就是我最终使用的。感谢分享!
【解决方案2】:

您可以将keras.layers.Input 替换为keras.layers.InputLayer 喜欢

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

这对我来说很好。

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2023-02-01
    • 2015-12-26
    • 2021-01-29
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多