使用TensorFlow Keras子类API保存模型时出现NotFoundError
问题解决:Keras子类化WideAndDeep模型保存时触发NotFoundError
问题场景
使用TensorFlow Keras子类化API构建了WideAndDeepModel,完成训练、评估与预测后,调用model.save('my_model', save_format='tf')保存模型时触发NotFoundError,错误提示无法重命名临时变量文件,系统找不到指定路径。
模型代码
class WideAndDeepModel(tf.keras.Model): def __init__(self, units=30, activation="relu", **kwargs): super().__init__(**kwargs) # needed to support naming the model self.norm_layer_wide = tf.keras.layers.Normalization() self.norm_layer_deep = tf.keras.layers.Normalization() self.hidden1 = tf.keras.layers.Dense(units, activation=activation) self.hidden2 = tf.keras.layers.Dense(units, activation=activation) self.main_output = tf.keras.layers.Dense(1) self.aux_output = tf.keras.layers.Dense(1) def call(self, inputs): input_wide, input_deep = inputs norm_wide = self.norm_layer_wide(input_wide) norm_deep = self.norm_layer_deep(input_deep) hidden1 = self.hidden1(norm_deep) hidden2 = self.hidden2(hidden1) concat = tf.keras.layers.concatenate([norm_wide, hidden2]) output = self.main_output(concat) aux_output = self.aux_output(hidden2) return output, aux_output tf.random.set_seed(42) # extra code – just for reproducibility model = WideAndDeepModel(30, activation="relu", name="my_cool_model") optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) model.compile(loss="mse", loss_weights=[0.9, 0.1], optimizer=optimizer, metrics=["RootMeanSquaredError"]) model.norm_layer_wide.adapt(X_train_wide) model.norm_layer_deep.adapt(X_train_deep) history = model.fit( (X_train_wide, X_train_deep), (y_train, y_train), epochs=10, validation_data=((X_valid_wide, X_valid_deep), (y_valid, y_valid))) eval_results = model.evaluate((X_test_wide, X_test_deep), (y_test, y_test)) weighted_sum_of_losses, main_loss, aux_loss, main_rmse, aux_rmse = eval_results y_pred_main, y_pred_aux = model.predict((X_new_wide, X_new_deep))
保存代码
model.save('my_model', save_format='tf')
错误信息
--------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) Cell In[94], line 1 ----> 1 model.save('my_model', save_format='tf') File ~\anaconda3\Lib\site-packages\keras\src\utils\traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs) 67 filtered_tb = _process_traceback_frames(e.__traceback__) 68 # To get the full stack trace, call: 69 # `tf.debugging.disable_traceback_filtering()` ---> 70 raise e.with_traceback(filtered_tb) from None 71 finally: 72 del filtered_tb File ~\anaconda3\Lib\site-packages\tensorflow\python\eager\execute.py:53, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name) 51 try: 52 ctx.ensure_initialized() ---> 53 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, 54 inputs, attrs, num_outputs) 55 except core._NotOkStatusException as e: 56 if name is not None: NotFoundError: {{function_node __wrapped__SaveV2_dtypes_43_device_/job:localhost/replica:0/task:0/device:CPU:0}} Failed to rename: my_model\variables\variables_temp/part-00000-of-00001.data-00000-of-00001.tempstate16756848698604293682 to: my_model\variables\variables_temp/part-00000-of-00001.data-00000-of-00001 : The system cannot find the path specified. ; No such process [Op:SaveV2]
解决方案
1. 提前创建保存所需的目录层级
错误提示找不到路径,可能是TensorFlow自动创建目录时出现异常,手动创建完整目录结构后再保存:
import os # 创建完整的目录层级 os.makedirs('my_model/variables/variables_temp', exist_ok=True) model.save('my_model', save_format='tf')
2. 使用绝对路径保存
相对路径可能因当前工作目录问题导致异常,换成绝对路径避免歧义:
import os # 获取绝对路径 save_dir = os.path.abspath('my_model') model.save(save_dir, save_format='tf')
3. 检查权限与进程占用
- 确认当前用户对目标保存目录有读写权限,如果是系统保护目录(如
C:\Windows),换个非系统目录保存 - 关闭所有可能访问
my_model目录的程序(如文件资源管理器、IDE的文件预览),避免目录被占用
4. 临时切换为HDF5格式保存
如果TF格式保存问题无法快速解决,可以先保存为HDF5格式,后续按需转换:
# 保存为HDF5 model.save('my_model.h5') # 加载时需指定自定义模型类 loaded_model = tf.keras.models.load_model( 'my_model.h5', custom_objects={'WideAndDeepModel': WideAndDeepModel} )
5. 升级TensorFlow到最新稳定版
该错误可能是TensorFlow的已知bug,升级到最新版可修复部分路径相关的保存问题:
pip install --upgrade tensorflow
内容的提问来源于stack exchange,提问作者Alexander Peev
相关产品推荐
相关产品推荐

