我想集成ResNet50和DenseNet121,但遇到了一个错误:
图形断开连接:无法获取张量Tensor(“input_8:0”, shape=(?, 224, 224, 3), dtype=float32)在层“input_8”的值。之前访问的层没有问题:[]
下面是我集成的代码:
from keras import applicationsfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2Dfrom keras.models import Model, Input#from keras.engine.topology import Inputfrom keras.layers import Averagedef resnet50(): base_model = applications.resnet50.ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) last = base_model.output x = Flatten()(last) x = Dense(2000, activation='relu')(x) preds = Dense(200, activation='softmax')(x) model = Model(base_model.input, preds) return modeldef densenet121(): base_model = applications.densenet.DenseNet121(weights='imagenet', include_top=False, input_shape=(224,224, 3)) last = base_model.output x = Flatten()(last) x = Dense(2000, activation='relu')(x) preds = Dense(200, activation='softmax')(x) model = Model(base_model.input, preds) return modelresnet50_model = resnet50()densenet121_model = densenet121()ensembled_models = [resnet50_model,densenet121_model]def ensemble(models,model_input): outputs = [model.outputs[0] for model in models] y = Average()(outputs) model = Model(model_input,y,name='ensemble') return modelmodel_input = Input(shape=(224,224,3))ensemble_model = ensemble(ensembled_models,model_input)
我认为原因是在我结合ResNet50和DenseNet121时,它们有自己的输入层,尽管我设定了相同的输入形状。不同的输入层导致了冲突。这只是我的猜测,我不确定如何解决这个问题
回答:
您可以在创建基础模型时设置input_tensor=model_input
。
def resnet50(model_input): base_model = applications.resnet50.ResNet50(weights='imagenet', include_top=False, input_tensor=model_input) # ...def densenet121(model_input): base_model = applications.densenet.DenseNet121(weights='imagenet', include_top=False, input_tensor=model_input) # ...model_input = Input(shape=(224, 224, 3))resnet50_model = resnet50(model_input)densenet121_model = densenet121(model_input)
这样,基础模型将使用提供的model_input
张量,而不是创建它们自己的独立输入张量。