Create a user-friendly interface for your scikit learn models using Python

Posted by


As data scientists, we often use powerful machine learning libraries like scikit-learn to build and train models on our data. These models can provide invaluable insights and predictions that can help us make informed decisions. However, once these models are trained, they are often tucked away in the back-end, and we may want to showcase them in a more user-friendly way. This is where building a front-end for our scikit-learn models using Python can come in handy.

In this tutorial, we will walk through the steps of building a simple front-end using Python for a scikit-learn model. We will be using a Flask web application to create a simple user interface where users can input data, run predictions using our trained model, and see the results displayed on the screen.

Step 1: Train your scikit-learn model

First, we need to train a scikit-learn model that we want to showcase in our front-end. For this tutorial, we will use a simple example of training a linear regression model on a dataset.

import numpy as np
from sklearn.linear_model import LinearRegression

# Generate some random data
X = np.random.rand(100, 1)
y = 2 * X.squeeze() + np.random.normal(0, 0.1, 100)

# Train a linear regression model
model = LinearRegression()
model.fit(X, y)

Step 2: Create a Flask web application

Next, we will create a Flask application that will serve as the front-end for our trained model. First, make sure you have Flask installed by running pip install Flask.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return 'Welcome to the scikit-learn model front-end!'

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    input_data = np.array(data['input'])
    prediction = model.predict(input_data.reshape(1, -1))[0]
    return jsonify({'prediction': prediction})

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Run your Flask application

Save the above code in a file named app.py and run the Flask application by executing python app.py in your command line. You should see a message indicating that the Flask application is running.

Step 4: Test your application

You can now test your Flask application by sending a POST request to the /predict endpoint with some input data. You can do this using a tool like Postman or by writing a simple Python script.

import requests

url = 'http://127.0.0.1:5000/predict'
data = {'input': [0.5]}
response = requests.post(url, json=data)

print(response.json())

This script should send a POST request to your Flask application with an input of 0.5, and the response should display the prediction made by your trained model.

Step 5: Build a user interface

To enhance the user experience, you can build a simple HTML form that allows users to input data and see the predictions displayed on the screen. Modify the Flask application to render an HTML template with a form.

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    input_data = float(request.form['input'])
    prediction = model.predict(np.array([[input_data]]))[0]
    return render_template('index.html', prediction=prediction)

if __name__ == '__main__':
    app.run(debug=True)

Create a folder named templates in the same directory as your app.py file, and create an HTML file named index.html inside the templates folder. Here is a sample index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>scikit-learn Model Front-end</title>
</head>
<body>
    <h1>Enter input data:</h1>
    <form action="/predict" method="post">
        <input type="text" name="input">
        <input type="submit" value="Predict">
    </form>
    {% if prediction %}
    <h2>Prediction: {{ prediction }}</h2>
    {% endif %}
</body>
</html>

Step 6: Run your Flask application again

Save the modifications to your Flask application and HTML template, and run the Flask application by executing python app.py. You should now see a user-friendly interface where users can input data and see the predictions displayed on the screen.

Congratulations! You have successfully built a front-end for your scikit-learn model using Python and Flask. Feel free to customize the interface further and add more features to enhance the user experience.