Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Machine Learning Apps

Building a Machine Learning App

Build a machine learning app in Streamlit: load data, train a scikit-learn model, collect inputs with sliders, show predictions and probabilities, with clean code structure.

Streamlit became popular because it turns a notebook-style model into something a non-programmer can use. A product manager moves sliders, the model predicts, and a chart explains why. This lesson builds that kind of app from the ground up with scikit-learn. You will see how to separate the model code from the UI code, how to turn widget values into the exact input the model expects, and how to present a prediction honestly, with probabilities rather than a bare label.

If scikit-learn is new to you, the scikit-learn tutorial covers estimators, training and evaluation first. Here we focus on the app side.

Streamlit does not run on this site, so the app code is read-only. The model code is plain Python with scikit-learn, and the TryIts run it for real in your browser. Where a widget would supply a value, the TryIt uses an ordinary variable.

The shape of a model app

A model app does five jobs. Keeping them in separate functions makes the app readable, testable and cacheable.

flowchart LR
    A["Load data"] --> B["Train model<br/>(cached)"]
    B --> C["Collect inputs<br/>(widgets)"]
    C --> D["Predict"]
    D --> E["Explain<br/>(probabilities, charts)"]

Only the third step depends on the user, so the first two should run once.

Remember that the script reruns on every slider move (how reruns work). If training sits at the top of the file without caching, every interaction retrains the model. The usual structure is therefore:

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

@st.cache_data
def load_data():
    iris = load_iris(as_frame=True)
    return iris.data, iris.target, list(iris.target_names)

@st.cache_resource
def train_model():
    X, y, _ = load_data()
    model = RandomForestClassifier(n_estimators=100, random_state=0)
    return model.fit(X, y)

X, y, class_names = load_data()
model = train_model()

Data goes in cache_data (a copy of values) and the fitted model in cache_resource (one shared object), as explained in Caching.

Train and predict: the core, runnable

Before adding widgets, get the machine-learning part right. The next TryIt trains a classifier on the iris flower measurements and predicts for one flower. This is exactly the code that would sit inside the cached functions.

Python Train a model and predict one flower

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note how the input is a one-row DataFrame with the same column names and order as the training data. Passing a raw list in the wrong order is the most common reason a deployed model gives nonsense.

Widgets that match the features

Create one input per feature, with sensible ranges taken from the data so users cannot enter impossible values. Deriving the range from the data keeps the UI in sync when the dataset changes:

Python
st.title("Iris species predictor")

with st.sidebar:
    st.header("Flower measurements")
    values = {}
    for column in X.columns:
        values[column] = st.slider(
            column,
            min_value=float(X[column].min()),
            max_value=float(X[column].max()),
            value=float(X[column].median()),
            step=0.1,
        )

row = pd.DataFrame([values], columns=X.columns)

The sidebar keeps inputs separate from results (see layout lessons in this course). Using the median as the default gives a typical flower on first load, so the page is never empty.

Now show the prediction with its uncertainty:

Python
probabilities = model.predict_proba(row)[0]
best = int(probabilities.argmax())

st.metric("Predicted species", class_names[best], f"{probabilities[best]:.0%} confidence")
st.bar_chart(pd.DataFrame({"probability": probabilities}, index=class_names))

st.metric puts the headline answer in a large card, while the bar chart shows the whole distribution. A model that says "setosa, 98%" deserves more trust than one saying "versicolor, 41%", and the chart makes that visible.

Handling edge cases

A model app meets inputs the model never saw. Build guards in from the start:

  • Out-of-range inputs. Limit sliders to the training range, or warn when a value is far outside it.
  • Missing values. If the user can leave a field blank, decide whether to impute, to ask, or to stop with st.stop().
  • Class imbalance and low confidence. When the top probability is below a threshold, say "not sure" instead of showing a confident label.
  • Feature order. Always build the frame with columns=X.columns.

This TryIt shows a small prediction helper that covers these guards and returns a result dictionary, a good shape for a function you can test without any UI.

Python A guarded predict function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The helper returns a label, a confidence and any warnings. In the app you show warnings with st.warning and use the label in st.metric.

A complete app, read-only

Putting it together, this is a full short app. Read it as a template:

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

st.set_page_config(page_title="Iris predictor", page_icon="๐ŸŒธ")

@st.cache_data
def load_data():
    iris = load_iris(as_frame=True)
    return iris.data, iris.target, list(iris.target_names)

@st.cache_resource
def train(_X, _y):
    return RandomForestClassifier(n_estimators=100, random_state=0).fit(_X, _y)

X, y, names = load_data()
model = train(X, y)

st.title("Iris species predictor")
st.caption("A random forest trained on 150 flowers. Move the sliders.")

values = {c: st.sidebar.slider(c, float(X[c].min()), float(X[c].max()),
                               float(X[c].median()), 0.1) for c in X.columns}
row = pd.DataFrame([values], columns=X.columns)

probs = model.predict_proba(row)[0]
best = int(probs.argmax())
left, right = st.columns(2)
left.metric("Predicted species", names[best], f"{probs[best]:.0%} confidence")
right.bar_chart(pd.DataFrame({"probability": probs}, index=names))

The leading underscores in train(_X, _y) tell the cache not to hash the large arguments, because train always uses the same data. If the data could change, drop the underscore so the cache key reflects it.

Be honest about what the model is

An interactive model feels authoritative, so add context: what data it was trained on, how it was evaluated, and what it should not be used for. A short st.caption or an expander named "About this model" is enough. We build a proper evaluation page in Model Evaluation Dashboards.

Common mistakes

  • Training inside the main flow without caching.
  • Building the input with the wrong column order or names.
  • Showing a label without probabilities or any warning for strange inputs.
  • Forgetting random_state, so results change between restarts.
  • Using cache_data for a fitted model (use cache_resource).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the trained model be created in a Streamlit app?

    cache_resource keeps one shared fitted model, so the script does not retrain on every interaction.
  2. 2. Why build the input as pd.DataFrame([values], columns=X.columns)?

    A different column order silently produces wrong predictions. Matching the training columns avoids that.
  3. 3. Why show predict_proba results instead of only the label?

    A 98 percent and a 41 percent prediction look the same as a bare label but deserve different trust.
  4. 4. What do you gain by setting slider ranges from the training data?

    Limiting inputs to the training range avoids extrapolation, where model output becomes unreliable.

Summary

  • Structure a model app as load data, train (cached), collect inputs, predict, explain.
  • Cache data with cache_data and the fitted model with cache_resource.
  • Build the input row with the training columns and order.
  • Derive slider ranges from the data and show probabilities, not just labels.
  • Guard against out-of-range and low-confidence cases, and explain what the model is.

Next: Saving, Loading and Sharing Models