加载训练好的模型再训练时出现Unable to create dataset报错
多阶段训练加载模型报错:Unable to create dataset (name already exists)
问题情况
采用多阶段训练模型:第一轮训练后直接修改学习率再训练流程正常,但加载第一轮训练得到的最优模型并修改学习率时触发报错,移除学习率修改步骤后报错仍存在,确认问题源于模型加载,且已排除各层名称重复的影响。
报错信息
File "E:\Anaconda3\envs\tf2.7_bigData\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "E:\Anaconda3\envs\tf2.7_bigData\lib\site-packages\h5py\_hl\group.py", line 161, in create_dataset dsid = dataset.make_new_dset(group, shape, dtype, data, name, **kwds) File "E:\Anaconda3\envs\tf2.7_bigData\lib\site-packages\h5py\_hl\dataset.py", line 156, in make_new_dset dset_id = h5d.create(parent.id, name, tid, sid, dcpl=dcpl, dapl=dapl) File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper File "h5py\h5d.pyx", line 87, in h5py.h5d.create ValueError: Unable to create dataset (name already exists)
相关代码
加载模型与修改学习率代码
model = tensorflow.keras.models.load_model('resultats/' + str(bv_num) + '_convergeance_' + nom_exp + '.h5') optimizer.lr.assign(learning_rates[1]) model.compile(optimizer=optimizer, loss='mse')
优化器初始化代码
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
解决方案
1. 加载模型时跳过编译,重新初始化优化器
加载模型时添加compile=False参数,避免加载原模型的优化器状态,之后重新编译模型:
# 加载模型但不编译 model = tensorflow.keras.models.load_model('resultats/' + str(bv_num) + '_convergeance_' + nom_exp + '.h5', compile=False) # 重新初始化优化器并设置目标学习率 optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rates[1]) # 重新编译模型 model.compile(optimizer=optimizer, loss='mse')
原理:原模型保存时包含了优化器的状态数据,重新加载后再编译会导致新优化器的状态写入与已有数据集冲突,跳过加载优化器即可避免该问题。
2. 手动构建模型结构,仅加载权重
如果已知模型结构,先重新定义模型,再单独加载权重而非整个模型:
# 重新定义你的模型结构(示例,需替换为实际结构) def build_your_model(): model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', name='dense_1'), tf.keras.layers.Dense(32, activation='relu', name='dense_2'), tf.keras.layers.Dense(1, name='output') ]) return model # 构建模型 model = build_your_model() # 仅加载权重 model.load_weights('resultats/' + str(bv_num) + '_convergeance_' + nom_exp + '.h5') # 初始化优化器并编译 optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rates[1]) model.compile(optimizer=optimizer, loss='mse')
原理:完全分离模型结构与权重,避免加载原模型中的优化器状态,从根源上消除冲突。
3. 修改模型保存方式,仅保存权重
第一轮训练结束时,只保存模型权重而非完整模型,后续加载权重继续训练:
保存权重(第一轮训练后)
model.save_weights('resultats/' + str(bv_num) + '_convergeance_weights_' + nom_exp + '.h5')
加载权重并继续训练
# 构建模型结构 model = build_your_model() # 加载权重 model.load_weights('resultats/' + str(bv_num) + '_convergeance_weights_' + nom_exp + '.h5') # 初始化优化器并编译 optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rates[1]) model.compile(optimizer=optimizer, loss='mse')
内容的提问来源于stack exchange,提问作者Jonathan Roy
相关产品推荐
相关产品推荐

