我保存了一个包含多个层的LSTM模型。现在,我想加载它并只对最后一个LSTM层进行微调。我该如何定位这个层并更改其参数呢?
训练并保存的简单模型示例:
model = Sequential()# first layer #neurons model.add(LSTM(100, return_sequences=True, input_shape=(X.shape[1], X.shape[2])))model.add(LSTM(50, return_sequences=True))model.add(LSTM(25))model.add(Dense(1))model.compile(loss='mae', optimizer='adam')
我可以加载并重新训练它,但我找不到方法来定位特定的层并冻结其他所有层。
回答:
如果你之前已经构建并保存了模型,现在想加载它并只对最后一个LSTM层进行微调,那么你需要将其他层的trainable
属性设置为False
。首先,使用model.summary()
方法找到层的名称(或从顶部开始从零计数的层的索引)。例如,这是我的一个模型产生的输出:
_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_10 (InputLayer) (None, 400, 16) 0 _________________________________________________________________conv1d_2 (Conv1D) (None, 400, 32) 4128 _________________________________________________________________lstm_2 (LSTM) (None, 32) 8320 _________________________________________________________________dense_2 (Dense) (None, 1) 33 =================================================================Total params: 12,481Trainable params: 12,481Non-trainable params: 0_________________________________________________________________
然后将除了LSTM层之外的所有层的可训练参数设置为False
。
方法1:
for layer in model.layers: if layer.name != `lstm_2` layer.trainable = False
方法2:
for layer in model.layers: layer.trainable = Falsemodel.layers[2].trainable = True # set lstm to be trainable# to make sure 2 is the index of the layerprint(model.layers[2].name) # prints 'lstm_2'
别忘了重新编译模型以应用这些更改。