Forums

Cannot load .h5 model with joblib

I cannot load the models required for the post request in my flask app. the error only occurs in the deployed web app

This is the code where the error occurs

def __load_model(self, model_name):
    try:
        model = joblib.load(model_name)
        print("Model Loaded!")
        return model
    except:
        print("Error loading the model")

since the model isn't loaded the below error appears

2023-01-13 08:09:28,362: Exception on /model [POST]
Traceback (most recent call last):
 File "/home/budawath/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/home/budawath/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1822, in 
full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/budawath/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1820, in 
full_dispatch_request
rv = self.dispatch_request()
File "/home/budawath/.virtualenvs/env/lib/python3.7/site-packages/flask/app.py", line 1796, in 
dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
 File "/home/budawath/medicare_server/rest_api_app.py", line 15, in post_model
final_output = model.run_model()
 File "/home/budawath/medicare_server/ml_model_loader.py", line 16, in run_model
self.__load_covid(model_name)
 File "/home/budawath/medicare_server/ml_model_loader.py", line 31, in __load_covid
self.final_dict = self.__create_dict(self.answer_list, model_name, self.model_inp_list)
 File "/home/budawath/medicare_server/ml_model_loader.py", line 84, in __create_dict
risk_probability = self.__probab_calc2(answer_list, model_name, model_inp_list)
 File "/home/budawath/medicare_server/ml_model_loader.py", line 102, in __probab_calc2
if self.__predict_inputs(model_inp_list, model_name) == 0:
 File "/home/budawath/medicare_server/ml_model_loader.py", line 139, in __predict_inputs
model_output = model.predict([input_list])  # predicts the model_inp_list passed to this function
AttributeError: 'NoneType' object has no attribute 'predict'

Is it possible to fix this error

The server log also shows the following: 'Error loading the model'

It would be useful to know what the underlying cause is; right now, your code "swallows" the exception and replaces all of the details about the problem with the text "Error loading the model". I would recommend removing the try/except block from __load_model and just letting the exception propagate up, because it looks like the code that follows it depends on the model being valid, so there's no point in letting it run -- you'll just get another exception later on, like the AttributeError that you're currently seeing.

If you do that, then the full stack trace from the joblib.load call will appear in the error log, and then you'll find it easier to debug.