TensorFlow/Keras导入to_categorical报错求助(Python3.9+PyCharm环境)
解决PyCharm中无法导入tensorflow.keras.utils.to_categorical的问题
1. 修正导入语句的拼写错误
你写的utilis是拼写错误,正确模块名是utils,修正后的代码:
from tensorflow.keras.utils import to_categorical
2. 确认PyCharm的Python解释器配置
- 打开PyCharm,依次点击
File→Settings(Windows/Linux)或PyCharm→Settings(Mac) - 进入
Project: [你的项目名]→Python Interpreter界面 - 检查列表中是否有
tensorflow,且版本适配Python3.9(推荐TensorFlow 2.8.x及以上版本,对Python3.9兼容性更好) - 若没有
tensorflow,点击+搜索并安装;若已存在,可点击✓选择Upgrade更新到兼容版本
3. 卸载单独安装的Keras
TensorFlow 2.x已内置Keras,单独安装的Keras会和内置版本冲突,导致模块查找失败:
- 在PyCharm的Python Interpreter界面找到
keras,点击-卸载 - 或在终端执行命令:
pip uninstall keras -y
4. 验证并修复缓存问题
如果修正拼写和配置后仍报错:
- 在PyCharm终端执行以下命令验证导入是否正常:
python -c "from tensorflow.keras.utils import to_categorical; print('导入成功')"
- 若终端执行成功但PyCharm内报错,重启PyCharm,或点击
File→Invalidate Caches...→选择Invalidate and Restart清除缓存后重启
内容的提问来源于stack exchange,提问作者Skye1220
相关产品推荐
相关产品推荐

