Deploying a Machine Learning Model As a Web App Using Streamlit

Newton Kimathi
7 min readAug 17, 2023

--

Deploying ML App using streamlit

In today’s fast-paced and data-driven business landscape, accurate sales predictions play a pivotal role in shaping successful strategies and staying ahead of the competition. In this guide, we will embark on a step-by-step journey to create a Sales Forecasting App using Streamlit, a Python library known for its simplicity and effectiveness in developing interactive web applications.

This app will empower users to predict sales for specific products in chosen stores. We’ll use a hypothetical scenario involving “Corporation Favorita” to illustrate the process.The model used is pretrained.For detailed information about the analysis and modeling process, you can refer here.

Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  1. Python: Ensure you have Python installed on your machine. You can download it from the official Python website.
  2. Virtual Environment: To effectively handle project dependencies, prevent conflicts, and maintain a clean working environment, it is advisable to establish a virtual environment. You can create a virtual environment by executing the following commands:
* Windows
```python
python -m venv venv; # To create venv environment
venv\Scripts\activate # To activate the environment
python -m pip install -q --upgrade pip # To upgrade pip version

* Linux & MacOs
```python
python3 -m venv venv # To create venv environment
source venv/bin/activate # To activate the environment
python -m pip install -q --upgrade pip # To upgrade pip version

``````

3. Designated Requirements file with the libraries required. Create a requirement file with the essential libraries such as pandas, streamlit,scikit — learn, pickle and any other libraries specific to your model’s requirements. Run the code below to install the the requirements

python -m pip install -qr requirements.txt 

4. Pre-trained Machine Learning Components: Our app relies on pre-trained machine learning components. You’ll need an encoder, imputer, scaler, and a predictive model. For this case, we’ll use a RandomForestRegressor model.

Building the App: Step by Step

  1. Importing Packages: Start by importing the necessary packages. This includes Streamlit for building the app’s interface, pandas for data manipulation, scikit-learn for machine learning, and more.
# Importing Packages
import streamlit as st
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
import os
import pickle

2. Load Machine Learning Components: Define a function to load the pre-trained machine learning components. These components, including the encoder, imputer, scaler, and model, will enable the app to make accurate predictions.

def load_components_func(fp):
with open(fp, "rb") as f:
components = pickle.load(f)
return components

# Load the machine learning components

DIRPATH = os.path.dirname(os.path.realpath(__file__))
ml_core_fp = os.path.join(DIRPATH, "Sales_Pred_model.pkl")
ml_components_dict = load_components_func(fp=ml_core_fp)
encoder = ml_components_dict['encoder']
imputer = ml_components_dict['imputer']
scaler = ml_components_dict['scaler']
model = ml_components_dict['model']

3. Create User Interface: Design an interactive user interface using Streamlit’s user-friendly components. Include input fields for date, promotion status, number of transactions, oil price, product category, state, city, and weekly sales day.

st.set_page_config(layout="centered")
st.title("Sales Forecast App for Corporation Favorita")
st.write("""Welcome to Corporation Favorita Sales Prediction app!
This app allows you to predict the Sales for a specific
product in a chosen store at Corporation Favorita.
""")

4. Setting Up Interface: We will set up a user interface for inputting various parameters that are needed for sales prediction. Users can input the date, whether the product is on promotion, the number of transactions, oil price, product category, state, city, and weekly sales day. When the user clicks the “Predict” button, the input data is collected and stored in a DataFrame named data. This DataFrame will then be used for further data preprocessing and prediction steps.

with st.form(key="information", clear_on_submit=True):
# User Input Fields
date = st.date_input("Date")
Promotion = st.selectbox("On promotion, 0 for No and 1 for Yes", [0, 1])
transactions = st.number_input("Enter the number of transactions for the product")
dcoilwtico = st.number_input("Enter the oil price (dcoilwtico)")

products = st.selectbox('products', ['AUTOMOTIVE', 'BABY CARE', 'BEAUTY', 'BEVERAGES', 'BOOKS',
'BREAD/BAKERY', 'CELEBRATION', 'CLEANING', 'DAIRY', 'DELI', 'EGGS',
'FROZEN FOODS', 'GROCERY I', 'GROCERY II', 'HARDWARE',
'HOME AND KITCHEN I', 'HOME AND KITCHEN II', 'HOME APPLIANCES',
'HOME CARE', 'LADIESWEAR', 'LAWN AND GARDEN', 'LINGERIE',
'LIQUOR,WINE,BEER', 'MAGAZINES', 'MEATS', 'PERSONAL CARE',
'PET SUPPLIES', 'PLAYERS AND ELECTRONICS', 'POULTRY',
'PREPARED FOODS', 'PRODUCE', 'SCHOOL AND OFFICE SUPPLIES',
'SEAFOOD'])
state = st.selectbox('state', ['Santa Elena', 'El Oro', 'Guayas'])
city = st.selectbox('city',['Salinas', 'Machala', 'Libertad'])
weeklysales = st.number_input("weekly Sales, 0=Sun and 6=Sat", step=1)

# Prediction
if st.form_submit_button("Predict"):
# Creating a DataFrame with user input
data = pd.DataFrame({
"onpromotion": [Promotion],
"transactions": [transactions],
"dcoilwtico": [dcoilwtico],
"date": [date],
"family": [products],
"state": [state],
"weekly_sales": [weeklysales],
"city": [city],
})

The interface will look like this:

Data Preprocessing: We will handle data preprocessing tasks such as converting dates, feature engineering, encoding categorical variables, and imputing missing values.


# Data Preprocessing

# Converting date into datetime type
data['date'] = pd.to_datetime(data['date'])


# Feature Engineering
#New features for the year, month and days
data['year'] = data['date'].dt.year
data['month'] = data['date'].dt.month
data['day_of_month'] = data['date'].dt.day
data['day_of_year'] = data['date'].dt.dayofyear
data['Week'] = data['date'].dt.isocalendar().week
data['day_of_week'] = data['date'].dt.dayofweek
window = 7
data['transactions_rolling_avg'] = data['transactions'].rolling(window=window).mean()

# Dropping the date column
data = data.drop("date",axis=1)

# Dividing numerical and categorical columns
num_columns = data.select_dtypes(include=['int64', 'float64', 'int32', 'UInt32', 'int8']).columns
cat_columns = data.select_dtypes(include=['object']).columns

# Encoding Categorical columns
encoded_data = encoder.transform(data[cat_columns])

# Concatenate the encoded dataframe with the original dataframe
df_encoded = pd.concat([data[num_columns], encoded_data], axis=1)
df_encoded = df_encoded.reindex(columns=ml_components_dict['columns'])

#Imputing the missing values
data_imputed = imputer.transform(df_encoded)
# Ensure columns are in the correct order
data_scaled = data_imputed.copy()

# Scale the numerical columns
columns_to_scale = ['dcoilwtico', 'transactions', 'year', 'month', 'day_of_month',
'day_of_year', 'Week', 'day_of_week', 'transactions_rolling_avg']
data_scaled[columns_to_scale] = scaler.transform(data_scaled[columns_to_scale

Prediction: We will then use the trained model to make predictions on the preprocessed data as below:

        # Make prediction using the model
predictions = model.predict(data_scaled)

Styling and Output: Apply custom styling to enhance the app’s visual appeal. Display the predicted sales using stylish messages or icons.

# Display the predictions
st.balloons()
st.success(f"Predicted Sales: {predictions[0]:,.2f}", icon="✅")

Documentation and Help Section: Create a sidebar with navigation options for users to access documentation and support.

# Add a sidebar to the app
st.sidebar.title("Documentation and Help")

# Create a navigation menu within the sidebar
menu = st.sidebar.radio("Navigation", ["Introduction", "Getting Started", "User Guide", "Troubleshooting", "Feedback and Support"])
# Introduction
if menu == "Introduction":
st.title("Introduction")
st.write("Welcome to the Documentation and Help section of the Sales Prediction App. This section provides detailed instructions on how to use and understand the app effectively.")
# Getting Started
elif menu == "Getting Started":
st.title("Getting Started")
st.write("Before you can use the app, make sure you have Python and the required dependencies installed. Follow these steps:")
st.code("""
git clone https://github.com/yourusername/sales-prediction-app.git
cd sales-prediction-app
pip install -r requirements.txt
streamlit run app.py
""", language="bash")

# User Guide
elif menu == "User Guide":
st.title("User Guide")
st.write("The app requires the following input parameters for making sales predictions:")
st.write("- **Date:** Select the date for which the sales took place.")
st.write("- **On Promotion:** Choose whether the product is on promotion (1 for Yes, 0 for No).")
st.write("- **Number of Transactions:** Enter the number of transactions for the product.")
st.write("- **Oil Price (dcoilwtico):** Input the oil price for the selected date.")
st.write("- **Product Category:** Choose the product category from the available options.")
st.write("- **State:** Select the state where the store is located.")
st.write("- **City:** Choose the city where the store is located.")
st.write("- **Weekly Sales Day:** Enter the day of the week for which the sales occured (0 for Sunday, 1 for Monday, ..., 6 for Saturday).")

# Troubleshooting
elif menu == "Troubleshooting":
st.title("Troubleshooting")
st.write("Encountering issues while using the app? Here are some common troubleshooting steps:")
st.write("- **Missing Data:** Ensure that you have provided values for all required input parameters.")
st.write("- **Dependency Issues:** Make sure you have installed the necessary packages using the instructions provided in the installation section.")
st.write("- **Scikit--learn:** The specified version of sckit--learn for this app is version 1.2.2")

# Feedback and Support
elif menu == "Feedback and Support":
st.title("Feedback and Support")
st.write("We value your feedback! If you have any questions, feedback, or issues, feel free to reach out to us via email: newtonkimathi20@gmail.com or by [creating an issue](https://github.com/Newton23-nk/Sales-Prediction-App/issues) on the GitHub repository.")
st.write("Connect With Me on LinkedIn:")
st.write("[LinkedIn](https://www.linkedin.com/in/KimathiNewton/)")
st.write("Thank you for using the Sales Prediction App! We hope it provides valuable insights for your business decisions.")

Run the App:

Once the dependencies are installed, you can run the app using Streamlit. In your terminal, navigate to the project directory and run the following command:

streamlit run app.py

Documentations and Help Section:

The documentation and help section will look like this:

Getting Started Section:

Appreciation

I highly recommend Azubi Africa for their comprehensive and effective programs. Read More articles about Azubi Africa here and take a few minutes to visit this link to learn more about Azubi Africa life-changing programs

--

--

Newton Kimathi

Data Scientist || Data Analyst || Python, R, SQL, PowerBI , Machine Learning ||