使用FastAPI加载TensorFlow模型时遇ImportError问题求助
问题分析与解决方案
问题本质
这是典型的依赖版本不兼容问题。错误核心是当前安装的typing_extensions版本过低,TypeAliasType是该库4.1.0及以上版本才新增的特性,而你的环境里的版本不包含这个类,导致Pydantic(FastAPI的核心依赖)导入失败。
解决方案
方案1:升级typing_extensions
直接升级到满足要求的版本:
pip install --upgrade typing_extensions>=4.1.0
方案2:固定依赖版本适配旧环境
由于你使用的TensorFlow 2.5.0是较旧版本,建议安装与之兼容的FastAPI和Pydantic版本,避免后续出现更多依赖冲突:
pip install fastapi==0.95.2 pydantic==1.10.12
方案3:用虚拟环境隔离依赖(推荐)
为项目创建独立虚拟环境,彻底避免全局依赖干扰:
# 创建虚拟环境 python -m venv ct_detection_env # Windows激活环境 ct_detection_env\Scripts\activate # 安装指定版本的所有依赖 pip install tensorflow==2.5.0 tensorflow-serving-api==2.5.0 fastapi==0.95.2 uvicorn pillow numpy
代码优化提示
你的predict函数目前没有返回结果,补充后才能正常返回预测信息:
@app.post("/predict") async def predict( file: UploadFile = File(...) ): image = read_file_as_image(await file.read()) img_batch = np.expand_dims(image, 0) predictions = MODEL.predict(img_batch) predicted_class = CLASS_NAMES[np.argmax(predictions[0])] confidence = np.max(predictions[0]) return { "predicted_class": predicted_class, "confidence_score": float(confidence) }
内容的提问来源于stack exchange,提问作者Marcelo
相关产品推荐
相关产品推荐

