fchollet 5.4-visualizing-what-c​​onvnets-learn input_13:0 is both fed and fetched 错误

fchollet 5.4-visualizing-what-convnets-learn input_13:0 is both fed and fetched error

使用 Keras 2.2.4,我正在通过这个笔记本 5.4-visualizing-what-convnets-learn , except I switched the model with a unet one provided by Kaggle-Carvana-Image-Masking-Challenge 以我的方式工作。 Kaggle 模型的第一层如下所示,接下来是示例代码的其余部分。

def get_unet_512(input_shape=(512, 512, 3),
                 num_classes=1):
    inputs = Input(shape=input_shape)

...

Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_13 (InputLayer)           (None, 512, 512, 3)  0    
...

from keras import models
layer_outputs = [layer.output for layer in model.layers[:8]]
activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(img_tensor)

现在我得到的错误是

InvalidArgumentError: input_13:0 is both fed and fetched.

有人对如何解决这个问题有任何建议吗?

此错误是由以下原因引起的:

layer_outputs = [layer.output for layer in model.layers[:8]]

,并且说第一层(输入层)是fed和fetched。

解决方法如下:

import keras.backend as K
layer_outputs = [K.identity(layer.output) for layer in model.layers[:8]]

编辑: 完整示例,代码改编自:Mask_RCNN - run_graph

import numpy as np
import keras.backend as K
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Flatten

model = Sequential()
ip = Input(shape=(512,512,3,))
fl = Flatten()(ip)
d1 = Dense(20, activation='relu')(fl)
d2 = Dense(3, activation='softmax')(d1)

model = Model(ip, d2)
model.compile('adam', 'categorical_crossentropy')
model.summary()

layer_outputs = [K.identity(layer.output) for layer in model.layers]
#layer_outputs = [layer.output for layer in model.layers] #fails
kf = K.function([ip], layer_outputs)
activations = kf([np.random.random((1,512,512,3))])
print(activations)