Python 访问层';使用Tensorflow 2.0模型子分类的s输入/输出

Python 访问层';使用Tensorflow 2.0模型子分类的s输入/输出,python,tensorflow,keras,conv-neural-network,tensorflow2.0,Python,Tensorflow,Keras,Conv Neural Network,Tensorflow2.0,在一个大学练习中,我使用了TF2.0的模型子分类API。这是我的代码(如果你想知道的话,这是Alexnet体系结构…): 我的目标是访问任意层的输出(为了最大化特定神经元的激活,如果你必须确切知道:)。问题是,尝试访问任何层的输出时,会出现属性错误。例如: model = MyModel() print(model.get_layer('conv1').output) # => AttributeError: Layer conv1 has no inbound nodes. model

在一个大学练习中,我使用了TF2.0的模型子分类API。这是我的代码(如果你想知道的话,这是Alexnet体系结构…):

我的目标是访问任意层的输出(为了最大化特定神经元的激活,如果你必须确切知道:)。问题是,尝试访问任何层的输出时,会出现属性错误。例如:

model = MyModel()
print(model.get_layer('conv1').output)
# => AttributeError: Layer conv1 has no inbound nodes.
model = MyModel()
I = tf.keras.Input(shape=(224, 224, 3))
model(I)
print(model.get_layer('conv1').output)
# prints Tensor("my_model/conv1/Identity:0", shape=(None, 56, 56, 96), dtype=float32)
print(model.get_layer('FC_1000').output)
# => AttributeError: Layer FC_1000 has no inbound nodes.
我在SO中发现了一些与此错误有关的问题,所有这些问题都声称我必须在第一层定义输入形状,但正如您所看到的,这已经完成了(请参见
\uu init\uuuuuu
函数中的
self.conv1
的定义)

我确实发现,如果我定义一个
keras.layers.Input
对象,我确实能够获得
conv1
的输出,但是尝试访问更深的层失败,例如:

model = MyModel()
print(model.get_layer('conv1').output)
# => AttributeError: Layer conv1 has no inbound nodes.
model = MyModel()
I = tf.keras.Input(shape=(224, 224, 3))
model(I)
print(model.get_layer('conv1').output)
# prints Tensor("my_model/conv1/Identity:0", shape=(None, 56, 56, 96), dtype=float32)
print(model.get_layer('FC_1000').output)
# => AttributeError: Layer FC_1000 has no inbound nodes.

我用谷歌搜索了路上遇到的每一个例外,但没有找到答案。在这种情况下,我如何访问任何层的输入/输出(或者输入/输出形状属性?

在子类模型中,没有层图,它只是一段代码(模型
调用
函数)。创建模型类实例时未定义图层连接。因此,我们需要首先通过调用
call
方法来构建模型。

试试这个:

model = MyModel()
inputs = tf.keras.Input(shape=(224,224,3))
model.call(inputs)
# instead of model(I) in your code.
完成此操作后,将创建模型图

for i in model.layers:
  print(i.output)
# output
# Tensor("ReLU_7/Relu:0", shape=(?, 56, 56, 96), dtype=float32)
# Tensor("MaxPool_3/MaxPool:0", shape=(?, 27, 27, 96), dtype=float32)
# Tensor("Softmax_1/Softmax:0", shape=(?, 1000), dtype=float32)
# ...

谢谢,它起作用了!2个问题:1。我仍然不明白为什么调用
model(I)
不起作用-当我们这样做时有什么不同(调用时没有显式的
call
函数)。2.一些层正在被重用(例如,ReLU层)-有没有办法访问这些层每次激活的不同输出(我相信我可以使用简单复制这些层的简单解决方案,但我想知道是否有更有效的解决方案)@noamgot Q1:据我从
tf.keras.models.Model
github repo了解,
call
method从网络类调用父方法,该网络类构建网络图,而调用子类模型对象只将输入传递给自定义(MyModel)的call方法。虽然我不确定!问题2。正如您所说,对于子类模型,唯一的方法是复制这些层。虽然如果你找到任何工作,请分享!即使我使用方法
调用
,我也会收到以下错误
***AttributeError:Layer dense\u 12没有入站节点。
每当我使用模型子类化时。有解决办法吗?