Spaces:
Sleeping
Sleeping
André Fernandes
commited on
Commit
·
48b647e
1
Parent(s):
0f764c5
added predict method for a classic ML classifier model (wip)
Browse files- app.py +55 -13
- models/iris.py +7 -0
- models/iris_v1.joblib +3 -0
- models/ml/train.py +30 -0
app.py
CHANGED
|
@@ -1,47 +1,76 @@
|
|
| 1 |
-
from typing import Optional
|
| 2 |
|
| 3 |
from fastapi import FastAPI, HTTPException
|
| 4 |
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class Model(BaseModel):
|
| 8 |
id: int
|
| 9 |
name: str
|
| 10 |
param_count: Optional[int] = None
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
models = [Model(id=0, name="CNN"), Model(id=1, name="Transformer")]
|
| 20 |
-
id_2_hosted_models = {
|
| 21 |
-
model.id : model for model in models
|
| 22 |
}
|
|
|
|
|
|
|
|
|
|
| 23 |
model_names_2_id = {
|
| 24 |
-
model.name.lower() : model.id for model in models
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
@app.get("/")
|
| 29 |
def greet_json():
|
| 30 |
return {"Hello World": "Welcome to my ML Repository API!"}
|
| 31 |
|
|
|
|
| 32 |
@app.get("/hosted")
|
| 33 |
def list_models():
|
| 34 |
"List all the hosted models."
|
| 35 |
return models
|
| 36 |
|
|
|
|
| 37 |
@app.get("/hosted/id/{model_id}")
|
| 38 |
def get_by_id(model_id: int):
|
| 39 |
"Get a specific model by its ID."
|
| 40 |
if model_id not in id_2_hosted_models:
|
| 41 |
-
raise HTTPException(status_code=404, detail=f"Model with id={model_id} not found")
|
| 42 |
|
| 43 |
return id_2_hosted_models[model_id]
|
| 44 |
|
|
|
|
| 45 |
@app.get("/hosted/name/{model_name}")
|
| 46 |
def get_by_name(model_name: str):
|
| 47 |
"Get a specific model by its name."
|
|
@@ -50,4 +79,17 @@ def get_by_name(model_name: str):
|
|
| 50 |
if model_name not in model_names_2_id:
|
| 51 |
raise HTTPException(status_code=404, detail=f"Model '{model_name}' not found")
|
| 52 |
|
| 53 |
-
return id_2_hosted_models[model_names_2_id[model_name]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Any
|
| 2 |
|
| 3 |
from fastapi import FastAPI, HTTPException
|
| 4 |
from pydantic import BaseModel
|
| 5 |
+
from contextlib import asynccontextmanager
|
| 6 |
+
from joblib import load
|
| 7 |
+
|
| 8 |
+
from models.iris import Iris
|
| 9 |
|
| 10 |
|
| 11 |
class Model(BaseModel):
|
| 12 |
id: int
|
| 13 |
name: str
|
| 14 |
param_count: Optional[int] = None
|
| 15 |
+
_model : Optional[Any] = None
|
| 16 |
|
| 17 |
|
| 18 |
+
models = {
|
| 19 |
+
"0" : Model(id=0, name="CNN"),
|
| 20 |
+
"1" : Model(id=1, name="Transformer"),
|
| 21 |
+
"2" : Model(id=2, name="Iris"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
}
|
| 23 |
+
id_2_hosted_models = {
|
| 24 |
+
model.id : model for model in models.values()
|
| 25 |
+
}
|
| 26 |
model_names_2_id = {
|
| 27 |
+
model.name.lower() : model.id for model in models.values()
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
#TODO: fix this mess ^^
|
| 31 |
+
ml_models = {
|
| 32 |
+
model.name : model for model in models.values()
|
| 33 |
}
|
| 34 |
|
| 35 |
+
@asynccontextmanager
|
| 36 |
+
async def lifespan(app: FastAPI):
|
| 37 |
+
# Load the ML model
|
| 38 |
+
ml_models["Iris"]._model = load('models/iris_v1.joblib')
|
| 39 |
+
yield
|
| 40 |
+
# Clean up the ML models and release the resources
|
| 41 |
+
ml_models.clear()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
################################################################
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
app = FastAPI(
|
| 48 |
+
title="ML Repository API",
|
| 49 |
+
description="API for getting predictions from hosted ML models.",
|
| 50 |
+
version="0.0.1",
|
| 51 |
+
lifespan=lifespan)
|
| 52 |
+
|
| 53 |
|
| 54 |
@app.get("/")
|
| 55 |
def greet_json():
|
| 56 |
return {"Hello World": "Welcome to my ML Repository API!"}
|
| 57 |
|
| 58 |
+
|
| 59 |
@app.get("/hosted")
|
| 60 |
def list_models():
|
| 61 |
"List all the hosted models."
|
| 62 |
return models
|
| 63 |
|
| 64 |
+
|
| 65 |
@app.get("/hosted/id/{model_id}")
|
| 66 |
def get_by_id(model_id: int):
|
| 67 |
"Get a specific model by its ID."
|
| 68 |
if model_id not in id_2_hosted_models:
|
| 69 |
+
raise HTTPException(status_code=404, detail=f"Model with 'id={model_id}' not found")
|
| 70 |
|
| 71 |
return id_2_hosted_models[model_id]
|
| 72 |
|
| 73 |
+
|
| 74 |
@app.get("/hosted/name/{model_name}")
|
| 75 |
def get_by_name(model_name: str):
|
| 76 |
"Get a specific model by its name."
|
|
|
|
| 79 |
if model_name not in model_names_2_id:
|
| 80 |
raise HTTPException(status_code=404, detail=f"Model '{model_name}' not found")
|
| 81 |
|
| 82 |
+
return id_2_hosted_models[model_names_2_id[model_name]]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@app.post("/hosted/name/{model_name}/predict", tags=["Predictions"])
|
| 86 |
+
async def get_prediction(model_name: str, iris: Iris):
|
| 87 |
+
|
| 88 |
+
if model_name.lower() != "iris":
|
| 89 |
+
raise HTTPException(status_code=501, detail="Not implemented yet.")
|
| 90 |
+
|
| 91 |
+
data = dict(iris)['data']
|
| 92 |
+
prediction = ml_models["Iris"]._model.predict(data).tolist()
|
| 93 |
+
log_probs = ml_models["Iris"]._model.predict_proba(data).tolist()
|
| 94 |
+
return {"predictions": prediction,
|
| 95 |
+
"log_probs": log_probs}
|
models/iris.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from pydantic import BaseModel, conlist
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Iris(BaseModel):
|
| 7 |
+
data: List[conlist(float, min_length=4, max_length=4)] # type: ignore
|
models/iris_v1.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:08b4855f249d786bfaeb015eb7db4ee4d91948434a68a81285bfce06315054e6
|
| 3 |
+
size 3496
|
models/ml/train.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Literal, Optional
|
| 2 |
+
|
| 3 |
+
from joblib import dump
|
| 4 |
+
from sklearn import datasets
|
| 5 |
+
from sklearn.pipeline import Pipeline
|
| 6 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 7 |
+
from sklearn.tree import DecisionTreeClassifier
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_dataset(dataset_name: Literal["iris", "other"]):
|
| 11 |
+
if dataset_name != "iris":
|
| 12 |
+
raise NotImplementedError()
|
| 13 |
+
|
| 14 |
+
dataset = datasets.load_iris(return_X_y=True)
|
| 15 |
+
return dataset[0], dataset[1]
|
| 16 |
+
|
| 17 |
+
def train_ml_classifier(X, y, output_file: Optional[str] = None):
|
| 18 |
+
clf_pipeline = [('scaling', MinMaxScaler()),
|
| 19 |
+
('classifier', DecisionTreeClassifier(random_state=42))]
|
| 20 |
+
pipeline = Pipeline(clf_pipeline)
|
| 21 |
+
pipeline.fit(X, y)
|
| 22 |
+
|
| 23 |
+
if output_file is not None:
|
| 24 |
+
dump(pipeline, output_file)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
|
| 29 |
+
X, y = load_dataset('iris')
|
| 30 |
+
model = train_ml_classifier(X, y, output_file='./iris_v1.joblib')
|