在用imageAI时,遇到一下报错,查了说版本不一样,但换了好几个版本都没解决
ModuleNotFoundError: No module named 'tensorflow.python.keras.preprocessing'
我是按照这篇文章来的,代码如下
# 导入ImageAI库和python os类
from imageai.Prediction import ImagePrediction
import os
execution_path = 'E:\imageAI' # imageAI 根目录
prediction = ImagePrediction() # 图片预测预备
# 模型文件下载在根目录的models子目录下
# 选择一个神经网络
# 1 DenseNet 预测时间较慢,精度最高
# prediction.setModelTypeAsDenseNet()
# prediction.setModelPath(
# os.path.join(execution_path, 'models',
# "DenseNet-BC-121-32.h5")) # 加载模型文件地址
# 2 InceptionV3 预测速度慢且精度更高
# prediction.setModelTypeAsInceptionV3()
# prediction.setModelPath(
# os.path.join(execution_path, 'models',
# 'inception_v3_weights_tf_dim_ordering_tf_kernels.h5'))
# 3 ResNet 预测时间快,精度高
prediction.setModelTypeAsResNet()
prediction.setModelPath(
os.path.join(execution_path, 'models',
'resnet50_weights_tf_dim_ordering_tf_kernels.h5'))
# 4 squeezenet 预测时间最快,精度中等
# prediction.setModelTypeAsSqueezeNet()
# prediction.setModelPath(
# os.path.join(execution_path, 'models',
# 'squeezenet_weights_tf_dim_ordering_tf_kernels.h5'))
prediction.loadModel() # 加载模型
# 图片文件在执行目录的images子目录下
redictions, probabilities = prediction.predictImage(
os.path.join(execution_path, 'images', "1.jpg"),
result_count=5) # 加载待预测的图片地址,输出5个最高可能的类型
for eachPrediction, eachProbability in zip(predictions,
probabilities): # 输出格式 预测类型 : 可能性大小
print(eachPrediction, ' : ', eachProbability)
根据错误提示,缺少了tensorflow.python.keras.preprocessing模块,这可能是由于版本不兼容或者环境配置不正确引起的。可以尝试以下方法解决:
确保安装了正确的TensorFlow版本。ImageAI 2.1.6版本需要TensorFlow 1.x,ImageAI 4.0.0及更高版本需要TensorFlow 2.x。您可以通过以下命令安装TensorFlow:
pip install tensorflow==2.5.0
确认您已经安装了所需的所有依赖项。您可以使用以下命令检查和安装依赖项:
pip install tensorflow
pip install keras
pip install numpy
pip install scipy
pip install pillow
pip install h5py
pip install matplotlib
pip install opencv-python
pip install pandas
确认您的环境配置正确。您可以使用以下命令检查TensorFlow是否正在正确工作:
import tensorflow as tf
print(tf.__version__)
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
如果上述方法都不起作用,您可以尝试重新安装ImageAI,并检查其依赖项是否满足要求。如果仍然无法解决问题,建议尝试使用其他预测模型库。
答案来自 我点评开发社区 https://www.wodianping.com/
引用错误