How to Build Interactive Machine‑Learning Web Apps with Streamlit: A Complete Guide

This tutorial explains how to install Streamlit, use its text, data, chart, and input components, manage layout, control flow, and caching, and demonstrates a full garbage‑classification web app that integrates a third‑party image‑recognition API, providing complete Python code examples.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Build Interactive Machine‑Learning Web Apps with Streamlit: A Complete Guide

Introduction

Streamlit is a pure‑Python library that enables rapid creation of interactive web applications for machine‑learning and data‑analysis, offering a rich set of UI components without requiring front‑end expertise.

Installation

Install Streamlit with pip install streamlit and verify the installation by running streamlit hello, which launches a demo app.

Text Components

Streamlit can display various text formats:

import streamlit as st
# markdown
st.markdown('Streamlit is **_really_ cool**.')
# title
st.title('This is a title')
# header
st.header('This is a header')
# subheader
st.subheader('This is a subheader')
# code with syntax highlighting
code = '''def hello():
  print("Hello, Streamlit!")''' 
st.code(code, language='python')
# plain text
st.text('This is some text.')
# LaTeX formula
st.latex(r'''a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
  \sum_{k=0}^{n-1} ar^k =
  a \left(\frac{1-r^{n}}{1-r}\right)''')

Data Components

Data can be shown with st.dataframe (interactive) or st.table (static). Example:

import streamlit as st, pandas as pd, numpy as np
df = pd.DataFrame(np.random.randn(50, 5), columns=[f'col {i}' for i in range(5)])
st.dataframe(df)   # interactive
st.table(df)       # static

Metrics are displayed with st.metric to show a value and its change, and JSON objects can be rendered with st.json for a collapsible view.

st.metric(label="Temperature", value="70 °F", delta="1.2 °F")
st.json({"foo": "bar", "stuff": ["stuff 1", "stuff 2"]})

Chart Components

Native charts include st.line_chart, st.area_chart, st.bar_chart, and st.map. They accept a DataFrame as data source.

import streamlit as st, pandas as pd, numpy as np
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a','b','c'])
st.line_chart(chart_data)

Streamlit also integrates third‑party visualisation libraries such as Matplotlib, Altair, Plotly, Bokeh, PyDeck, and Graphviz. Example with Matplotlib:

import streamlit as st, matplotlib.pyplot as plt, numpy as np
arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)

Input Components

Common input widgets include st.button, st.download_button, st.file_uploader, st.checkbox, st.radio, st.selectbox, st.multiselect, st.slider, st.select_slider, st.text_input, st.text_area, st.number_input, st.date_input, st.time_input, and st.color_picker. All share parameters such as label, key, help, on_change, args, and kwargs.

option = st.selectbox('Dropdown', ('Option 1', 'Option 2', 'Option 3'))
st.write('Selected:', option)

Layout

Streamlit offers five layout containers: st.sidebar (vertical side panel), st.columns (horizontal column layout), st.expander (collapsible section), st.container (multiple components), and st.empty (single placeholder).

Control Flow

Control the execution of an app with st.stop (halt further execution), st.form (group inputs and submit together), and st.form_submit_button (trigger form submission).

Caching

Long‑running data processing can be cached using the @st.cache decorator, which stores the result of a function in memory and reuses it on subsequent runs.

import streamlit as st, pandas as pd, numpy as np
DATA_URL = 'https://s3-us-west-2.amazonaws.com/streamlit-demo-data/uber-raw-data-sep14.csv.gz'
@st.cache
def load_data(nrows):
    data = pd.read_csv(DATA_URL, nrows=nrows)
    data.rename(lambda x: str(x).lower(), axis='columns', inplace=True)
    data['date/time'] = pd.to_datetime(data['date/time'])
    return data

Garbage‑Classification App Example

The tutorial builds a Streamlit app that classifies waste images using the TianAPI image‑classification service. The UI lets the user choose an image source (local upload or URL), select a classification mode (strict or fuzzy), and displays the image, the API response, and a confidence bar chart.

import base64, requests, streamlit as st, pandas as pd, numpy as np
# Sidebar selectors
source = st.sidebar.selectbox('Image source', ('Upload', 'URL'))
uploaded_file = None
img_url = None
if source == 'Upload':
    uploaded_file = st.sidebar.file_uploader('Upload image')
else:
    img_url = st.sidebar.text_input('Image URL')
mode_dict = {'Strict': 0, 'Fuzzy': 1}
mode_name = st.sidebar.radio('Classification mode', list(mode_dict))
mode = mode_dict[mode_name]
# Show selected image
if uploaded_file:
    st.image(uploaded_file, caption='Local image')
    img_base64 = base64.b64encode(uploaded_file.getvalue()).decode()
elif img_url:
    st.image(img_url, caption='URL image')
    img_base64 = None
# Request API
def get_img_cls_res(img_base64, img_url, mode):
    url = 'https://api.tianapi.com/txapi/imglajifenlei/index'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    body = {'key': 'YOUR_APPKEY', 'mode': mode}
    if img_base64:
        body['img'] = img_base64
    if img_url:
        body['imgurl'] = img_url
    return requests.post(url, headers=headers, data=body)
if img_base64 or img_url:
    resp = get_img_cls_res(img_base64, img_url, mode)
    if resp.status_code == 200:
        df = pd.DataFrame(resp.json()['newslist'])
        type_map = {0:'Recyclable',1:'Hazardous',2:'Kitchen',3:'Other',4:'Unrecognizable'}
        df['Category'] = df['lajitype'].apply(lambda x: type_map[x])
        df['Confidence'] = df['trust']
        df.set_index('Category', inplace=True)
        st.bar_chart(df[['Confidence']])
    else:
        st.write(resp)

Running the full code (reply "Garbage Classification v2" in the original source) launches the complete app.

Streamlit demo for autonomous driving model
Streamlit demo for autonomous driving model
Dataframe vs table
Dataframe vs table
Metric component
Metric component
Matplotlib chart in Streamlit
Matplotlib chart in Streamlit
Selectbox example
Selectbox example
Image upload component
Image upload component
Bar chart of classification confidence
Bar chart of classification confidence
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

machine learningData visualizationweb appStreamlitinteractive UI
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.