AttributeError:模块“numpy”没有属性“object”。 `np.object` 是内置 `object` 的已弃用别名

问题描述 投票:0回答:1
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
tensorflow
,但问题仍然存在。

如何解决这个问题?

tensorflow fastapi attributeerror
1个回答
0
投票

numpy
1.24 版本起,
np.object
已弃用,需要替换为
object
- 这就是发行说明中所说的(numpy 发行说明)。您需要在代码或您正在使用的其他包中更新此内容。 由于您使用的是经过训练的模型,因此一种解决方案就是恢复到
numpy=1.23.4
,它将解决问题:

pip install numpy==1.23.4

附注在

numpy 1.23.4
中,它仍然被弃用,但没有完全从包中删除,因此它仍然会抛出警告,但它会起作用。如果您不想要警告,也可以返回
numpy==1.19
,但这可能会产生其他依赖项的问题,因此我建议使用
numpy==1.23.4
并使用
warnings
库来忽略警告消息

这是我的测试代码:

import warnings
import numpy as np
warnings.filterwarnings("ignore")
print("Version: ",np.__version__)
print("np.object: ",np.object)

输出:

Version:  1.23.4
np.object:  <class 'object'>
© www.soinside.com 2019 - 2024. All rights reserved.