streamlit logo

In our data-driven age, presenting machine learning (ML) models in a fun and interactive way is super important for sharing insights and showcasing AI’s capabilities. Whether you’re a budding data scientist, a machine learning engineer, or a researcher, knowing how to deploy a model effectively is a must-have skill. One tool that’s taken off lately is Streamlit!

Streamlit makes it easy to deploy machine learning models and lets you quickly create interactive web applications. With just a few lines of code, you can transform your model into a user-friendly and visually appealing app that anyone can access. In this blog, weโ€™ll dive into how to build and deploy interactive machine-learning applications using Streamlit hence making your model engaging and accessible even for those without coding skills.

What is Streamlit?

Streamlit is an open-source Python framework that enables the creation of web applications with minimal complexity. It has gained significant popularity among data scientists and machine learning professionals due to its user-friendly nature, rapid performance, and adaptability.

Streamlit is specifically crafted to facilitate the transformation of data scripts into engaging interactive applications. No prior experience in front-end web development is required to design attractive, tailored applications. Additionally, it integrates effortlessly with well-known machine-learning libraries such as Scikit-learn, TensorFlow, and PyTorch.

Why choose Streamlit?

1. User-Friendly Interface– Streamlit offers a user-friendly API that facilitates the development of web applications in Python with minimal coding effort. We don’t need to engage extensively with HTML, CSS, or JavaScript. The design of Streamlit’s API allows developers to concentrate on the essential components of their applicationโ€”namely, the model, data, and insightsโ€”without the complexities associated with web development.

2. Interactive Functionality– A prominent characteristic of Streamlit is its capacity to enable dynamic, real-time interactions within applications. Developers can create elements such as sliders, buttons, and file uploaders, empowering users to modify input parameters and immediately observe the outcomes of the model’s predictions.

3. Effortless Compatibility – Streamlit seamlessly integrates with various Python libraries, positioning it as an excellent option for the deployment of machine learning models. Whether utilizing Pandas, NumPy, or other data manipulation or machine learning libraries, integration into your application is straightforward.

4. Quick Deployment – Once the application is developed, the deployment process is uncomplicated. You have the option to host your application locally or utilize cloud services such as Streamlit sharing, Heroku, or AWS. With a simple click, your application becomes available to anyone with internet access.

5. Community Cloud – Streamlit provides a free community cloud for users to deploy and test the working of their apps before publishing them.

Building an Interactive ML App with Streamlit for Diabetes Prediction

In this section, we will explore the steps involved in developing a diabetes prediction application utilizing Streamlit. This application will incorporate a pre-trained machine learning model and offer a user-friendly interface, allowing individuals to enter their health parameters and receive predictions. Along with this another tab is added where users can upload bulk data in a CSV file to see and download predictions!

The first step is to create your Diabetes Prediction model and save it in your system in .sav format. You can use the following code snippet to save your model-

# Save the trained model
with open('diabetes_model.sav', 'wb') as file:
    pickle.dump(model, file)

You can download the diabetes prediction model from here. Once that is done you can simply follow the below-mentioned step and create your very first Streamlit web application-

STEP 1: Install Necessary Libraries

It is essential to install all necessary libraries before engaging in the creative aspect of the project. Please ensure that this step is completed, as failure to install the required components will result in errors within your code. You can install these via pip:-

pip install streamlit scikit-learn numpy pickle-mixin

STEP 2: Import Libraries

After installing the, you have to import all these libraries at the very start of the code-

import streamlit as st
import pandas as pd
import numpy as np
import pickle

STEP 3: Set Up the Streamlit App

Start creating your Streamlit app by loading the saved model.

# Load the pre-trained model
model_filename = 'diabetes_model.sav' # change the path to your model's object path
with open(model_filename, 'rb') as file:
    model = pickle.load(file)

STEP 4: Design the User Interface

Create a simple and interactive interface for users to input their health data. In this step, you can be creative and use various elements and functions provided by Streamlit. This includes –

Input Elements:

  • st.text_input(): For text input.
  • st.number_input(): For numerical values.
  • st.slider(): For selecting ranges or values.
  • st.selectbox(): Dropdown menus for options.
  • st.checkbox(): Toggle options.
  • st.radio(): Radio button selection.
  • st.button(): Add buttons for actions.

Text Display:

  • st.write(): Displays text, data, and even Markdown.
  • st.markdown(): Add custom Markdown text with styling.
  • st.title(), st.header(), and st.subheader(): For structured titles and headers.

Layout and Organization

  • Sidebar:
    • st.sidebar.*: Add widgets or elements to the appโ€™s sidebar.
    • Example: st.sidebar.selectbox() creates a dropdown in the sidebar.
  • Columns:
    • st.columns(): Arrange elements in columns.
    • Example: Split the screen into two or more sections for better design.
  • Tabs:
    • st.tabs(): Organize content into tabs for better navigation.
  • Expander:
    • st.expander(): Collapsible sections to hide/show detailed content.

You can check out other features and elements provided by Streamlit here and play around with them a little!

Code

For reference look at the following code for a sample web page design –

# Title and Description
st.title("๐Ÿ” Diabetes Prediction App")
st.markdown("""
This app predicts whether a person is at risk of diabetes based on their input data. 
You can either fill in your details for a single prediction or upload a CSV file for bulk predictions.
""")

# Creating tabs for single and bulk predictions
tab1, tab2 = st.tabs(["Single Prediction", "Bulk Prediction"])

# Single Prediction Tab
with tab1:
    st.header("Enter Your Details:")

    # Organizing inputs into columns
    col1, col2 = st.columns(2)

    with col1:
        pregnancies = st.number_input("Number of Pregnancies", min_value=0, max_value=20, value=0, step=1)
        glucose = st.number_input("Glucose Level", min_value=0, max_value=300, value=120, step=1)
        blood_pressure = st.number_input("Blood Pressure (mm Hg)", min_value=0, max_value=200, value=80, step=1)
        skin_thickness = st.number_input("Skin Thickness (mm)", min_value=0, max_value=100, value=20, step=1)

    with col2:
        insulin = st.number_input("Insulin Level (ยตU/mL)", min_value=0, max_value=900, value=30, step=1)
        bmi = st.number_input("BMI (Body Mass Index)", min_value=0.0, max_value=70.0, value=25.0, step=0.1)
        diabetes_pedigree = st.number_input("Diabetes Pedigree Function", min_value=0.0, max_value=2.5, value=0.5, step=0.01)
        age = st.number_input("Age", min_value=0, max_value=120, value=30, step=1)

    # Predict Button for single input
    if st.button("๐Ÿ” Predict", key="single_predict"):
        # Prepare input data for prediction
        user_data = np.array([[pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age]])

        # Make prediction
        prediction = model.predict(user_data)[0]

        # Display the result
        st.write("---")
        if prediction == 1:
            st.error("๐Ÿšจ **High Risk**: You are likely to have diabetes. Please consult a healthcare professional.")
        else:
            st.success("๐ŸŽ‰ **Low Risk**: You are unlikely to have diabetes. Keep up the healthy lifestyle!")
        st.write("---")

# Bulk Prediction Tab
with tab2:
    st.header("Upload CSV for Bulk Predictions")
    uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"], key="bulk_upload")

    if uploaded_file is not None:
        # Read the CSV file
        data = pd.read_csv(uploaded_file)

        # Display the uploaded data
        st.write("Uploaded Data:")
        st.write(data)

        # Ensure the data has the correct columns
        required_columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 
                            'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']
        if all(col in data.columns for col in required_columns):
            # Make predictions
            predictions = model.predict(data[required_columns])

            # Append predictions to the data
            data['Prediction'] = predictions

            # Map predictions to human-readable labels
            data['Prediction'] = data['Prediction'].map({1: "High Risk", 0: "Low Risk"})

            # Display the results
            st.write("Predictions:")
            st.write(data)

            # Allow user to download the results
            csv = data.to_csv(index=False)
            st.download_button(label="Download Predictions as CSV", data=csv, file_name="predictions.csv", mime="text/csv")
        else:
            st.error(f"The uploaded file must contain the following columns: {', '.join(required_columns)}")

# Footer Section
st.markdown("""
---
**Disclaimer**: This app is for educational purposes only and should not be used as a substitute for professional medical advice.
""")

STEP 4: How to run

Once the code is ready:

  1. Save the file as app.py.
  2. Place your trained model file (diabetes_model.sav) in the same directory.
  3. Run the following code in the terminal to see the results!
streamlit run app.py
Streamlit UI screens
Streamlit UI screens
Streamlit UI screens
Streamlit UI screens

Conclusion

Deploying machine learning models using Streamlit provides a straightforward, effective, and engaging method to actualize intricate algorithms. By developing an intuitive web application for diabetes prediction, we not only enhance user accessibility to the model but also illustrate how technology can enable individuals to make well-informed health decisions. You can also read more about machine learning in healthcare.

Streamlit also helps us in intermittent demos, where the final UI is not yet finalised, but you want to quickly try some UI and make changes, quickly to get signed with the stakeholders. It also doesn’t need extra installation other than the Streamlit package, providing quicker and hassle-free installations.

This instance underscores the adaptability of Streamlit in crafting visually attractive and user-centric applications without requiring extensive frontend expertise. Because of its robust capabilities and user-friendly interface, Streamlit effectively connects data science with tangible real-world outcomes, transforming machine learning models from mere code into instruments for meaningful change and interactive applications.


Leave a Reply

Your email address will not be published. Required fields are marked *

Search

Contents

About

Welcome to AI ML Universeโ€”your go-to destination for all things artificial intelligence and machine learning! Our mission is to empower learners and enthusiasts by providing 100% free, high-quality content that demystifies the world of AI and ML.

Whether you are a curious beginner or an experienced professional looking to enhance your skills, we offer a wide range of resources, including tutorials, articles, and practical guides.

Join us on this exciting journey as we unlock the potential of AI and ML together!

Archive