imageAI搭配TensorFlow/Keras报tensorflow.python.platform模块缺失错误
ModuleNotFoundError: No module named 'tensorflow.python.platform' 修复方案 报错截图:
问题根因
该报错由两类问题共同触发:
- 核心原因是依赖版本不兼容:imageAI旧稳定版本仅适配TensorFlow 2.4~2.9版本区间,≥2.10版本的TensorFlow调整了内部私有API的目录结构,导致
sidecar_evaluator.py中导入tensorflow.python.platform模块时找不到对应路径。 - 附加问题是提供的
imagea.py代码存在多处缩进语法错误,即使解决依赖问题也无法正常运行。
修复步骤
- 清理环境中不兼容的依赖
进入项目对应的Python/conda环境,执行命令卸载冲突包:
pip uninstall -y tensorflow tensorflow-gpu keras imageai numpy
- 安装经过验证的兼容版本依赖
直接固定版本安装,避免自动拉取最新不兼容版本:
pip install numpy==1.23.5 pip install tensorflow==2.9.0 pip install keras==2.9.0 pip install imageai==3.0.3
使用N卡CUDA加速的用户,将上述命令中的tensorflow==2.9.0替换为tensorflow-gpu==2.9.0即可,对应配套CUDA版本为11.2、cuDNN版本为8.1。
- 修正代码缩进错误
原imagea.py中函数内代码、主逻辑判断块存在缩进错位,修正后可运行代码如下:
import os import threading from imageai.Prediction import ImagePrediction from imageai.Prediction.Custom import ModelTraining from imageai.Prediction.Custom import CustomImagePrediction def modelTrain(dataDir='data',classNum=2,epochs=100,batch_size=32): model_trainer = ModelTraining() model_trainer.setModelTypeAsResNet() model_trainer.setDataDirectory(dataDir) model_trainer.trainModel(num_objects=classNum, num_experiments=epochs,enhance_data=True, batch_size=batch_size, show_network_summary=True) print('Model Train Finished!!!') def modelPredict(model_path='data/models/model_ex-001_acc-0.500000.h5', class_path='data/json/model_class.json', pic_path='a.jpg',classNum=2,resNum=5): prediction=CustomImagePrediction() prediction.setModelTypeAsResNet() prediction.setModelPath(model_path) prediction.setJsonPath(class_path) prediction.loadModel(num_objects=classNum,prediction_speed='fastest') predictions,probabilities=prediction.predictImage(pic_path,result_count=resNum) for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction+" : "+str(eachProbability)) if __name__=='__main__': modelTrain(dataDir='data',classNum=2,epochs=10,batch_size=8) modelPredict(model_path='data/models/model_ex-001_acc-0.500000.h5', class_path='data/json/model_class.json', pic_path='test.jpg',classNum=2,resNum=5)
- 验证修复结果
执行如下命令做导入校验,无报错即说明模块问题修复完成:
python -c "import tensorflow as tf; from tensorflow.python.platform import tf_logging; print('TensorFlow版本:', tf.__version__, '模块导入正常')"
校验通过后即可正常运行训练、预测逻辑。
注意:不要通过修改TensorFlow安装目录源码、手动改写sidecar_evaluator.py导入路径的方式临时绕过报错,这类操作会触发更多连锁依赖异常,固定兼容版本是稳定性最高的方案。
内容的提问来源于stack exchange,提问作者yannn31
相关产品推荐
相关产品推荐

