Tuesday, September 24, 2024

Getting Started with Streamlit for Machine Learning and Data Science

Streamlit is an open-source app framework designed specifically for machine learning and data science projects. It allows you to create stunning web applications using simple Python scripts, making it easier to showcase your work and share valuable insights. In this blog post, we’ll walk through the steps to set up a basic Streamlit application, including examples to help you get started.

Why Use Streamlit?
Streamlit offers several compelling advantages:

  1. Ease of Use: Its straightforward syntax enables users to quickly convert scripts into interactive apps. The minimal learning curve makes it accessible for anyone with basic Python knowledge.
  2. Real-Time Interactivity: You can build applications that respond to user inputs in real time, facilitating dynamic data exploration and model interactions.
  3. Seamless Integration: Streamlit works smoothly with popular Python libraries such as Pandas, NumPy, Matplotlib, and Plotly, allowing for comprehensive data manipulation and visualization.
  4. No Front-End Development Needed: Focus solely on your data and models without the hassle of learning HTML, CSS, or JavaScript, simplifying the development process.
  5. Customization Options: Streamlit allows for the addition of custom components, giving developers the flexibility to enhance their applications as needed.


Where Can It Be Used?
Streamlit can be applied in various scenarios:

  1. Machine Learning Applications: Deploy models as web applications, allowing users to input data and receive predictions or insights.
  2. Dashboards: Create real-time dashboards to monitor key performance indicators (KPIs) and metrics, aiding businesses in making data-driven decisions.
  3. Prototyping and Experimentation: Rapidly prototype ideas and experiment with different models or algorithms without the overhead of traditional web development.
  4. Cloud Deployment: Streamlit applications can be deployed on cloud platforms like AWS, Google Cloud, and Heroku, making it easy to share your applications with a broader audience.

Prerequisites
Before diving in, ensure you have Python installed on your machine. You’ll also need to install Streamlit. Open your terminal and run:

pip install streamlit


Creating Your First Streamlit App

1. Set Up Your Project
Create a new file named `app.py` in your preferred directory.

2. Write Basic Streamlit Code
In `app.py`, add the following code to set up a simple Streamlit app:

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

# Title of the application
st.title("Hello Streamlit")

# Display a simple text
st.write("This is a simple text")

# Create a simple DataFrame
df = pd.DataFrame({
    'First Column': [1, 2, 3, 4],
    'Second Column': [10, 20, 30, 40]
})

# Display the DataFrame
st.write("Here is the dataframe")
st.write(df)

# Create a line chart
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])
st.line_chart(chart_data)

3. Run Your Application
Open your terminal, navigate to the directory where `app.py` is located, and run the following command:

streamlit run app.py


This will start the Streamlit server, and you’ll see a message indicating that you can view your app in your browser at `http://localhost:8501`.


 


Enhancing Your App with Widgets

To make your app interactive, you can add widgets. Create another file named `widgets.py` and include the following code:

import streamlit as st
import pandas as pd

st.title("Streamlit Text Input")

name = st.text_input("Enter your name:")
age = st.slider("Select your age:", 0, 100, 31)
st.write(f"Your age is {age}.")

options = ["Python", "Java", "Perl", "JavaScript"]
choice = st.selectbox("Choose your favorite language:", options)
st.write(f"You selected {choice}.")

if name:
    st.write(f"Hello, {name}")

data = {
    "Name": ["John", "Cena", "Roman", "Reigns"],
    "Age": [30, 32, 34, 36],
    "City": ["New York", "Los Angeles", "Tampa", "Chicago"]
}
df = pd.DataFrame(data)
df.to_csv("sampledata.csv")
st.write(df)

uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write(df)



Run this file using the command:

streamlit run widgets.py



 

Building a Machine Learning App

Let’s create a simple machine learning application using Streamlit. Make a new file called `classification.py` and add the following code:

import streamlit as st
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

@st.cache_data
def load_data():
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target
    return df, iris.target_names

df, target_names = load_data()

model = RandomForestClassifier()
model.fit(df.iloc[:, :-1], df['species'])

st.sidebar.title("Input Features")
sepal_length = st.sidebar.slider("Sepal Length", float(df['sepal length (cm)'].min()), float(df['sepal length (cm)'].max()))
sepal_width = st.sidebar.slider("Sepal Width", float(df['sepal width (cm)'].min()), float(df['sepal width (cm)'].max()))
petal_length = st.sidebar.slider("Petal Length", float(df['petal length (cm)'].min()), float(df['petal length (cm)'].max()))
petal_width = st.sidebar.slider("Petal Width", float(df['petal width (cm)'].min()), float(df['petal width (cm)'].max()))

input_data = [[sepal_length, sepal_width, petal_length, petal_width]]

# Prediction
prediction = model.predict(input_data)
predicted_species = target_names[prediction[0]]

st.write("Prediction")
st.write(f"The predicted species is: {predicted_species}")


Run this application with:

streamlit run classification.py


 

 

Conclusion

Streamlit is a powerful tool for creating interactive web applications tailored for data science and machine learning. With just a few lines of code, you can build applications that visualize data and enable user interactions with machine learning models. Explore the possibilities with Streamlit, and start building your own applications today!

Key Takeaways

- Streamlit simplifies the development of interactive web applications with minimal coding.
- It allows for real-time data interaction and seamless integration with popular Python libraries.
- Ideal for machine learning, data visualization, and rapid prototyping.
- Deployment options make it easy to share applications with a wider audience.
 


Share your Streamlit projects in the comments below!

 #Streamlit #DataScience #MachineLearning #Python #WebDevelopment #DataVisualization #AI #TechTutorial #OpenSource #DataScienceCommunity #InteractiveApps #MLApps #SoftwareDevelopment #Analytics #Coding #StreamlitApps

Getting Started with Streamlit for Machine Learning and Data Science

Streamlit is an open-source app framework designed specifically for machine learning and data science projects. It allows you to create stun...