Deep Learning model deployment using Flask

Sumit Kothari
Mar 15 · 3 min read


Usage / Installation


git clone
cd mnist-demo
pip install -r requirements.txt

Code Structure

code structure of flask webapp

DL Model

Training deeplearning model, y_train, epochs=5)
model.evaluate(x_test, y_test)
# Save entire model to a HDF5 file'mnist_ann_model.h5')

Testing deeplearning model

# load model
model = tf.keras.models.load_model('tensorflow_model/mnist_ann_model.h5')
graph = tf.get_default_graph()
def predict_image(test_image):
# load test image, resize and normalize it
img =
img.thumbnail(image_size, Image.ANTIALIAS)
img = img.convert('L')
image_data = np.asarray(img, dtype=np.float32)
image_data = image_data / 255
image_data_test = image_data.reshape((1, image_size[0], image_size[1]))
global graph
with graph.as_default():
# predit the output
classes = model.predict(image_data_test)
image_pred = str(np.argmax(classes))
confidence = round(classes[0][np.argmax(classes)], 2) * 100
print(image_pred, confidence)

return image_pred, confidence

Flask Webapp & Integrating DL model

@app.route('/', methods=['GET', 'POST'])
def upload_file():
return render_template('index.html')
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
return redirect('/error')
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
return redirect('/error')
from tensorflow_model.predict import predict_image as model_predict
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)['UPLOAD_FOLDER'], filename)) image_pred, confidence = model_predict(file)
messages = {
'file': 'uploads/' + filename,
'image_pred': str(image_pred),
'confidence': str(confidence)

messages = json.dumps(messages)
return redirect(url_for('file_predict', messages=messages))
def file_predict():
messages = request.args['messages']
messages = json.loads(messages)
return render_template('predict.html', predicted_value=messages['image_pred'],
<h3>Predicted Value: </h3><h1>{{predicted_value}}</h1>
<h3>Prediction Confidence: </h3><h1>{{predicted_confidence}}</h1>
<h3>Orignal Image</h3>
<img src="{{image}}" height="auto" />
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade