TensorFlow/Keras model.save失败疑因非英文字母路径求解决
问题描述
训练手写数字识别神经网络时,模型训练环节正常,但调用model.save()保存模型时报错,终端错误信息如下:
Traceback (most recent call last):
File "c:\Users\Käyttäjä\Desktop\Sampo\Neural\handwritten.py", line 33, in
model.save('handwritten.model.test1')
File "C:\Users\Käyttäjä\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Käyttäjä\AppData\Local\Programs\Python\Python311\Lib\site-packages\tensorflow\python\lib\io\file_io.py", line 513, in recursive_create_dir_v2
_pywrap_file_io.RecursivelyCreateDir(compat.path_to_bytes(path))
tensorflow.python.framework.errors_impl.FailedPreconditionError: handwritten.model.test1\variables is not a directory
怀疑是用户名Käyttäjä中的特殊字符Ä导致路径编码问题,且无法修改现有目录,寻求可行解决办法。
使用的代码如下:
import os import cv2 import numpy as np import matplotlib.pyplot as plt import tensorflow as tf # Load the dataset mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # Use tf to normalize datasets between 0-1 x_train = tf.keras.utils.normalize(x_train, axis=1) x_test = tf.keras.utils.normalize(x_test, axis=1) # Create a basic sequential model. Also define the shape of input to be flattened 28 x 28 because of dataset beeing a 28 x 28 greyscale image. model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten(input_shape=(28, 28))) # Second, Dense, layer is a layer where every neuron is connected to every neuron. relu= rectified linear unit is the activation function (negative values turn to 0) model.add(tf.keras.layers.Dense(128, activation='relu')) # thrid layer, exactly same model.add(tf.keras.layers.Dense(128, activation='relu')) # final layer. 10 outputs for numbers 0-9. Softmax activation function is often used for the output. Gives a probability distribution as the output model.add(tf.keras.layers.Dense(10, activation='softmax')) # compile model using optimizer algorithm and loss function model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # finally train the model. Model is going to see each datapoint 3 times model.fit(x_train, y_train, epochs=3) # after the model has been trained, save the model as handwritten.model model.save('handwritten.model.test1')
可行解决办法
1. 保存到不含特殊字符的绝对路径
选择路径中无特殊字符的目录(如系统临时目录、非用户目录的磁盘分区),使用绝对路径保存模型:
# 示例:保存到D盘指定目录 model.save(r'D:\saved_models\handwritten.model.test1') # 或者保存到系统临时目录 import tempfile temp_dir = tempfile.gettempdir() model.save(os.path.join(temp_dir, 'handwritten.model.test1'))
2. 保存为HDF5格式(单个文件)
HDF5格式将模型保存为单个文件,无需创建子目录结构,可直接绕过路径编码问题:
# 保存为.h5格式文件 model.save('handwritten_model.h5') # 后续加载模型使用: # model = tf.keras.models.load_model('handwritten_model.h5')
3. 强制TensorFlow使用UTF-8编码处理路径
在代码开头添加环境变量设置,强制TensorFlow用UTF-8解析文件路径:
import os os.environ['TF_IO_ENCODING'] = 'UTF-8' os.environ['PYTHONUTF8'] = '1' # 之后再导入tensorflow import tensorflow as tf # 其余代码保持不变
验证建议
优先尝试方案2(HDF5格式),操作简单且直接解决问题;若需保留SavedModel格式,可选择方案1或方案3。
内容的提问来源于stack exchange,提问作者Santaissick

