繁体   English   中英

有没有办法训练一个 CNN 模型,保存这个 CNN 的权重,然后使用这个权重来为其他训练数据重新训练这个 CNN?

[英]Is there a way to train a CNN model, save the weights of this CNN, and then use this weights to retrain this CNN for other train data?

有人告诉我这种类型的实验。 第一步是训练一个 CNN 并保持权重,第二步是使用这些权重来重新训练这个 CNN,但这次是向你的训练集添加更多数据(微调)。

我想这有点像迁移学习,但是你训练了一个 CNN。 有没有办法在训练 CNN 之前选择权重,并将那些选择的权重作为您的文件?

所以到目前为止我所做的是训练我的 CNN 模型并将权重保存到 h5 文件中,代码如下

model.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])
validation_data=(x_testcnn, y_test))
checkpoint_path= 'scratchmodel.best.h5'
save_dir = os.path.join(os.getcwd(), 'weights')
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                             save_weights_only=True,
                                             verbose=1)
 cnnhistory=model.fit(x_traincnn, 
      y_train,
      batch_size=16,           
      epochs=400,
      validation_data=(x_testcnn,y_test),
      callbacks=[cp_callback])

现在我想用相同的权重重新训练相同的 CNN,但这次将数据添加到训练集。 有没有办法做到这一点? 谢谢你的帮助。

是的,您只需要将权重加载到新创建的模型中,然后使用新数据进行训练。

from tensorflow.python.keras.models import load_model #Tensorflow 2.0

new_model.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])
new_model = load_model(filepath, compile=False) #compile=False allows you to load saved optimizer state

new_model.fit(...) # Fit on new data, leveraging training on old data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM