我将两个VGG网在keras中组合在一起以进行分类任务。当我运行该程序时,它显示一个错误:



我很困惑,因为我在代码中只使用了一次prediction层:

from keras.layers import Dense
import keras
from keras.models import  Model
model1 = keras.applications.vgg16.VGG16(include_top=True, weights='imagenet',
                                input_tensor=None, input_shape=None,
                                pooling=None,
                                classes=1000)
model1.layers.pop()

model2 =  keras.applications.vgg16.VGG16(include_top=True, weights='imagenet',
                                input_tensor=None, input_shape=None,
                                pooling=None,
                                classes=1000)
model2.layers.pop()
for layer in model2.layers:
    layer.name = layer.name + str("two")
model1.summary()
model2.summary()
featureLayer1 = model1.output
featureLayer2 = model2.output
combineFeatureLayer = keras.layers.concatenate([featureLayer1, featureLayer2])
prediction = Dense(1, activation='sigmoid', name='main_output')(combineFeatureLayer)

model = Model(inputs=[model1.input, model2.input], outputs= prediction)
model.summary()

感谢@putonspectacles的帮助,我按照他的指示进行操作,找到了一些有趣的部分。如果您使用model2.layers.pop()并使用“model.layers.keras.layers.concatenate([model1.output, model2.output])”组合两个模型的最后一层,您会发现仍然使用model.summary()显示最后一层信息。但是实际上它们不存在于结构中。因此,您可以使用model.layers.keras.layers.concatenate([model1.layers[-1].output, model2.layers[-1].output])。它看起来很棘手,但确实有效。.我认为这是有关日志和结构同步的问题。

最佳答案

首先,根据您发布的代码,您没有名称属性为“predictions”的图层,因此此错误与您的图层无关
Denseprediction:即:

prediction = Dense(1, activation='sigmoid',
             name='main_output')(combineFeatureLayer)

VGG16 模型具有Dense层和name predictions。特别是这一行:
x = Dense(classes, activation='softmax', name='predictions')(x)

并且由于您使用了其中两个模型,所以您的图层具有重复的名称。

您可以做的是将第二个模型中的图层重命名为除预测之外的其他名称,例如predictions_1,如下所示:
model2 =  keras.applications.vgg16.VGG16(include_top=True, weights='imagenet',
                                input_tensor=None, input_shape=None,
                                pooling=None,
                                classes=1000)

# now change the name of the layer inplace.
model2.get_layer(name='predictions').name='predictions_1'

关于python - Keras-所有图层名称应唯一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43452441/

10-12 19:27