簡體   English   中英

如何使用Tensorflow Keras API從預訓練的模型復制特定的圖層權重?

[英]How do I copy specific layer weights from pretrained models using Tensorflow Keras api?

我正在嘗試訓練需要4通道輸入的轉換網絡,並希望使用像VGG16這樣的預訓練模型。 有意義的是,我不應該使用VGG16中的初始轉換塊,因為它們經過了3通道輸入的訓練,並重新定義了初始轉換塊。

但是,我想從VGG16開始使用block3。 如何使用Tensorflow Keras API實現此目標?

簡而言之,如何從預訓練模型的特定圖層復制權重。 我正在使用tensorflow 2.0 alpha版本。

一種快速的方法是創建一個新模型,該模型將您的自定義輸入和VGG16的最后一層結合在一起。 找到您要保留的第一個VGG16層的索引,並將其連接到新創建的輸入。 然后,手動連接下面的每個VGG16層,以重新創建VGG16段。 您可以一路凍結VGG16層。

from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D

vgg16 = VGG16()

# Find the index of the first block3 layer
for index in range(len(vgg16.layers)):
    if 'block3' in vgg16.layers[index].name:
        break

# Add your own input
model_input = Input(shape=(224,224,4), name='new_input')
x = Conv2D(...)(model_input)
...

# Connect your last layer to the VGG16 model, starting at the "block3" layer
# Then, you need to connect every layer manually in a for-loop, freezing each layer along the way

for i in range(index, len(vgg16.layers)):
  # freeze the VGG16 layer
  vgg16.layers[i].trainable = False  

  # connect the layer
  x = vgg16.layers[i](x)

model_output = x
newModel = Model(model_input, model_output)

還要確保自定義圖層的輸出與block3圖層期望作為輸入的形狀匹配。

暫無
暫無

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

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