Implementation in Heroku | Deploy the ML application / DL Streamlit en Heroku

Share on facebook
Share on twitter
Share on linkedin
Share on telegram
Share on whatsapp


Developed a machine learning or deep learning application using Streamlit and you don't know how to implement it on Heroku? Do not worry, I cover his back. In this article, I will discuss how to implement your ML application / DL Streamlit en Heroku. Then let's get started!

Note: This article considers that the reader has already developed an optimized application and we will use a demo application in this article.

Table of Contents

  1. Create a demo application
  2. Required software
  3. Implementation in Heroku
  4. Final notes

Create a demo application

Let's build a demo app. We will use a simple and famous House price prediction Application. You can download the data sets from here. Below is the code.

import pandas as pd
import numpy as np
import streamlit as st
import time
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
def main():
    df = load_data()
    df = preprocess_data(df)
    st.title('House Price Prediction for Silicon Valley of India - Bangalore')
    st.markdown('Just Enter the following details and we will predict the price of your **Dream House**')
    st.sidebar.title('Developer's Contact')
                        '( Dhamecha-brightgreen)]'
    st.warning('Only Enter Numeric Values in the Following Fields')
    bhk = st.text_input("Total BHK")
    area = st.text_input("Area in Square Feet")
    baths = st.text_input("Total Bathrooms")
    balcony = st.selectbox("Total Balcony", ['0', '1', '2', '3'])
    submit = st.button('Predict Price')
    if submit: 
        if bhk and area and baths and balcony:
            with st.spinner('Predicting...'):
                bhk, area, baths, balcony = int(bhk), int(area), int(baths), int(balcony)
                x_test = np.array([[bhk, area, baths, balcony]])
                prediction = predict(df, x_test)
      "Your **Dream House** Price is {prediction} lacs")
            st.error('Please Enter All the Details')
def train_model(df):
    global scaler
    X, y = df.iloc[:, :-1].values, df.iloc[:, -1].values
    scaler = StandardScaler().fit(X)
    X = scaler.transform(X)
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=23)
    model = LinearRegression().fit(X_train, y_train)
    return model, scaler
def predict(df, x_test):
    model, scaler = train_model(df)
    X_test = scaler.transform(x_test)
    y_pred = model.predict(X_test)
    return round(y_pred[0], 2)
def load_data():
    return pd.read_csv('Datasets/house-price-prediction.csv')
def preprocess_data(df):
    df = df.loc[:, ['size', 'total_sqft', 'bath', 'balcony', 'price']]
    df = df[df['size'].str.contains('BHK', na = False)]
    df['size'] = df['size'].str.replace(r'D', '').astype(int)
    df['total_sqft'] = df['total_sqft'].str.extract(r'(d+)', expand=False)
    df['bath'] = df['bath'].astype(int)
    df['balcony'] = df['balcony'].astype(int)
    df['total_sqft'] = df['total_sqft'].astype(int)
    return df
if __name__ == '__main__':

You can run your streamlit application locally using the following command.

streamlit run

Note: is the file we want to run.

Our application looks like the following.

Before entering the details:


After entering the details:


Required software

To implement our optimized application, we need the following software:

  1. Git Download from here
  2. Heroku CLI Download from here
  3. Free Heroku account create here

and follow the instructions on the screen.

Implementation in Heroku

Now that we have our demo application and the necessary software in our hands, let's implement our application on Heroku.

Required files

First, we need to add some files that allow Heroku to install all required libraries and run our application.


This file contains all the necessary libraries that will be installed for the project to work. This file can be created manually by reviewing the project and listing all the libraries that were used in the project. But we will be using the pipreqs module to do that, which automatically creates a requirements.txt file. Install it with the following command if you haven't already.

pip install pipreqs

Now, navigate to your project directory and type the following command.

pipreqs ./

Our requirements.txt file is ready!! It should look something like the following.


Procfile and

Using these two files, we tell Heroku the necessary commands to start our application.

In the file we will create a streamlit folder with credentials.toml and a config.toml file. Below is the command that will be pasted in the file.

mkdir -p ~/.streamlit/
echo "
email = "[email protected]"n
" > ~/.streamlit/credentials.toml
echo "
headless = truen
port = $PORTn
" > ~/.streamlit/config.toml

The Procfile is used to first run and then call illuminated race to run the application. Your Procfile should look something like the following.

web: sh && streamlit run

Note: is the file we want to run first (contains the main function). If you have defined your main function in some other file, pass it instead of

Create a Git repository

Heroku provides different ways of implementation, but we will use git since it is simple.

Type the following command to initialize an empty git repository. Make sure you are in the root directory of your project.

git init

Sign in to Heroku

Then, we must log in to Heroku. We can do that with the following command.

heroku login

You will be prompted to press a button and, once i've done it, you will be redirected to a login screen in your default browser.


After entering your credentials, you should see something like the following.


Deploy the application

Finally, we can implement our application in Heroku. Let's first create an instance of our application. We can do that with the following command.

heroku create houses-prices-predictor

home price predictor is a name that I chose for my application. You cannot use the same name that I have already taken. So choose your app name accordingly.

Finally, send the code to that instance with the following commands.

git add . 
git commit -m "some message" 
git push heroku master

When running git push Heroku master, You should notice that it should automatically detect that you have a Python application and it should install all packages within requirements.txt. After the command is finished, you should see something like the following.


Note: How i chose the name home price predictor, I have this url. You would get a url according to your app name.

Click on the URL to see your live deployed application.

Congratulations! Have I successfully deployed our first application.

Bonus Tips

If you want to change / edit files after deployment, you can do it in your files and run the following commands for those changes to be reflected in your live deployed application.

git add . 
git commit -m "some message" 
git push heroku master

You would get again the same url as shown in the image above, click that and voila!

Final notes

This completes today's discussion.

Thanks for reading this!

Hope you enjoyed the article and successfully implemented your first Streamlit app on Heroku!!

Click here to see our first live illuminated app. Feel free to put your first live app link in the comment section below.

Did I miss something important or did I want to share your thoughts? Comment below and I will answer you.

About the Author

I am Harsh Dhamecha, an aspiring data scientist. I am a last year student of the Computer Science degree with a specialization in Artificial Intelligence. A motivated student who is eager to help the data science community as much as he can.

If you have any query, can directly Email me or connect with me on LinkedIn O Twitter.

If you like the way I write, you can also search the other articles i have written.

Keep reading! A special thanks to you 🙌

The media shown in this article explaining how to implement the Streamlit app on Heroku is not the property of DataPeaker and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.