MENU

[AI from Scratch] Episode 234: Web Application Development with Flask — Embedding a Model in a Simple Web App

TOC

Recap and Today’s Theme

Hello! In the previous episode, we learned how to deploy models using Flask by building a simple Web API. We saw how an API can provide access to trained models, allowing real-time predictions as a service.

This time, we’ll take it a step further and explore how to integrate models into a web application using Flask. Beyond deploying models as APIs, this approach allows users to interact with the model through a web interface and view prediction results interactively. This will help you understand how to incorporate machine learning models into real applications. Let’s dive into building a simple web application using Flask.

What Is Flask?

Flask is a lightweight web framework for building web applications and APIs in Python. It is simple, flexible, and widely used for developing everything from small-scale applications to APIs.

Key features of Flask include:

  1. Simple and Lightweight: Minimal features for ease of learning.
  2. Flexibility: Allows for building customized web applications using plugins and extensions.
  3. Rapid Development: With a straightforward structure, Flask enables quick prototyping and application development.

Designing a Simple Web Application

First, we will design a simple web application using Flask, incorporating a trained model within it. The web application we will build includes the following features:

  • An interface where users can input data via a form.
  • A process that receives the input data and uses a trained model for prediction.
  • A webpage that displays the prediction results.

By embedding the model within the web application, users can interact with the prediction function in real time.

Installing the Required Libraries

First, install Flask and TensorFlow (or Keras) for building the web application and loading the trained model.

pip install flask tensorflow

Preparing the Trained Model

First, create a simple model and save it. Below is an example of a simple model for classifying numbers.

import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np

# Defining the model
model = models.Sequential([
    layers.Dense(128, activation='relu', input_shape=(4,)),  # Input has 4 features
    layers.Dense(64, activation='relu'),
    layers.Dense(3, activation='softmax')  # 3-class classification
])

# Compiling the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Training with dummy data
x_train = np.random.rand(100, 4)
y_train = np.random.randint(3, size=100)
model.fit(x_train, y_train, epochs=10)

# Saving the model
model.save('simple_model.h5')
  • model.save(‘simple_model.h5’): Saves the model to a file. This file will be loaded and used for predictions in the web application.

Creating the Flask Application

Next, we create a Flask application and load the saved model for use within the web application.

1. Setting Up the Flask Application

First, create a file named app.py and write the following code:

from flask import Flask, render_template, request
import tensorflow as tf
import numpy as np

# Initializing the Flask application
app = Flask(__name__)

# Loading the trained model
model = tf.keras.models.load_model('simple_model.h5')

# Routing for the homepage
@app.route('/')
def home():
    return render_template('index.html')

# Routing for prediction
@app.route('/predict', methods=['POST'])
def predict():
    # Getting data from the form
    input_data = [float(request.form['feature1']),
                  float(request.form['feature2']),
                  float(request.form['feature3']),
                  float(request.form['feature4'])]

    # Making predictions using the model
    prediction = model.predict(np.array([input_data]))
    predicted_class = np.argmax(prediction)

    # Displaying the result
    return render_template('result.html', prediction=predicted_class)

# Running the application
if __name__ == '__main__':
    app.run(debug=True)

2. Creating Template Files

Flask uses HTML templates to generate web pages. Save the template files in a folder called templates.

(1) index.html (Input Form)

Create templates/index.html with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Flask App</title>
</head>
<body>
    <h1>Enter Data</h1>
    <form action="/predict" method="POST">
        <label for="feature1">Feature 1:</label>
        <input type="text" id="feature1" name="feature1"><br><br>
        <label for="feature2">Feature 2:</label>
        <input type="text" id="feature2" name="feature2"><br><br>
        <label for="feature3">Feature 3:</label>
        <input type="text" id="feature3" name="feature3"><br><br>
        <label for="feature4">Feature 4:</label>
        <input type="text" id="feature4" name="feature4"><br><br>
        <input type="submit" value="Predict">
    </form>
</body>
</html>

This form allows users to input four features and submit the data to the /predict endpoint.

(2) result.html (Displaying Prediction Results)

Next, create templates/result.html to display the prediction results:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prediction Result</title>
</head>
<body>
    <h1>Prediction Result</h1>
    <p>Predicted Class: {{ prediction }}</p>
    <a href="/">Back</a>
</body>
</html>

The {{ prediction }} part displays the prediction result sent from Flask.

3. Running the Application

Once all files are prepared, run app.py in the terminal.

python app.py

Access http://127.0.0.1:5000 in your browser to view the web application, enter data, and check the prediction results.

Best Practices for Deploying Flask Applications

  1. Enhancing Security: Validate user input to protect the application from threats like SQL injection or XSS attacks.
  2. Scalability: When deploying the application in a production environment, use WSGI servers like Nginx or Gunicorn to enhance performance and scalability.
  3. Operating on Cloud Platforms: Use cloud platforms like AWS, Heroku, or GCP to run the application in a scalable and reliable environment.

Summary

This episode covered how to create a web application with Flask by embedding a simple machine learning model. Flask allows you to quickly build interactive applications that enable users to interact with models and view real-time prediction results. Use this as a foundation for developing more complex applications and APIs in the future.

Next Episode Preview

Next time, we’ll explore creating and publishing APIs, showing how to provide models as APIs and the steps to publish them. Learn how to build and deploy your own APIs!


Notes

  • Flask: A lightweight Python web framework widely used for building APIs and web applications.
  • Template Engine: Flask uses the Jinja2 template engine, allowing you to embed Python variables and logic in HTML templates.
Let's share this post !

Author of this article

株式会社PROMPTは生成AIに関する様々な情報を発信しています。
記事にしてほしいテーマや調べてほしいテーマがあればお問合せフォームからご連絡ください。
---
PROMPT Inc. provides a variety of information related to generative AI.
If there is a topic you would like us to write an article about or research, please contact us using the inquiry form.

Comments

To comment

TOC