如何在Keras的ResNet50中添加顶部密集层?

时间:2017-03-14 14:13:08

标签: python deep-learning keras

我在这里阅读了这篇关于转学的非常有用的Keras教程:

https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

我认为这可能非常适用于这里的鱼类数据,并开始沿着这条路走下去。我试图尽可能多地遵循教程。代码是一团糟,因为我只是想弄清楚一切是如何工作的,但可以在这里找到:

https://github.com/MrChristophRivera/ClassifiyingFish/blob/master/notebooks/Anthony/Resnet50%2BTransfer%20Learning%20Attempt.ipynb

为简洁起见,这里是我在这里采取的步骤:

model = ResNet50(top_layer = False, weights="imagenet"
# I would resize the image to that of the standard input size of ResNet50.
datagen=ImageDataGenerator(1./255)
generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=32,
    class_mode=None,
    shuffle=False)
# predict on the training data
bottleneck_features_train = model.predict_generator(generator, 
nb_train_samples)
print(bottleneck_features_train)
file_name = join(save_directory, 'tbottleneck_features_train.npy')
np.save(open(file_name, 'wb'), bottleneck_features_train)
# Then I would use this output to feed my top layer and train it. Let's 
say I defined 
# it like so:
top_model = Sequential()
# Skipping some layers for brevity
top_model.add(Dense(8,  activation='relu')
top_model.fit(train_data, train_labels)
top_model.save_weights(top_model_weights_path).

此时,我保存了重量。下一步是将顶层添加到ResNet50。教程只是这样做:

# VGG16 model defined via Sequential is called bottom_model.
bottom_model.add(top_model)

问题是,当我尝试这样做时,这会失败,因为"模型没有属性添加"。我的猜测是ResNet50以不同的方式定义。无论如何,我的问题是:如何将此顶级模型与加载的权重添加到底部模型?任何人都可以提供有用的指示吗?

1 个答案:

答案 0 :(得分:2)

尝试:

input_to_model = Input(shape=shape_of_your_image)
base_model = model(input_to_model)
top_model = Flatten()(base_model)
top_model = Dense(8,  activation='relu')
...

您的问题来自Resnet50在所谓的wxTrac中定义的事实。我还建议您使用不同的激活功能,因为将relu作为输出激活可能会导致问题。此外 - 您的模型未编译。