Python 运行报错 UnicodeDecodeError 解决方法

在尝试使用Keras的load_model函数加载保存的深度学习模型时,出现UnicodeDecodeError,原因是模型文件所在的文件夹名称包含中文字符,导致utf-8编码无法解码。将文件夹名称改为英文后,问题得到解决,模型成功加载。

问题描述:

在使用 Jupyter Notebook 进行深度学习模型导入的时候报错UnicodeDecodeError

model = keras.models.load_model('20220113_L=16_model.47-0.1436.h5')

UnicodeDecodeError Traceback (most recent call last)
Cell In[16], line 1
----> 1 model = keras.models.load_model(‘20220113_L=16_model.47-0.1436.h5’) # load the model (L=4)

File ~\anaconda3\envs\tf\Lib\site-packages\keras\saving\saving_api.py:212, in load_model(filepath, custom_objects, compile, safe_mode, **kwargs)
204 return saving_lib.load_model(
205 filepath,
206 custom_objects=custom_objects,
207 compile=compile,
208 safe_mode=safe_mode,
209 )
211 # Legacy case.
–> 212 return legacy_sm_saving_lib.load_model(
213 filepath, custom_objects=custom_objects, compile=compile, **kwargs
214 )

File ~\anaconda3\envs\tf\Lib\site-packages\keras\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\envs\tf\Lib\site-packages\tensorflow\python\lib\io\file_io.py:703, in is_directory_v2(path)
694 “”“Returns whether the path is a directory or not.
695
696 Args:
(…)
700 True, if the path is a directory; False otherwise
701 “””
702 try:
–> 703 return _pywrap_file_io.IsDirectory(compat.path_to_bytes(path))
704 except errors.OpError:
705 return False

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xdb in position 26: invalid continuation byte

问题描述表示出现了无法识别的字符,导致模型文件加载失败,并且这个无法识别的字符是第26个字符。

解决思路:

实际上是因为这段代码中传递模型文件路径字符出现了utf-8无法解码的情况。

解决方法:

模型文件路径中包含 中文 ,导致解码失败,具体来说是存储该模型的文件夹为中文,将文件夹修改为 英文 后,代码运行成功。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值