在Keras中重置模型的所有权重和偏差(训练后恢复模型)

时间:2019-09-06 17:55:05

标签: python tensorflow machine-learning keras lstm

假设我有这样的东西。

model = Sequential()
model.add(LSTM(units = 10 input_shape = (x1, x2)))
model.add(Activation('tanh'))
model.compile(optimizer = 'adam', loss = 'mse')

## Step 1.
model.fit(X_train, Y_train, epochs = 10)

训练完模型后,我想重设模型中的所有内容(权重和偏差)。因此,我想在compile函数之后还原模型(步骤1)。在Keras中最快的方法是什么?

1 个答案:

答案 0 :(得分:3)

是否最快,也许是未知之数,但这肯定很简单,可能对您的情况足够好:序列化初始权重,然后在必要时反序列化,并使用类似io.BytesIO的方法来避免磁盘I / O命中(并且此后必须清理):

from io import BytesIO

model = Sequential()
model.add(LSTM(units = 10, input_shape = (x1, x2)))
model.add(Activation('tanh'))
model.compile(optimizer = 'adam', loss = 'mse')
f = BytesIO()
model.save_weights(f)  # Stores the weights
model.fit(X_train, Y_train, epochs = 10)
# [Do whatever you want with your trained model here]
model.load_weights(f)  # Resets the weights