DEV Community

Yixin Cao
Yixin Cao

Posted on

Building a Flask Application with a Decision Tree Classifier for the Iris Dataset

This blog is fully powered by ChatGPT 3.5. Application process tested.

In this tutorial, we will be building a web application using Flask that uses a decision tree classifier to predict the species of an iris flower based on its sepal length, sepal width, petal length, and petal width. We will be using the Iris dataset from scikit-learn to train the decision tree classifier.

Prerequisites

Before we begin, make sure that you have the following installed on your machine:

  • Python 3
  • Flask
  • scikit-learn
  • pandas

Getting Started

First, let's create a new directory for our project and navigate into it:

mkdir flask-iris-prediction
cd flask-iris-prediction
Enter fullscreen mode Exit fullscreen mode

Next, create a new Python file called app.py and open it in your favorite text editor:

touch app.py
Enter fullscreen mode Exit fullscreen mode

In app.py, import the necessary modules:

from flask import Flask, render_template, request
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
Enter fullscreen mode Exit fullscreen mode

Create a new Flask application:

app = Flask(__name__)
Enter fullscreen mode Exit fullscreen mode

Define a route for the home page:

@app.route('/')
def home():
    return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

Define a route for the prediction page:

@app.route('/predict', methods=['POST'])
def predict():
    # Load iris dataset
    iris = load_iris()
    X = iris.data
    y = iris.target

    # Train decision tree classifier
    clf = DecisionTreeClassifier()
    clf.fit(X, y)

    # Get user input from HTML form
    sepal_length = float(request.form['sepal_length'])
    sepal_width = float(request.form['sepal_width'])
    petal_length = float(request.form['petal_length'])
    petal_width = float(request.form['petal_width'])

    # Make prediction
    prediction = clf.predict([[sepal_length, sepal_width, petal_length, petal_width]])

    # Return result to HTML page
    return render_template('index.html', prediction=prediction)
Enter fullscreen mode Exit fullscreen mode

Finally, add a check to make sure that the application is being run directly and not imported:

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Creating the HTML Templates

Create a new directory called templates:

mkdir templates
Enter fullscreen mode Exit fullscreen mode

Inside the templates directory, create a new HTML file called index.html:

touch templates/index.html
Enter fullscreen mode Exit fullscreen mode

Open index.html in your text editor and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Iris Prediction</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Iris Prediction</h1>
    <form method="POST" action="{{ url_for('predict') }}">
        <label for="sepal_length">Sepal Length:</label>
        <input type="text" name="sepal_length" id="sepal_length" required>
        <br>
        <label for="sepal_width">Sepal Width:</label>
        <input type="text" name="sepal_width" id="sepal_width" required>
        <br>
        <label for="petal_length">Petal Length:</label>
        <input type="text" name="petal_length" id="petal_length" required>
        <br>
        <label for="petal_width">Petal Width:</label>
        <input type="text" name="petal_width" id="petal_width" required>
        <br>
        <button type="submit">Predict</button>
    </form>
    {% if prediction %}
    <p>The predicted species is {{ prediction[0] }}</p>
    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here we have a simple HTML form with input fields for the four features of the Iris dataset, and a "Predict" button that will send the form data to our Flask application. If a prediction has been made, the result will be displayed below the form.

Adding Some Style

Create a new directory called static:

mkdir static
Enter fullscreen mode Exit fullscreen mode

Inside the static directory, create a new CSS file called style.css:

touch static/style.css
Enter fullscreen mode Exit fullscreen mode

Open style.css in your text editor and add the following code:

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f0f0f0;
}

h1 {
    text-align: center;
    margin-top: 20px;
}

form {
    max-width: 500px;
    margin: 0 auto;
    background-color: #fff;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

label {
    display: block;
    margin-bottom: 5px;
}

input {
    display: block;
    width: 100%;
    margin-bottom: 10px;
    padding: 10px;
    font-size: 16px;
    border-radius: 5px;
    border: none;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

button {
    background-color: #4CAF50;
    color: #fff;
    padding: 10px;
    font-size: 16px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #3e8e41;
}

p {
    text-align: center;
    margin-top: 20px;
}
Enter fullscreen mode Exit fullscreen mode

This will add some style to our HTML form and make it look more visually appealing.

Running the Application

To run the application, execute the following command:

python app.py
Enter fullscreen mode Exit fullscreen mode

This will start the Flask development server on http://localhost:5000/.

Open your web browser and navigate to http://localhost:5000/ to see the home page.

Enter some values for the four features of the Iris dataset and click the "Predict" button. The predicted species will be displayed below the form.

Demo

Here is a quick demo of the application in action:

Image description

In this demo, we can see that the user has entered values for the four features of an iris flower, and clicked the "Predict" button. The application then displays the predicted species of the iris flower based on the input values.

This is just a small example of what you can do with Flask and machine learning. With a little bit of creativity and knowledge, you can build powerful applications that can make predictions based on data.

Conclusion

In this tutorial, we have built a simple Flask application that uses a decision tree classifier to predict the species of an iris flower based on its features. We have also added some style to the HTML form using CSS. Flask is a powerful web framework that makes it easy to build web applications with Python. With a little bit of knowledge about web development and machine learning, you can create powerful applications that can make predictions based on data.

Top comments (0)