Keras 進行模型拼接出現“’Model‘ object has no attribute ‘add’解決
1.部分代碼如下:
# build the VGG16 network
model = applications.VGG16(weights='imagenet', input_shape=(150,150,3),include_top=False)
print('Model loaded.')
# build a classifier model to put on top of the convolutional model
top_model = Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(1, activation='sigmoid'))
top_model.load_weights(top_model_weights_path)
model.add(top_model)
跟着官方Keras 給出的代碼,想通過sequential 序貫式的方式來進行finetune
不料發現了諸多報錯,其中一個很嚴重的問題就是
AttributeError: 'Model' object has no attribute 'add'
作者本人因這個問題嘗試了5天,一直百度不到答案,本以爲在序貫式模型中無法正常add【拼接】,終於在26號早晨的GitHub上的問答中找到該問題的解決方法,一試就通!開森啊!~
2.解決:
"""將modle.add 替換成如下"""
model = Model(input = model.input,output = top_model(model.output))
後來又在答案堆裏看到,應該考慮到Use plurals in the args
3.修改如下:
@JWGS1
Use plurals in the args:
model = Model(inputs=base_model.input, outputs=top_model(base_model.output))
作者本人親自嘗試,以上兩種都可以正常運行,沒有問題。
該文作爲技術分享,以及個人的技術成長,與君共勉~