[英]Issues splitting autoencoder model in Keras
我已經訓練了一個自動編碼器並使用內置於save()方法的keras保存它。 現在我想把它分成兩部分:編碼器和解碼器。 我可以通過使用舊模型創建新模型來成功加載模型並獲取編碼器部件:
encoder_model = keras.models.Model(inputs=self.model.input,
outputs=self.model.get_layer(layer_of_activations).get_output_at(0))
但是,如果我嘗試用解碼器做替代的事情,我不能。 我嘗試使用各種方法,其中沒有一個是正確的。 然后我在這里找到了類似的問題( Keras替換輸入層 )並嘗試使用此方法使用以下代碼:
for i, l in enumerate(self.model.layers[0:19]):
self.model.layers.pop(0)
newInput = Input(batch_shape=(None, None, None, 64))
newOutputs = self.model(newInput)
newModel = keras.models.Model(newInput, newOutputs)
我刪除的最后一層的輸出形狀是(None,None,None,64),但此代碼會產生以下錯誤:
ValueError: number of input channels does not match corresponding dimension of filter, 64 != 3
我假設這是因為在彈出原始圖層后模型的輸入尺寸沒有更新,這在本問題的第一個答案,第二個評論中注明: Keras替換輸入圖層
簡單地循環遍歷圖層並在新模型中重新創建它們不起作用,因為我的模型不是順序的。
我通過構建一個與原始自動編碼器網絡的解碼器部分完全相同的架構的新模型解決了這個問題,然后只復制了權重。
這是代碼:
# Looping through the old model and popping the encoder part + encoded layer
for i, l in enumerate(self.model.layers[0:19]):
self.model.layers.pop(0)
# Building a clean model that is the exact same architecture as the decoder part of the autoencoder
new_model = nb.build_decoder()
# Looping through both models and setting the weights on the new decoder
for i, l in enumerate(self.model.layers):
new_model.layers[i+1].set_weights(l.get_weights())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.