In Chapter 22, we asked whether a model should be used for a proposed decision. Suppose we have a suitable use and enough evidence to try it. How can someone use our model without opening our notebook, installing our development tools, or training it again?
We will build a text classifier using methods from earlier chapters, turn it into a small web application, and deploy it on Render. Then we will step back from the demonstration: what changes when people rely on predictions, and how do the ideas from this course help us decide what to do?
Learning outcomes
By the end of this chapter, you should be able to:
Save and load a complete fitted pipeline for later prediction.
Explain how a web application connects user input to a model prediction.
Run a small prediction app locally and describe how to deploy it on Render.
Distinguish a functioning service from a model that remains suitable for use.
Justify an end-to-end ML workflow, communicate its limitations, and recommend a next action.
From a notebook to an application
For this demo, we will use HappyDB, a dataset of short descriptions of happy moments. Some descriptions have category labels such as achievement, bonding, or nature. Our task is to predict a description’s category from its text. For example, a description of finishing a difficult assignment might be labeled achievement. This is a multiclass text-classification problem: the input is a string, and the output is one of several categories.
In a notebook, we can call predict ourselves. A friend trying our classifier should be able to type a moment into a web page and see the result.
There are two pieces to this change. We save the fitted pipeline so that we can reuse it without training again. Then we build an application that accepts input, calls that pipeline, and displays its output. Deployment makes the application available in the environment where it will be used.
For our demo, the path is:
Browser: a user enters text → server: the app calls the saved pipeline → browser: the app displays a category.
The server needs the model and its software dependencies. A user needs only a browser. We will use Gradio to build the interface in Python and Render to host it. These are choices for this demonstration, rather than requirements for deploying ML.
Build and deploy the HappyDB app
We will first save a fitted pipeline, then connect it to a local interface, and finally run that same application on Render. Each step gives us something we can check before moving to the next.
Build and save the prediction pipeline
The HappyDB corpus is included in the course data directory. We will use cleaned_hm as the input text and ground_truth_category as the target, keeping only rows where both are available. The code below assumes the notebook is running from book/, where data/cleaned_hm.csv and the two application directories are located. The application files themselves locate the model relative to their own location.
We had a serious talk with some friends of ours who have been flaky lately. They understood and we had a good evening hanging out.
bonding
5
I meditated last night.
leisure
24
My grandmother start to walk from the bed after a long time.
affection
32
I picked my daughter up from the airport and we have a fun and good conversation on the way home.
bonding
42
when i received flowers from my best friend
bonding
Each row pairs a moment description with its recorded category. The text is our input; the category is the label we want to predict. We will now separate the inputs and labels and hold out a test set before fitting the pipeline.
X = moments["cleaned_hm"]y = moments["ground_truth_category"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, stratify=y, random_state=123)pipe_lr = make_pipeline( CountVectorizer(stop_words="english"), LogisticRegression(max_iter=2000, random_state=123),)pipe_lr.fit(X_train, y_train)baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)pd.Series({"baseline test accuracy": accuracy_score(y_test, baseline.predict(X_test)),"pipeline test accuracy": accuracy_score(y_test, pipe_lr.predict(X_test)),})
baseline test accuracy 0.340531
pipeline test accuracy 0.825487
dtype: float64
We keep the model configuration fixed here: our purpose is to demonstrate deployment, not to repeat model selection. In a project, preprocessing choices, model choices, and tuning would use the training data with validation or cross-validation before final test evaluation.
This split estimates performance on held-out moment descriptions drawn from this dataset. It does not establish performance on another language, a different population, or a different use of the categories. HappyDB also contains multiple moments from some writers. If our goal were performance on entirely new writers, we would split by writer rather than let a writer contribute to both sets. Deployment does not repair an evaluation that answers the wrong question.
Save the whole pipeline
The vectorizer has learned a vocabulary and the classifier has learned coefficients for that representation. Saving only the classifier would leave the application without the transformation it needs. Save the fitted pipeline, so new text follows the same steps as training text.
for directory in [Path("web_application"), Path("web_api")]: joblib.dump(pipe_lr, directory /"moment_predictor.joblib", compress=3)model = joblib.load("web_application/moment_predictor.joblib")text ="I had a lovely dinner with my friends."assert model.predict([text])[0] == pipe_lr.predict([text])[0]model.predict([text])[0]
'bonding'
The input is a list containing one string because predict expects a collection of examples. Loading this file restores the fitted objects; it does not refit them.
WarningModel files and their environment
Only load joblib files from a trusted source: loading can execute code. A saved scikit-learn object also depends on the software used to create it. Keep training and serving versions consistent and record the dependencies alongside the artifact. See scikit-learn’s model persistence guidance.
Should we retrain on all the data?
After fixing the approach and completing evaluation, a team may refit it on all available labeled data. This can make more data available for learning, but the resulting artifact is different from the one evaluated. The earlier test score is evidence about the development procedure under its evaluation conditions, not a fresh measurement of this refitted artifact. Further tuning in response to test results would require new held-out evidence.
Here we deploy the pipeline fitted on the training set, so it is the same artifact we evaluated. More data is not automatically useful if its labels, population, or collection process are inappropriate.
Build and run the app locally
Gradio creates an interface around a Python function. Our function accepts a string and returns a predicted category. The complete app lives in web_application/app.py:
from pathlib import Pathimport osimport gradio as grimport joblibmodel = joblib.load(Path(__file__).parent /"moment_predictor.joblib")def predict_moment(text):ifnotisinstance(text, str) ornot text.strip():return"Please describe a happy moment first."returnstr(model.predict([text])[0])demo = gr.Interface( fn=predict_moment, inputs=gr.Textbox(label="Describe a happy moment", lines=3, max_length=5000), outputs=gr.Textbox(label="Predicted category"), title="Happy Moment Classifier", description="A course demo: a predicted category is not an objective account of your experience. Please use fictional examples rather than private information.", examples=["I had a lovely dinner with my friends.", "I finished a difficult assignment."], flagging_mode="never",)if__name__=="__main__": demo.launch( server_name="0.0.0.0"if"PORT"in os.environ else"127.0.0.1", server_port=int(os.environ.get("PORT", "7860")), share=False, )
The model is loaded once when the application starts, rather than for every prediction. Gradio supplies the text box, button, and output display. The empty-input check gives users a useful response before we call the model.
The final lines start a web server. Locally it listens on 127.0.0.1, an address on our own computer. On Render, it listens on 0.0.0.0 and the port specified by the PORT environment variable, allowing Render to route requests to it. These settings make the app reachable; they do not improve the model.
Files and prerequisites
The main app needs only these files:
web_application/
├── app.py # interface and prediction function
├── moment_predictor.joblib # complete fitted pipeline
├── requirements.txt # tested package versions
└── .python-version # tested Python version
The old Flask templates and style sheet are retained in the directory as reference material; the Gradio app does not use them. No Flask forms or HTML editing are required for this walkthrough.
Use the course environment to run the training and saving cells above. Do not reuse an old model artifact with a new scikit-learn installation.
In a terminal, activate that environment and navigate to book/web_application from the repository root.
Open http://127.0.0.1:7860 in a browser. Try a fictional happy moment, then an empty input. You should receive a category for the former and a request for text for the latter. Press Ctrl+C in the terminal to stop the server.
NoteCheck before deploying
If the model file is missing, run the saving cell first. For import or version errors, check that the terminal is using the intended Python environment. If port 7860 is already occupied, stop the earlier app before restarting it. A local prediction should work before you investigate hosting problems.
Deploy the app on Render
Our local server stops being available when we stop the process or turn off the laptop. Render runs the process on a hosted server and provides a public URL. It installs our dependencies during a build, then runs our start command to serve requests. The model is already trained: the hosted app only loads it and predicts.
You need a GitHub repository containing the app files, a Render account, and permission to connect that repository. Use a small repository containing the four files above rather than uploading the textbook, training data, or personal information. Include the saved model file; check whether your Git ignore rules exclude it. A .joblib file should come from your own trusted training process.
Create the web service
Push the contents of book/web_application to the root of your deployment repository. Keep app.py, requirements.txt, .python-version, and moment_predictor.joblib together.
In Render, choose New → Web Service and connect the repository and branch you intend to deploy.
Select the Python runtime and use the settings below. With the app files at the repository root, leave Root Directory blank. If instead deploying from the full textbook repository, set Root Directory to book/web_application.
Setting
Value
Build command
pip install -r requirements.txt
Start command
python app.py
Python version
Match the app’s .python-version file
Compute plan
Choose a plan appropriate for a short teaching demo; check current limits and costs
Create the service and watch the build and startup logs. The build installs dependencies; the start command loads the saved pipeline and starts Gradio. The app reads Render’s PORT automatically.
When the service is ready, open the onrender.com URL shown in its dashboard. Submit the same fictional text used locally and check that the predicted category agrees. Check empty input too.
These steps follow Render’s web-service documentation. Its Python version guidance explains runtime selection. Dashboard labels and hosting plans may change, so consult those references if the interface differs.
Diagnose a failed deployment
Use the logs to locate the stage that failed. A package installation failure is a build problem; a missing model file or a version mismatch usually appears when the app starts. If Render cannot detect an open port, check that the app binds to 0.0.0.0 and reads PORT. If it runs but gives an unexpected category, compare the input, saved model, and dependencies with the local version before changing the hosting settings.
Render’s free-service documentation describes idle shutdown and other restrictions. A first request after inactivity can take longer while a service starts. Treat a free teaching deployment as a demonstration, rather than evidence that an application is ready for dependable use. Stop or remove the service when you no longer need it.
Changing a linked repository may trigger a new deployment, depending on the service’s configuration. Record which code and model artifact belong together so that a change can be checked and, when necessary, reversed.
Beyond the demo: deployment in practice
Our demo accepts text and returns a category. A real application also has to specify when predictions are useful, what happens when they fail, and who is responsible for the system. Those requirements often shape the deployment more than the choice of hosting provider.
Predictions do not always need a web app
In an online service, an application requests a prediction when it needs one, as our interface does. A retailer might instead generate demand forecasts in a scheduled batch each night and store them for the next morning. A phone could run a model on the device, avoiding a network request. These choices depend on how quickly a result is needed, connectivity, available computation, and which data should leave the device. An API is useful when another program, rather than a person at a form, needs predictions.
Deploy the transformation and its assumptions
The artifact includes our vocabulary and classifier, but using it also requires compatible dependencies and an agreed input format. Another team needs to know whether an input is one string or a table, which fields are required, and what the output means. A model version should identify the training procedure, evaluation, code, and dependencies associated with it. This makes a prediction traceable and allows a team to restore a previous version when a change causes problems.
Plan for failures and responsibility
Requests can contain missing fields, unexpected values, or more data than the service can handle. Input checks should reject malformed requests with useful errors. A system also needs a response when the model is unavailable: perhaps queue the request, use an agreed fallback, or route it to a person. The appropriate response depends on the consequences of delay and error. Access controls, careful handling of logs, and clear retention practices matter when inputs contain personal information. Someone needs authority and time to investigate failures and change the service.
Monitor the service and the predictions
A service can respond quickly to every request while making poor predictions. Monitoring errors and response time tells us about software operation; evaluating usefulness requires evidence about predictions and their consequences. Outcomes may arrive much later, or only for selected cases. Changes in input data can prompt investigation, but an input change alone does not measure a change in accuracy.
Compare performance with appropriate baselines, inspect important groups and failure cases, and revisit whether the intended use remains justified. New evidence might support retraining, but it can also point to an inappropriate target, a data-collection problem, or a need to withdraw the system. Retraining automatically on whatever data arrive can preserve or amplify these problems. Deployment continues the workflow and the responsibilities from Chapter 22.
Exercise 23.1: Is the deployed model working?
The HappyDB service still returns a category for every nonempty message. Users now submit many messages in languages absent from its training data.
What evidence suggests the software is functioning? What remains unknown about the model?
What evidence would you collect to assess usefulness for these users? Explain why a change in input language alone does not quantify prediction error.
What could the app do while that evidence is unavailable?
Discussion: read after trying
Successful responses show that requests reach the model and return outputs. They do not establish that the categories are appropriate. We would need representative examples, suitable labels or another justified assessment process, and evaluation by language and intended use. Input monitoring identifies a change, not its performance consequences. The app might state its evaluated language scope, ask users to use a supported language, or decline unsupported inputs where they can be identified reliably. Translation is another modeling choice that would need evaluation, rather than an automatic fix.
Optional extension: predictions for another program
A web interface serves a person. A web API provides an agreed way for another program to send input and receive output. For this example, a client sends an HTTP POST request containing JSON such as {"text": "I met a friend."}. The server returns JSON containing the category. The client does not need to be written in Python.
The accompanying web_api/app.py keeps a small Flask example. It loads the same saved pipeline, checks the input, and exposes /predict. It is separate from the Gradio walkthrough so we can examine the request explicitly.
From the repository root, activate the course environment and run:
cd book/web_apipython-m pip install -r requirements.txtpython app.py
In a second terminal, send a request:
curl-X POST http://127.0.0.1:5000/predict \-H'Content-Type: application/json'\-d'{"text":"I had a lovely dinner with my friends."}'
-H identifies the body as JSON, -d supplies the input, and -X POST states the request method. The response has a prediction field. Sending an empty object should instead produce a useful error and HTTP status 400, indicating an invalid request. Stop the local server with Ctrl+C when finished.
To host this optional API on Render, use the API directory as the service root, the same build command, and gunicorn app:app --bind 0.0.0.0:$PORT as the start command. Gunicorn runs the Flask application as a hosted service; python app.py uses Flask’s local development server. Successful hosting would still leave the monitoring, access, and operating responsibilities discussed above.
Your first ML project: what would you recommend?
We began this course by asking what machine learning could do. You can now make more specific decisions: what to predict, what evidence would support using a model, and when to choose a different approach.
The following activity brings those decisions together. Allow about 20–25 minutes. Work through each stage before opening its discussion. You do not need executable code or a single “best” algorithm; make your reasoning concrete enough that another person could implement and evaluate your proposal.
A support team wants to identify incoming requests that need urgent attention. Its records contain submission timestamps, customer IDs, message text, account information, and eventual resolutions. Some customers submit several requests. The team hopes to use the system next month.
Exercise 23.2: Define the task before choosing a model
What should count as urgent, who should help define it, and what action would a positive prediction trigger?
Is ML an appropriate approach? Propose a simpler alternative and explain how you would compare them.
Define one training example, a possible target, and usable features. Identify a tempting feature that would be unavailable when the request arrives.
Discussion: read after trying
One example could be a request at submission time, with a target defined by a documented urgency assessment. Support staff and affected users can help establish which consequences require urgent attention. Historical handling speed alone may reflect staffing or unequal service rather than urgency. A keyword rule or manual triage process is a useful comparator; neither should be assumed reliable without evidence. Submission text and account information already available then may be features. Eventual resolution, final handling time, or notes added after triage would leak future information. A useful proposal names the decision and label limitations before choosing an estimator.
Exercise 23.3: Build an honest comparison
Design a split that helps estimate performance next month. How would repeat customers affect your evaluation? How would the plan differ if the service were intended only for new customers?
Choose a baseline and an initial model. Describe preprocessing for text, numerical, and categorical inputs and explain where it is fitted.
A colleague vectorizes all messages, tries many models, and repeatedly checks test accuracy to choose the winner. Identify the problems and propose a corrected workflow.
Discussion: read after trying
A later holdout period better represents future use than shuffling all requests. Validation within the earlier data should also respect time. Repeat customers may legitimately appear in both periods if future use includes returning customers, but duplicated requests or information recorded later can still leak information. For entirely new customers, evaluation should also prevent customer overlap; a grouped random split alone would not address time changes.
Compare against the existing process and a simple estimator such as DummyClassifier. A reasonable first model is logistic regression with count-based text features, imputation and scaling where appropriate for numerical inputs, and imputation and one-hot encoding for categorical inputs. Use a ColumnTransformer inside a pipeline. Fit learned transformations within each training fold, not before splitting or on validation data. A target-derived preprocessing step needs particular care too.
Vectorizing all messages lets held-out text influence the vocabulary. Repeatedly selecting by test accuracy turns the test set into development data. Use validation or cross-validation for choices, then evaluate the fixed approach on untouched test data. If the original test data have already guided selection, seek fresh held-out evidence rather than relabeling the old score as final.
Exercise 23.4: Decide what the result supports
Suppose 95% of requests in a held-out sample are non-urgent. A model achieves 96% accuracy.
What accuracy would predicting “non-urgent” for every request achieve? What does the one-percentage-point gain tell us, and what does it leave unknown?
What further results would help decide whether the model improves triage? Consider missed urgent requests, false alarms, staff capacity, and performance across relevant groups.
Write a 100–150 word recommendation to the support manager. Explain the evidence, one consequential limitation, and a specific next action. Do not invent precision or recall values.
Discussion: read after trying
The majority baseline achieves 95% accuracy. A gain to 96% does not reveal how many urgent requests the model finds: it could still miss most of them. Inspect the confusion matrix, urgent-class recall and precision, and the number of requests sent for review at a proposed threshold. Choose that threshold on validation evidence with staff capacity and error consequences in mind. Inspect uncertainty and relevant subgroups rather than assuming an aggregate gain benefits everyone.
A defensible recommendation would say that accuracy alone is insufficient to justify changing triage. A concrete next step could be a time-respecting validation study reporting urgent-request recall and review workload against the existing process, with staff checking the target definition. A limited evaluation without changing actual routing could gather evidence before operational use. Several recommendations are possible, but the supplied accuracy does not establish safety or usefulness.
Exercise 23.5: Change the question
The team also wants to discover recurring themes in requests, but has no theme labels. How does this task differ from urgency prediction? Suggest an approach using methods from the course. How would you assess whether the resulting groups are useful, and what would those groups fail to establish?
Discussion: read after trying
This is an exploratory unsupervised task rather than supervised urgency prediction. Text representations with clustering or topic modeling could suggest themes for staff to inspect. Examine representative requests, stability, coverage, and whether staff find the groupings useful for a specified action. Clusters need not correspond to natural or objectively correct categories. A group is not evidence of urgency, a cause of complaints, or a customer trait. Check privacy before circulating example messages.
What did you just demonstrate?
The activity connects to the original nine course objectives:
Course objective
Evidence in your response
Identify problems suitable for ML
Decide whether urgency prediction needs ML (23.2)
Select an appropriate ML tool
Justify an initial model and an exploratory method (23.3, 23.5)
Transform different data types into features
Plan text and tabular preprocessing (23.3)
Apply supervised and unsupervised tools
Specify implementable approaches for two distinct tasks (23.3, 23.5)
Distinguish training, validation, and testing
Assign each dataset a clear role (23.3)
Communicate pipeline results
Write a recommendation for the manager (23.4)
Recognize limitations of methods and ML
Examine targets, errors, groups, and unsupported claims (23.2–23.5)
Avoid mixing training and test information
Identify future information and preprocessing leakage (23.2, 23.3)
Use good applied habits, including baselines
Start with comparators and a reproducible pipeline (23.3, 23.4)
These also fit the book’s five broader learning goals: frame the problem, choose the ingredients, build and evaluate a prototype, recognize limitations, and communicate responsibly. Explaining a workflow is one kind of evidence; implementing it is another. To extend the activity into practice, build the proposed pipeline on a suitable dataset and check whether the observed errors change your recommendation.
Taking the course forward
The project activity brings the course together. Here is a workflow to return to in your next project, followed by a chance to recognize what you can now explain and decide where you want more practice.
A workflow to take with you
There is no fixed recipe that makes every ML project sound. The following is a reference for supervised learning, with decisions that may need revisiting as you learn more.
Understand the decision and the data
Talk with the people who will use the result, those who collected the data, and those affected by its use. Define the unit of prediction, target, input information available at prediction time, and intended action. Ask whether rules, service changes, or human judgement would better address the goal. Decide what success means and whose mistakes matter. Data availability does not itself justify using a field or automating a decision.
Protect evaluation before experimenting
Choose a holdout strategy that represents intended use. A random split can be appropriate for independent examples; time order and repeated entities may require temporal or grouped splits. Keep the final test data outside exploratory development. Investigate training data, label quality, missingness, and coverage. Keep learned preprocessing and feature selection inside the validation workflow.
Build a useful comparison
Start with the existing approach and a simple baseline. Build a reproducible pipeline and try a sensible initial model. Use validation or cross-validation to examine errors, underfitting, overfitting, and whether improvements matter. Tune promising choices within a reasonable search budget. More algorithms, larger searches, and ensembles are options to justify, not steps every project must include.
Inspect scores across folds, but do not treat their standard deviation as an automatic confidence interval: folds share training examples, and the splitting scheme itself makes assumptions. Examine relevant groups and conditions alongside aggregate results. Interpretation tools can help diagnose model behaviour; they do not establish causation or fairness.
Evaluate, explain, and decide
Once development choices are fixed, evaluate on the held-out test set. Report the baseline, chosen metrics, important error patterns, and limitations. If test findings lead to revisions, acknowledge that they informed development and obtain fresh evaluation evidence for the revised approach. Explain the practical implications to stakeholders and recommend a specific action, which may be further investigation or a decision not to deploy.
Operate and revisit
If deployment is justified, preserve the code, dependencies, artifact, and evaluation record. Decide whether to refit on all available data, document that choice, and plan for monitoring, failures, and changes. Establish who can respond to problems. Continue checking the purpose and consequences, not just the score.
Return to Eva’s questions
In Chapter 1, Eva asked how a spam classifier could work on a message it had never seen, what happens when it makes a mistake, and how we could know whether it is reliable. Those questions should now feel more approachable.
Exercise 23.6: Explain what you now know
Choose two questions and answer each for someone who has not taken this course. Use a concrete example and state a limitation.
If the code is written by a programmer, in what sense does a model learn?
How can a model predict a label for a message it has never seen? Why is a correct answer not guaranteed?
What are the consequences of marking a legitimate message as spam, and how should those consequences affect evaluation?
What evidence would make you trust a spam filter for its intended use? Is a confidence score enough?
Review after explaining
A useful explanation connects training examples to fitted patterns and generalization, rather than suggesting the model understands every message. Distinguish false positives from false negatives and connect metrics or thresholds to their costs. Reliability requires suitable held-out evidence and attention to intended use; a high score for one prediction, even a calibrated probability, does not guarantee correctness or suitability in a different setting. You should be able to say both what the model can do and what the available evidence cannot establish.
Where would you like more practice?
For each row, choose “I can explain and justify this,” “I can do this with a reference,” or “I need more practice.” Using documentation is normal; the goal is to recognize what you need to check.
Choose one area and a concrete next step: rerun an example with a different split, investigate a model’s errors, or build a small project with a baseline and an honest evaluation. A project that changes your initial recommendation can teach you as much as an improvement in a metric.
Conclusion and farewell
We made it! At the beginning, machine learning could look like calling fit and hoping for useful predictions. You can now ask what the target means, whether information leaks across a split, which errors matter, and whether the evidence supports the proposed use.
You are ready to begin an applied ML project when you can define the problem, build an honest comparison, and explain what the evidence supports. You will still encounter unfamiliar data and methods. This course gives you a way to decide what to try, recognize when something is wrong, and work out what to learn next.
Keep practicing on problems you care about. If you want to understand the mathematics and algorithms more deeply, a course such as CPSC 340 is a possible next step; check its current prerequisites and syllabus. Reproducing a small published result or making an existing workflow easier to reproduce are also useful ways to grow.
Thank you for the questions, experiments, and careful thinking you brought to the course. We hope you take that curiosity into your next project.