我正在使用Pydantic 模型通過FastAPI進行資料驗證來部署機器學習模型進行預測,因此我想處理以下例外/條件:
- 如果其中一個輸入與功能要求(型別、長度...)不匹配,則提供許多輸入,該輸入會針對特定的無效輸入拋出例外,但會顯示其他有效輸入的輸出
我想要達到的目標
輸入:
[
{
"name":"John",
"age": 20,
"salary": 15000
},
{
"name":"Emma",
"age": 25,
"salary": 28000
},
{
"name":"David",
"age": "test",
"salary": 50000
},
{
"name":"Liza",
"age": 5000,
"salary": 30000
}
]
輸出:
[
{
"prediction":"Class1",
"probability": 0.88
},
{
"prediction":"Class0",
"probability": 0.79
},
{
"?RROR: Expected type int but got str instead"
},
{
"?RROR: invalid age number"
}
]
我的基本模型類有什么:
from pydantic import BaseModel, validator
from typing import List
n_inputs = 3
n_outputs = 2
class Inputs(BaseModel):
name: str
age: int
salary: float
class InputsList(BaseModel):
inputs: List[Inputs]
@validator("inputs", pre=True)
def check_dimension(cls, v):
for point in v:
if len(point) != n_inputs:
raise ValueError(f"Input data must have a length of {n_inputs} features")
return v
class Outputs(BaseModel):
prediction: str
probability: float
class OutputsList(BaseModel):
output: List[Outputs]
@validator("output", pre=True)
def check_dimension(cls, v):
for point in v:
if len(point) != n_outputs:
raise ValueError(f"Output data must a length of {n_outputs}")
return v
我的問題是: -> 如何使用上面的代碼實作這種例外或條件處理?
uj5u.com熱心網友回復:
您可以通過解碼提交的 JSON 并自己處理串列來做到這一點。然后,當預期資料型別和提交的資料型別不匹配時,您可以ValidationError通過 Pydantic 獲得加薪。
from fastapi import FastAPI, Request
from pydantic import BaseModel, validator, ValidationError, conint
from typing import List
app = FastAPI()
class Inputs(BaseModel):
name: str
age: conint(lt=130)
salary: float
@app.post("/foo")
async def create_item(request: Request):
input_list = await request.json()
outputs = []
for element in input_list:
try:
read_input = Inputs(**element)
outputs.append(f'{read_input.name}: {read_input.age * read_input.salary}')
except ValidationError as e:
outputs.append(f'Invalid input: {e}')
return outputs
將您的串列提交到/foo端點會生成(在這種情況下)處理值串列或錯誤:
['John: 300000.0',
'Emma: 700000.0',
'Invalid input: 1 validation error for Inputs\nage\n value is not a valid integer (type=type_error.integer)',
'Invalid input: 1 validation error for Inputs\nage\n ensure this value is less than 130 (type=value_error.number.not_lt; limit_value=130)'
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472809.html
上一篇:如何在機器學習中加入驗證集?
