在特定时期后如何冻结特定层的训练

时间:2019-12-09 09:45:17

标签: tensorflow keras

我想在第三个纪元后冻结以下代码的前两层的训练。总纪元设置为10。

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

2 个答案:

答案 0 :(得分:2)

如何“冻结” Keras图层?

“冻结”一层意味着将其排除在训练之外,即其权重将永远不会更新。这在微调模型或为文本输入使用固定嵌入的情况下很有用。

您可以更改图层的可训练属性。

for layer in model.layers[:2]:
    layer.trainable = False

要使其生效,您需要在修改可训练属性后在模型上调用 compile()。如果不这样做,您将收到警告“可训练的重量与收集的可训练的重量之间的差异”,并且所有图层仍将可训练。所以:

  • 构建和编译模型
  • 训练3个时代
  • 冻结所需的图层
  • 再次编译模型
  • 训练其余纪元

答案 1 :(得分:-1)

这应该有效:

for epoch in range(3):
    model.fit(.., epochs=1)

# save the weights of this model
model.save_weights("weight_file.h5") 

# freeze the layers you want
for layer in model.layers[:2]:
    layer.trainable = False

为了进一步训练这些权重但冻结前两层,您需要再次编译模型。

model.compile(..)

# train further    
for epoch in range(3, 10):
    model.fit(..., epochs=1)