【问题标题】:How do I add a top dense layer to ResNet50 in Keras?如何在 Keras 中向 ResNet50 添加顶部密集层?
【发布时间】:2017-03-14 14:13:07
【问题描述】:

我在这里阅读了这篇关于迁移学习的非常有用的 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 的定义方式不同。无论如何,我的问题是:如何将这个带有加载权重的顶级模型添加到底部模型中?谁能给点有用的指点?

【问题讨论】:

    标签: python deep-learning keras


    【解决方案1】:

    试试:

    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 是在所谓的functional API 中定义的事实。我还建议您使用不同的激活函数,因为将relu 作为输出激活可能会导致问题。此外 - 您的模型未编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-24
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2019-03-06
      相关资源
      最近更新 更多