To create a machine learning app, define a prediction task, train and evaluate a model, and connect it to a user interface. This tutorial uses Python, scikit-learn and Streamlit to build a flower classifier with a local prediction interface. It also explains how to test the system and prepare it for deployment.
If you want to practice several small models before building an interface, start with our Python AI code examples.
Plan your machine learning application
A machine learning app combines a trained model with an interface that accepts new inputs and returns predictions. For this tutorial, you will create a small flower classifier using the Iris dataset included with scikit-learn. Users enter four measurements and the app predicts one of three species. No external model API or GPU is required.
Start with a clearly defined prediction task. Identify the input features, the target, how predictions will be used, and what counts as a useful result. For real projects, assess whether you have AI-ready data before selecting a model. A prediction interface cannot repair inaccurate or unrepresentative training data.
Set up Python and install the dependencies
If you need a portable development environment, our AI development laptop guide covers memory and hardware requirements for local and cloud projects.
If you plan to move beyond this small CPU-based example, our machine learning computer guide compares hardware configurations for larger workloads.
Create a project folder and a virtual environment. Use a Python version supported by the installed libraries. On macOS or Linux, run:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install streamlit scikit-learn pandas
On Windows PowerShell, activate the environment using .venv\Scripts\Activate.ps1. The example requires two files: model.py and app.py. After testing, record the versions you used in a dependency file so deployment can reproduce the environment.
Train and evaluate your model
Save the following as model.py. The dataset includes features named for sepal and petal length and width. We use logistic regression as a straightforward classification baseline. A pipeline fits scaling parameters only on the training set and applies the same transformation during prediction, avoiding leakage from the held-out test set.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
def train_model():
data = load_iris(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2,
stratify=data.target, random_state=42
)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000)
)
model.fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
return model, data, accuracy
if __name__ == "__main__":
model, data, accuracy = train_model()
print(f"Test accuracy: {accuracy:.1%}")
Run python model.py. Guilds AI tested this training and prediction logic with scikit-learn 1.8.0: 28 of 30 held-out flowers were classified correctly (93.3%). This is a small demonstration dataset and a single split, not evidence of reliable performance on other populations. For a real application, evaluate performance across representative conditions, compare against a baseline and examine errors by class. Scikit-learn’s common pitfalls documentation explains why preprocessing belongs inside the training pipeline.
Create the prediction interface with Streamlit
Save this code as app.py. Streamlit provides Python widgets and runs the script again when users interact with it. Its resource cache allows this example to reuse the trained model rather than training it on each widget update.
import pandas as pd
import streamlit as st
from model import train_model
@st.cache_resource
def get_model():
return train_model()
model, data, accuracy = get_model()
st.title("Iris flower classifier")
st.caption("Educational example using the Iris dataset")
st.write(f"Held-out test accuracy: {accuracy:.1%}")
values = {}
for name in data.feature_names:
column = data.data[name]
values[name] = st.number_input(
name,
min_value=float(column.min()),
max_value=float(column.max()),
value=float(column.median()),
step=0.1
)
if st.button("Predict species"):
row = pd.DataFrame([values], columns=data.feature_names)
prediction = int(model.predict(row)[0])
st.success(str(data.target_names[prediction]))
scores = model.predict_proba(row)[0]
st.dataframe(pd.DataFrame({
"Species": data.target_names[model.classes_],
"Model score": scores
}))
Start the app using python -m streamlit run app.py and open the local address shown in your terminal. Change the measurements and select Predict species. The table shows the model’s class scores; they are not guaranteed probabilities of correctness. This tutorial’s model code was tested locally, but the Streamlit interface was not executed in the test environment. Run it on your machine before deploying.
Test the app before sharing it
Try a known test-set example, values close to class boundaries, and inputs at the minimum and maximum supported values. Ensure the interface preserves feature order and names, reports the predicted species, and shows a score for each class. Input bounds in this prototype come from the demonstration dataset; they do not establish that every possible combination is realistic.
For a regression model, replace the classifier and classification metric with suitable regression methods. For real-world data, validate inputs on the server, handle missing and invalid values consistently, and test how the application responds when a dependency fails. Our AI evals guide explains how to create repeatable acceptance tests.
Deploy and maintain the application
A local app is sufficient for a prototype. To share it, use an appropriate Python hosting environment that supports Streamlit, supply your tested dependencies, and configure the app entry point. Verify access controls and check any hosting charges and resource limits before making it public.
For larger models, separate offline training from the serving application. Store the validated model and preprocessing pipeline together, record the model and dependency versions, and load artifacts only from trusted sources. Do not retrain on every request. If several applications need predictions, consider providing a separate API service instead of coupling the model to one interface. As the project grows, consider MLOps tools for recording experiments and versioning the data and model artifacts.
Monitor errors, latency, input changes, and prediction quality after launch. Keep a previous validated version available for rollback. Our AI deployment guide covers staged releases, hosting options and monitoring in more detail.
Frequently asked questions
Do you need deep learning to build a machine learning app? No. Logistic regression, decision trees and other classical algorithms often provide useful baselines.
Can I build a machine learning app for free? The example uses open-source Python libraries and a built-in dataset. Local execution does not require a paid API, although hosting, hardware and other services may incur costs.
Can Streamlit serve a production application? It can support deployed applications, but suitability depends on traffic, access controls, performance and operational requirements. Test those requirements rather than assuming a working prototype is production-ready.
Do I need to retrain the model for each prediction? No. Train and validate a model, then reuse its learned parameters for inference. Retrain separately when evidence indicates a change is needed.

