Keras - 所有图层名称都应该是唯一的

das*_*wen 8 python keras vgg-net

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

RuntimeError:名称"predictions"在模型中使用了2次.所有图层名称都应该是唯一的.

我很困惑因为我只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()
Run Code Online (Sandbox Code Playgroud)

感谢@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]).它看起来很棘手,但它的工作原理..我认为这是一个关于日志和结构同步的问题.

ors*_*ady 7

首先,根据您发布的代码,你有没有一个名字属性"预测"层,所以这个错误无关,与你的层 Denseprediction:即:

prediction = Dense(1, activation='sigmoid', 
             name='main_output')(combineFeatureLayer)
Run Code Online (Sandbox Code Playgroud)

VGG16模型有一个Densename predictions.特别是这一行:

x = Dense(classes, activation='softmax', name='predictions')(x)
Run Code Online (Sandbox Code Playgroud)

而且,由于您使用的是其中两个模型,因此您的图层具有重复的名称.

您可以做的是将第二个模型中的图层重命名为预测之外的其他内容,可能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'
Run Code Online (Sandbox Code Playgroud)