Django & TensorFlow

P4k D3velopers
Django Unleashed
Published in
6 min readMar 21, 2024

How to use your AI TensorFlow model in your Django project.

Leonardo.Ai image.

Hi to everyone! In this article I’ll explain how to load an AI TensorFlow model and make predictions with it from a Django application.

For this article I’ll skip the creation of a Django application and a TensorFlow model. Let’s assume we already have both.

Missing Django or TensorFlow model?

If you are missing a Django project or a TensorFlow model then I recommend you to read this articles first:

If you already have both skip this part.

Django project creation:

AI TensorFlow model creation:

Place your model

In the end of this article TensorFlow AI model for RGB color recognition (Part 2) we generated a model called ‘my_colors.keras’, which is the one that I’ll use in the examples.

The model I’ll use, is a trained TensorFlow model to predict RGB color combinations and classify the result between 12 normalized color categories:

color_names: list = ['black',
'blue',
'brown',
'gray',
'green',
'maroon',
'orange',
'pink',
'purple',
'red',
'white',
'yellow']

Note that the previous color categories match the normalized categories from my dataset. See the section ‘ Download or build a dataset’ from the article TensorFlow AI model for RGB color recognition (Part 1).

Since I’m including a TensorFlow model in Django we’ll create a Django project named ‘Colors’, with an application inside called ‘RGBPredictor and I renamed the main project folder from ‘Colors’ to ‘ColorsProject’.

Django don’t care the name of the main project folder, so you can rename it as you want.

Now lets include our AI TensorFlow model to the ‘ColorsProject’, but where? We’ll place it inside theColorsProject’ where the ‘manage.py’ file is.

After place the model, your project structure should look like this:

Django project structure with TensorFlow model.

Load TensorFlow model

Load our TensorFlow model is very simple, and you can load it from any Python’s file you need from the project. We can do it like this:

from keras import models

# Load model
rgb_color_model: Sequential = models.load_model('my_colors.keras')

Model predictions

To make predictions, we’ll design very fast, without stopping in details, a view called ‘index()’ in the ‘views.py’:

# ---------------------------------------------------------------------
# VIEWS
# ---------------------------------------------------------------------
def index(request):
'''
This is the function that will serve the landing view of the
SequenceApp application.
'''

# GET request
if request.method == 'GET':

# Template context
context: dict = {'title': 'RGB Predictor'}
# Return view
return render(request, 'RGBPredictor/base.html', context)

Also a form to submit the color to predict in the ‘base.html’ template:

<form action="{% url 'RGBPredict:index' %}" method="post" id="add_seq_form" class="text-center p-4 bg-dark bg-opacity-50 rounded">
<p class="w-100 text-center text-white fw-bold fs-4 m-0 mb-1 p-2 rounded">Select color</p>

<!-- Cross-Site Request Forgery -->
{% csrf_token %}

<!-- COLOR INPUT TYPE -->
<input class="w-100 mt-0 mb-2" type="color" name="color_to_predict">

<!-- SUBMIT BUTTON -->
<button class="w-100 btn btn-sm btn-light mb-4 p-2" name="add_seq">Predict color</button>
</form>

And receive the submitted form data in the ‘views.py’ file a by a ‘POST’ request method:

# POST request
if request.method == 'POST':

# Get hexadecimal color to predict
color_to_predict: str = request.POST['color_to_predict']

Problem!

Once here you are probably thinking in the problem we have. This input with type ‘color’, will obviously submit a color, but in hexadecimal format.

We need to convert the hexadecimal color to RGB color.

Hexadecimal color to RGB color conversion

How to do that?

An hexadecimal number is build in the next format: #123456.

To convert an hexadecimal color to a RGB color, we need to :

  • Remove the ‘#’ symbol from the rest of numbers ‘123456’.
hex_color:   str   = color_to_predict.replace("#", '')
  • Split the number ‘123456’ in new numbers of two digits (12, 34, 56).
  • Since the three numbers (12, 34, 56) are part of an hexadecimal color string, we can use the the inbuilt type casting method ‘int’ with base 16 to convert the tree numbers (12, 34, 56) from hexadecimal to integers numbers like this:
rgb_color:    list    = [int(hex_color[index:index+2], 16)
for index in (0, 2, 4)]

This Python’s list-comprehension will result in a list of three values, the values we need for a color in RGB format.

Prediction

Once we have our three integer values as RGB color values, we want to see the prediction of our TensorFlow model. To do that we need to do five simple things to get our prediction:

  • Convert our RGB color values to a Numpy array like this:
import numpy as np

# rgb tuple to numpy array
rgb_array = np.asarray((rgb_color[0],
rgb_color[1],
rgb_color[2]))
  • Give a new shape to the Numpy array without changing its data. In our case our shape is 1x3 since we have 1 round of tree values. To reshape use the Numpy ‘reshape()’ method:
# Reshaping as per input to ANN model
rgb_reshaped = np.reshape(rgb_array, (-1,3))
  • Use TensorFlow ‘predict()’ method to predict the RGB color. This will give us one prediction value for each one of the 12 normalized color categories:
# Output of layer is in terms of Confidence of my 12 color classes
color_class_confidence = rgb_color_model.predict(rgb_reshaped)
  • Find the index of the value with higher confidence:
# Finding the color_class index with higher confidence
color_index = np.argmax(color_class_confidence, axis=1)
  • Find the color that matches the same index than the index with higher confidence:
color_names: list = ['black',
'blue',
'brown',
'gray',
'green',
'maroon',
'orange',
'pink',
'purple',
'red',
'white',
'yellow']

# Traduce the result to a human readble color
color: str = color_names[int(color_index)]

At that point what we only need to do is to pass the result of the prediction stored in the ‘color’ variable, to the view through the ‘index()’ view function placed in the ‘views.py’ file.

Test RGB Predictor application

Let’s try our prototype of web application to predict RGB colors.

Execute the project and open the landing view url in a browser:

Landing view

Landing view of RGBPredictor application.

Select color to predict

RGBPredictor select color..

Predict

Orange prediction.
Green prediction.
Pink prediction.
Purple prediction.

Up to here this article. I hope it was interesting and useful!

Please clap the article if you like it!

--

--

P4k D3velopers
Django Unleashed

Writes about Python Web Development (Django/Flask) and Data Science (Python/pandas/statistics/) || Scientist || Prototype creator || Side hustles