我将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]).它看起来很棘手,但它的工作原理..我认为这是一个关于日志和结构同步的问题.
1)我尝试使用TF后端重命名模型和Keras中的图层,因为我在一个脚本中使用多个模型.类Model似乎具有属性model.name,但在更改它时我得到"AttributeError:无法设置属性".这里有什么问题?
2)此外,我正在使用顺序API,我想给图层命名,这似乎是功能API的可能,但我找不到顺序API的解决方案.anonye知道如何为顺序API做到这一点吗?
更新到2):命名图层工作,虽然它似乎没有记录.只需添加参数名称,例如model.add(Dense(...,...,name ="hiddenLayer1").注意,具有相同名称的图层共享权重!