2017-06-02 227 views
0

我想使用預訓練模型的卷積函數特徵映射作爲主模型的輸入特徵。Keras合併/連接模型輸出作爲新層

inputs = layers.Input(shape=(100, 100, 12)) 
sub_models = get_model_ensemble(inputs) 
sub_models_outputs = [m.layers[-1] for m in sub_models] 
inputs_augmented = layers.concatenate([inputs] + sub_models_outputs, axis=-1) 

下面是我在get_model_ensemble()做的關鍵部分:

for i in range(len(models)): 
    model = models[i] 
    for lay in model.layers: 
     lay.name = lay.name + "_" + str(i) 
    # Remove the last classification layer to rather get the underlying convolutional embeddings 
    model.layers.pop() 
    # while "conv2d" not in model.layers[-1].name.lower(): 
    #  model.layers.pop() 
    model.layers[0] = new_input_layer 
return models 

所有這給:

Traceback (most recent call last): 
    File "model_ensemble.py", line 151, in <module> 
    model = get_mini_ensemble_net() 
    File "model_ensemble.py", line 116, in get_mini_ensemble_net 
    inputs_augmented = layers.concatenate([inputs] + sub_models_outputs, axis=-1) 
    File "/usr/local/lib/python3.4/dist-packages/keras/layers/merge.py", line 508, in concatenate 
    return Concatenate(axis=axis, **kwargs)(inputs) 
    File "/usr/local/lib/python3.4/dist-packages/keras/engine/topology.py", line 549, in __call__ 
    input_shapes.append(K.int_shape(x_elem)) 
    File "/usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py", line 451, in int_shape 
    shape = x.get_shape() 
AttributeError: 'BatchNormalization' object has no attribute 'get_shape' 

這裏是輸入信息:

print(type(inputs)) 
print(type(sub_models[0])) 
print(type(sub_models_outputs[0])) 

<class 'tensorflow.python.framework.ops.Tensor'> 
<class 'keras.engine.training.Model'> 
<class 'keras.layers.normalization.BatchNormalization'> 

注:我從012獲得的模型已經調用了它們的compile()函數。那麼,我應該如何正確地連接我的模型?爲什麼不行?我想這可能與如何將輸入饋送到子模型以及如何熱交換其輸入層有關。

感謝您的幫助!

回答

0

事情工作,如果我們這樣做:

sub_models_outputs = [m(inputs) for m in sub_models] 

而不是:

sub_models_outputs = [m.layers[-1] for m in sub_models] 

TLDR:模型需要被稱爲層。