Keras-所有图层名称应唯一
问题内容:
我将两个VGG网在keras中组合在一起以进行分类任务。当我运行程序时,它显示一个错误:
RuntimeError:名称“预测”在模型中使用了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()
感谢@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”的图层,因此此错误与您的图层Dense
图层无关
prediction
:即:
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'