You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级numpy和tensorflow后仍遇np.object属性错误,如何解决?

问题描述

升级numpy和tensorflow至最新版本后,运行FastAPI图像预测代码时仍报错:AttributeError: module 'numpy' has no attribute 'object'。错误提示指出np.object是内置object的已弃用别名,应直接使用object,但调整后问题仍未解决。

运行代码

import tensorflow as tf
from tensorflow.keras.models import load_model
from fastapi import FastAPI, File, UploadFile
from io import BytesIO
from PIL import Image
import numpy as np
import uvicorn

app = FastAPI()

MODEL = load_model("../models/1")
CLASS_NAMES = ["Early Blight", "Late Blight", "Healthy"]

@app.get("/ping")
async def ping():
    return "Hello, I am alive"

def read_file_as_image(data) -> np.ndarray:
    image = np.array(Image.open(BytesIO(data)))
    return image

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    image = read_file_as_image(await file.read())
    image_batch = np.expand_dims(image, axis=0)
    predictions = MODEL.predict(image_batch)
    predicted_class = CLASS_NAMES[np.argmax(predictions[0])]
    confidence = np.max(predictions[0])
    return {
        'class': predicted_class,
        'confidence': float(confidence)
    }

if __name__ == "__main__":
    uvicorn.run(app, host='localhost', port=8000)

错误信息

AttributeError: module 'numpy' has no attribute 'object'.
np.object was a deprecated alias for the builtin object. To avoid this error in existing code, use object by itself. Doing this will not modify any behavior and is safe.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

解决办法
  • 重新训练并保存模型:你加载的模型文件是用旧版本numpy训练保存的,内部代码依赖了np.object这个已弃用的别名。用当前环境的tensorflow和numpy重新训练模型,替换掉原模型文件即可解决。
  • 添加临时兼容映射:在代码最开头插入以下代码,手动将np.object映射为内置object,适配依赖旧别名的组件:
    import numpy as np
    np.object = object
    
  • 排查并更新间接依赖:除了tensorflow和numpy,项目中的其他依赖库(如PIL、keras相关组件)可能仍在使用np.object。通过pip list查看所有库版本,更新到最新稳定版;或者根据错误堆栈的调用链,定位到具体触发错误的库进行处理。
  • 降级numpy到兼容版本:如果最新版numpy与tensorflow存在兼容性问题,可降级numpy到1.23.x版本(该版本仍保留np.object别名,且与新版tensorflow兼容性较好),执行命令:
    pip install numpy==1.23.5
    

内容的提问来源于stack exchange,提问作者Navaneeth kini K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:35:25