Black Lives Matter. Please consider donating to Black Girls Code today.

Using a trained and saved keras .h5 model!

Hello Dash Community,

I am trying to make a simple API which takes the input of an image using input function and when a button is pressed, there should be a callback which predicts the object in the image and outputs with a bounding box on the image with the already saved weights in the keras model. Is it possible in the dash to use a saved h5py format model.?


Yes, and it works (although this pipeline is good only for POCs and not for production).
Shortly explained: use a dash button component and an image canvas from plotly, assign a callback with input by the clickEvent of the button (use n_clicks property for instance). Then, in the callback function, do whatever you want - load your Keras model, take the input image (you can use upload file component) as a state argument to the callback and feed it to your model, wait for response from the model (res = model(image)) , create the figure for the graph component and update it in your output.

I will not get into details here about what is going behind the scenes, but you can read the official Dash docs for the upload compnent to see a short example on handling files in this framework.
However, I want to point out that if you take a large CNN model, it will most likely take a couple of seconds to the model to response. Moreover, loading the model in the callback will again make it slow and clumsy. You can pre-load the model and serve it in a different Flask instance, and use the callback to make requests to the model instance and get the response in the Dash instance. If you like something simpler but smooth enough, just pre-load the model in the Dash framework and use the callback only to make the prediction.
Having said that, I refrain from making complex architectures in Dash since this framework is still very premature in terms of production and deployment, and even in terms of implementing existing capabilities like other “real” frameworks do (Anglular, Vue, React). Since its just POCs, sufficient UX in the dashboards is enough.