使用 model.pop() 方法,然后使用 Keras Model() API 会导致错误。 Model() API 没有 .pop() 方法,所以如果你想多次重新训练你的模型,就会出现这个错误。 p>
但只有在重新训练后保存模型并在下次重新训练时使用新保存的模型时才会出现错误。
另一个非常错误并且使用过的方法是使用 model.layers.pop()。这次的问题是该函数只删除了它返回的副本中的最后一层。所以,模型还是有层的,只是方法的返回没有层。
我推荐以下解决方案:
承认您已将已训练好的模型保存在模型变量中,例如:
model = load_my_trained_model_function()
# creating a new model
model_2 = Sequential()
# getting all the layers except the output one
for layer in model.layers[:-1]: # just exclude last layer from copying
model_2.add(layer)
# prevent the already trained layers from being trained again
# (you can use layers[:-n] to only freeze the model layers until the nth layer)
for layer in model_2.layers:
layer.trainable = False
# adding the new output layer, the name parameter is important
# otherwise, you will add a Dense_1 named layer, that normally already exists, leading to an error
model_2.add(Dense(num_neurons_you_want, name='new_Dense', activation='softmax'))
现在您应该指定编译和拟合方法来训练您的模型并完成:
model_2.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# model.fit trains the model
model_history = model_2.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_split=0.1)
编辑:
请注意,通过添加新的输出层,我们不会在上次训练中调整权重和偏差。
因此,我们几乎失去了之前训练的所有内容。
我们需要保存上一次训练的输出层的权重和偏差,然后我们必须将它们添加到新的输出层中。
我们还必须考虑是否应该让所有层都训练,或者即使我们应该只允许训练一些插层。
要使用 Keras 从输出层获取权重和偏差,我们可以使用以下方法:
# weights_training[0] = layer weights
# weights_training[1] = layer biases
weights_training = model.layers[-1].get_weights()
现在您应该指定新输出层的权重。例如,您可以将权重的平均值用于新类的权重。这取决于你。
要使用 Keras 设置新输出层的权重和偏差,我们可以使用以下方法:
model_2.layers[-1].set_weights(weights_re_training)