由于包不一致而无法安装 h5py,我想知道是否可以在 Keras 中保存和加载权重以继续在新数据上训练您的模型。我知道我可以做到以下几点:
old_weights = model.get_weights()
del model
new_model.set_weights(old_weights)
其中模型是旧模型,new_model是新模型。下面是一个完整的示例:
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 在每次迭代中都不同(后保存权重并再次加载它并从预先训练的模型开始。我不确定我的代码是否这样做,因为我再次定义了优化器和 model.compile。如果以下代码保存模型并且每次迭代都从预先训练的模型开始,任何人都可以帮助我。
你不需要
不断重新编译模型。相反,只需在加载样本后多次拟合模型即可。
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)