簡體   English   中英

如何使用來自一個預先訓練的MLP的最后一個隱藏層權重作為Keras的新MLP(轉移學習)的輸入?

[英]How to use the last hidden layer weights from one pre-trained MLP as input to a new MLP (transfer learning) with Keras?

我想使用簡單的MLP模型進行遷移學習。 首先,我在大數據上訓練了1個隱藏層前饋網絡:

net = Sequential()
net.add(Dense(500, input_dim=2048, kernel_initializer='normal', activation='relu'))
net.add(Dense(1, kernel_initializer='normal'))
net.compile(loss='mean_absolute_error', optimizer='adam')
net.fit(x_transf, 
        y_transf,
        epochs=1000, 
        batch_size=8, 
        verbose=0)

然后,我想將唯一的隱藏層作為輸入傳遞到新網絡,在其中我要添加第二層。 重用的層不應是可訓練的。

idx = 1  # index of desired layer
input_shape = net.layers[idx].get_input_shape_at(0) # get the input shape of desired layer
input_layer = net.layers[idx]
input_layer.trainable = False

transf_model = Sequential()
transf_model.add(input_layer)
transf_model.add(Dense(input_shape[1], activation='relu'))
transf_model.compile(loss='mean_absolute_error', optimizer='adam')
transf_model.fit(x, 
                 y,
                 epochs=10, 
                 batch_size=8, 
                 verbose=0)

編輯:上面的代碼返回:

ValueError: Error when checking target: expected dense_9 to have shape (None, 500) but got array with shape (436, 1)

使這項工作有效的訣竅是什么?

我將只使用Functional API來構建這樣的模型:

shared_layer = net.layers[0] # you want the first layer, so index = 0
shared_layer.trainable = False

inp = Input(the_shape_of_one_input_sample) # e.g. (2048,)
x = shared_layer(inp)
x = Dense(800, ...)(x)
out = Dense(1, ...)(x)

model = Model(inp, out)

# the rest is the same...

暫無
暫無

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

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