Ever imagined making my machine learning algorithm available to the world? In this tutorial, I’ll walk you through the process of deploying a basic machine learning model as an interactive website using Flask, GitHub, and Render. I’ve taken a highly hands-on approach, explaining each step—from building the model to deploying it—so you can follow along and create your own live web app.

1. Setting Up the Machine Learning Model

Let's start with a simple machine learning model using Scikit-learn. The model predicts a linear relationship: ( y = 2x ).

Step 1: Write the Model Script
Create a file called model.py with the following code:


import pickle
from sklearn.linear_model import LinearRegression
import numpy as np

# Create a simple linear regression model
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])

model = LinearRegression()
model.fit(X, y)

# Save the trained model
with open("model.pkl", "wb") as file:
    pickle.dump(model, file)

Step 2: Train the Model
Run the script:


python model.py

Here this generates a file named model.pkl, which contains the trained model. We’ll load this file in our Flask app for predictions.

2. Building the Flask App

Flask is a lightweight Python framework perfect for hosting machine learning models as web applications.

Step 1: Install Flask

Install Flask and other required libraries:


pip install flask scikit-learn

Step 2: Create the Flask Application

Create a file named app.py and add the following code:


from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

# Load the trained model
with open("model.pkl", "rb") as file:
    model = pickle.load(file)

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

@app.route('/predict', methods=['POST'])
def predict():
    try:
        input_value = float(request.form.get("input_value"))
        prediction = model.predict([[input_value]])[0]
        return render_template("index.html", prediction=f"The prediction is: {prediction}")
    except Exception as e:
        return render_template("index.html", prediction=f"Error: {str(e)}")

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

This app:

  • Displays a homepage where users can input values.
  • Sends the input to the /predict route to generate predictions.

3. Designing the Frontend

Save the following HTML code as templates/index.html to create a simple user interface:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ML Model Prediction</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f9;
            text-align: center;
        }
        .container {
            max-width: 400px;
            margin: 50px auto;
            background: #ffffff;
            padding: 20px;
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        button {
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 20px;
            font-size: 1.2em;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>ML Model Prediction</h1>
        <form action="/predict" method="POST">
            <input type="number" name="input_value" placeholder="Enter a number" required>
            <button type="submit">Predict</button>
        </form>
        {% if prediction %}
        <div class="result">
            {{ prediction }}
        </div>
        {% endif %}
    </div>
</body>
</html>

This interface includes:

  • A form for user input.
  • A section to display predictions.

4. Testing Locally

Run the Flask app:


python app.py

Check http://127.0.0.1:5000/ in your browser. Enter a number, click Predict, and see the result.

5. Deploying the App

Step 1: Prepare the Project

  1. Create a requirements.txt file to specify dependencies:

  Flask
  scikit-learn

  1. Generate the file automatically:

  pip freeze > requirements.txt

Step 2: Push to GitHub

  1. Initialize a Git repository:

    
       git init
       git add .
       git commit -m "Initial commit"
    

  2. Push to GitHub: 


      ```

      git branch -M main
      git remote add origin https://github.com/<your-username>/<repository-name>.git
      git push -u origin main 

Step 3: Deploy on Render

Render is a cloud platform that allows you to deploy web apps with minimal configuration.

  1. Sign Up on Render

    • Create an account on Render.
    • Click on New + > Web Service.
  2. Link Your GitHub Repository

    • Connect your GitHub account.
    • Select your Flask app repository.
  3. Configure Deployment

    • Set the Build Command to:

      
         pip install -r requirements.txt
      
     - Set the **Start Command** to:
           ```

           python app.py

Render will automatically detect your app, build it, and deploy it. Once done, you’ll get a public URL where your app is live!

Conclusion

With Flask, GitHub, and Render, deploy your own machine learning algorithm as a live web app . This tutorial provides a foundation for showcasing your models to the world. Start experimenting and extend the app with more advanced models and features!


Comments(0)