Keras: Keras 2.0.6, VGG16 'Model' object has no attribute 'add'

Created on 14 Jul 2017  ·  6Comments  ·  Source: keras-team/keras

在练习你们文档中"面向小数据集构建图像分类模型"案例时,第三部分微调预训练网络,出错.

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'))

# note that it is necessary to start with a fully-trained
# classifier, including the top classifier,
# in order to successfully do fine-tuning
top_model.load_weights(top_model_weights_path)

# add the model on top of the convolutional base
model.add(top_model)

文章地址:https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
代码地址(59-75行):https://gist.github.com/fchollet/7eb39b44eb9e16e59632d25fb3119975

Keras 2.06, TensorFlow 1.2.x,

stale

Most helpful comment

Use something like this:

base_model = applications.VGG16(...

top_model = Sequential()
top_model.add(Flatten(input_shape=base_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 = Model(inputs= base_model.input, outputs= top_model(base_model.output))

All 6 comments

Use something like this:

base_model = applications.VGG16(...

top_model = Sequential()
top_model.add(Flatten(input_shape=base_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 = Model(inputs= base_model.input, outputs= top_model(base_model.output))

I solved by creating a new model (Sequential()) and by copying all the layers of VGG16 into this new model:

model = applications.VGG16(...)
...
new_model = Sequential() #new model
for layer in model.layers: 
    new_model.add(layer)
...
new_model.add(top_model) # now this works

thanks @MatinHz @edoven , is ok, @MatinHz good

This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 30 days if no further activity occurs, but feel free to re-open a closed issue if needed.

@MatinHz
How do I find the top_model_weights_path?

@cloudhsiao
You have to have pretrained weights to run the mentioned fine tuning, top_model_weights_path is the place where it is located, check:
https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

Was this page helpful?
0 / 5 - 0 ratings