通过加载和保存权重来保持Keras模型的训练

2024-04-25 22:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

由于软件包不一致,我无法安装h5py,因此我想知道是否可以保存并加载Keras中的权重,以便在新数据上继续训练您的模型。我知道我可以做到以下几点:

   old_weights = model.get_weights()
   del model
   new_model.set_weights(old_weights)

其中模型是旧模型,新模型是新模型一个。这里是一个完整的例子:

for i in training data:
    model = Sequential()
    model.add(Dense(20, activation='tanh', input_dim=Input))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mse')
    model.fit(X, y, epochs=8, batch_size=16, shuffle=False, verbose=0)
    new_model = Sequential()
    new_model.add(Dense(20, activation='tanh', input_dim=Input))
    new_model.add(Dense(1))
    new_model.compile(optimizer='adam', loss='mse')
    old_weights = model.get_weights()
    del model
    new_model.set_weights(old_weights)
    model=new_model

我想在阅读了每个训练示例(X和y在每个迭代中是不同的)之后,保存权重并再次加载它,然后从预先训练的模型开始。我不确定我的代码是否做到了这一点,因为我正在定义优化器和模型.编译再一次。如果下面的代码保存了模型并且每次迭代都从预先训练好的模型开始,有人能帮我吗。你知道吗


Tags: 模型addnewinputgetmodelactivationold
1条回答
网友
1楼 · 发布于 2024-04-25 22:20:52

您不需要一直重新编译模型。取而代之的是,只需在加载样本后多次拟合模型。你知道吗

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(20, activation='tanh', input_dim=Input))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
# load the data into training_data 
for data in training_data:  
    model.fit(data[0], data[1], epochs=8, batch_size=16, shuffle=False, verbose=0)

相关问题 更多 >

    热门问题