簡體   English   中英

如何在Keras中的ResNet50上添加一個頂部密集層?

[英]How do I add a top dense layer to ResNet50 in 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是用不同的方式定義的。 無論如何,我的問題是:如何將帶有已加載權重的頂級模型添加到底層模型中? 誰能提供有用的指導?

嘗試:

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是在所謂的功能API中定義的事實。 我也建議您使用其他激活功能,因為將relu作為輸出激活可能會引起問題。 此外-您的模型未編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM