Finalizing our naive first iteration

Let's imagine we're building a service for the 311 call center. The goal is to estimate the expected time it will take to close the complaint. We will start with a terribly naive model—one that returns a median value for a given type of complaint. As such, it is essentially a pre-computed lookup, similar to the one we used earlier; computing the median is trivial, so we won't cover it. If needed, the code is stored in the repository. As a result, we have a JSON file with a simple key-value structure; for each type of complaint, it stores the median time.

Now, let's modify our existing API to use this data:

  1. First of all, copy the file and call it 311v1.py. Now, let's create a simple class that resembles a scikit-learn model, using lookup data:
class naive_model:
data = None

def __init__(self, path='./data/model.json'):

with open(path, 'r') as f:
self.data = json.load(f)

def predict(self, type_):
return self.data.get(type_, None)

Why do we make it similar to the scikit-learn models? Because that way, it would be easier to swap it with the real one in the future!

  1. Now, we only need to initialize the model on load and replace the hardcoded hour value with expected_time, predicted by the model:
app = FastAPI()
model = naive_model()

@app.get("/complaints/time/{complaint_type}")
def complaints(complaint_type: str):
return {"complaint_type": complaint_type,
"expected_time": model.predict(complaint_type)}
  1. Again, run it via Uvicorn:
uvicorn 311v1:app --reload
  1. Specify the type of complaint, as in the following example:
$ http://127.0.0.1:8000/complaints/time/noise
{"complaint_type":"water quality","expected_time":19.29}

Next, let's see how to validate this data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset