Machine learning in everyday applications

Recognize the task behind an everyday feature

A suggested book, an unwanted-message warning and a forecast of tomorrow’s orders can all use machine learning. Their common feature is not the screen or the word “smart.” They use information to estimate an outcome that is not already known. What they predict—and what happens when they are wrong—can be very different.

In the previous lesson, we distinguished known targets, unlabeled structure and action rewards. Here we connect those ideas to applications. We will follow a book recommendation in detail, then inspect messages, forecasts, recognition systems and chatbots.

A feature may combine learned models with ordinary programmed rules. A sorting menu, an exact fee calculation or a fixed keyword lookup does not become machine learning merely because it appears in a modern application. Ask where fitting actually occurs and what evidence guides it.

What you’ll learn

  • Identify an application’s input, estimated output and final action.
  • Distinguish a transparent recommendation rule from a fitted model.
  • Explain the different costs of false alarms and missed cases.
  • Trace a small trained message classifier and numerical forecaster.
  • Recognize missing information, changing data and recommendation feedback loops.

Three jobs, three kinds of output

Recommend

Suggest a book

Information available
Interests, book descriptions and prior interactions
Estimated output
A score for each candidate book
Application action
Show a ranked shortlist

A recommendation can be irrelevant or too repetitive.

Classify

Filter a message

Information available
Message text and permitted contextual signals
Estimated output
Spam category or a risk score
Application action
Deliver, flag or review

A legitimate message can be flagged by mistake.

Forecast

Plan tomorrow’s stock

Information available
Past orders and information known before tomorrow
Estimated output
Expected demand
Application action
Choose an order quantity

Too much stock and too little stock have different costs.

An estimate is not the final action. The application chooses what to show, flag or order.

Separate the input, prediction and action

Consider a message filter. The input is the text and any other relevant information the system is permitted to use. The model may predict a category or score. The application then decides whether to show a warning, move the message or request review. Those are three distinct parts, even when they happen almost instantly.

This separation helps diagnose mistakes. Incorrect input may confuse a good model. A poor model may produce an unreliable score. An aggressive decision rule may block too many legitimate messages even when the score contains useful information. Improving one part does not automatically fix the others.

InputNew message text
Model outputEstimated spam score
Application policyFlag for review above a chosen threshold

A threshold is a cutoff used to turn a score into an action. It is a design choice with consequences, not a universal boundary between truth and falsehood. We examine score-based decisions in model evaluation.

Recommendations: rank useful candidates

Imagine a library reader interested in science and history. A content-based approach compares those interests with book descriptions or tags. A collaborative approach uses interaction patterns—for example, which books readers with similar histories enjoyed. A system can combine these approaches, and either may use learned representations or simpler similarity methods.

A ranking assigns scores and places candidates in an order. The score might represent predicted interest, an estimated response or a chosen similarity measure; it is not automatically the probability that the reader will enjoy a book. The application may then adjust the order for availability, variety or other goals.

The next program uses an explicit tag-matching rule. It is a baseline: a simple approach used for comparison. It is deliberately not a trained model. Before adding a learned ranker, we should understand what this simple approach can already do and what evidence would demonstrate an improvement.

For a fitted ranker, training signals might include ratings or observed interactions. A borrow or click is not identical to satisfaction: availability, placement and exposure influence those signals. See Google’s recommendation overview for the broader task.

Build an inspectable book ranking

Prepare and run

Use standard Python in the course environment. All book data is embedded in this complete program.

Python · complete runnable example

reader = {"science", "history"}
books = {
    "Space": {"science", "space"},
    "Ancient Cities": {"history", "travel"},
    "Cooking": {"food"},
}

scored = []
for title, tags in books.items():
    score = len(reader & tags)
    scored.append((title, score))

# Highest overlap first; alphabetical title breaks equal-score ties.
ranked = sorted(scored, key=lambda item: (-item[1], item[0]))
for title, score in ranked:
    print(title, "shared interests:", score)

Expected output

Ancient Cities shared interests: 1
Space shared interests: 1
Cooking shared interests: 0

The reader and each book’s tags are sets, collections of distinct values. The & operator finds the shared tags, and len counts them. Scored stores each title with its overlap count. The sorting key puts larger counts first because it negates the score, then uses the title alphabetically for ties. Ancient Cities and Space both score one; the tie rule puts Ancient Cities first. No fitting or training occurs.

An alphabetical tie-break makes output repeatable; it does not establish that Ancient Cities is the reader’s best choice. A zero score means no shared listed tags, not that the reader would dislike Cooking. Our limited representation can miss interests or fail to support discovery.

Why these books received their scores

Reader interestssciencehistory
Spacescience ✓space1 shared tag
Ancient Citieshistory ✓travel1 shared tag
Cookingfood0 shared tags
Matching tags explain this rule’s scores. A score is evidence from the chosen representation, not a complete description of the reader.

Message filtering: inspect both kinds of mistake

A supervised message classifier can learn from messages labeled spam or ordinary. Text must first be represented numerically, such as by counting words. The learner fits a relationship between those measurements and the labels. It can then classify another message whose correct label is not supplied.

A false positive occurs when an ordinary message is flagged as spam. A false negative occurs when spam is missed. The costs differ: hiding a genuine appointment message can matter more than failing to hide an easily ignored advertisement. Count both kinds of mistake instead of reporting only a single overall success percentage.

Fraud review can use a related classification or risk-scoring idea, but an unusual transaction is not proof of fraud. Some anomaly-detection methods find unusual patterns without fraud labels. A new location, unusual amount or uncommon purchasing pattern may have an innocent explanation. The action and review process must reflect that uncertainty.

The spam project adds a larger text-processing workflow; the outlier documentation distinguishes different unusual-observation tasks.

Run a tiny trained message classifier

Prepare and run

Use the course environment with scikit-learn. These six fictional English messages are deliberately easy to separate. This is a mechanism demonstration, not a reliable spam filter.

Python · complete runnable example

from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

messages = [
    "free prize claim", "win free prize", "claim cash prize",
    "meeting agenda today", "project meeting notes", "team project update",
]
labels = ["spam", "spam", "spam", "ordinary", "ordinary", "ordinary"]
model = make_pipeline(CountVectorizer(), MultinomialNB())
model.fit(messages, labels)
for text in ["claim free prize", "project meeting"]:
    print(text, "->", model.predict([text])[0])

Expected output

claim free prize -> spam
project meeting -> ordinary

CountVectorizer learns a vocabulary from the training messages and converts each message into word counts. MultinomialNB then fits a classifier using those counts and their known labels. Make_pipeline connects the two steps so predict transforms each new text with the same learned vocabulary before classifying it. The list [text] supplies one message, and [0] selects its one predicted label.

Unlike tag overlap, this program calls fit and learns from labeled examples. Two plausible outputs do not establish reliability. Real messages contain unfamiliar wording, other languages and changing tactics; useful evaluation needs separate representative messages and checks of both false alarms and missed spam. Words outside this learned vocabulary do not become new vocabulary just because predict sees them.

API references: numerical text features and Naive Bayes classifiers.

Forecasting: estimate demand before it happens

A café wants enough sandwiches for tomorrow without wasting food. A forecast estimates a future quantity using past observations and information available at the forecast time. Relevant inputs might include past demand, weekday, known bookings and planned opening hours.

Tomorrow’s final sales are not an input available today. Including them would leak the answer into the evaluation. Time also matters when checking a forecast: training on later records and testing on earlier ones can answer a different question from predicting an unseen future. Use a time-appropriate evaluation design.

Observed sales can understate demand when sandwiches sold out early. A record of ten sold sandwiches does not prove only ten were wanted. Understanding how a measurement was produced is part of understanding the model’s training data.

An estimate of demand is separate from the stock decision. Shelf life, preparation capacity and the costs of shortages or leftovers affect how much the café should make. Compare with a simple alternative such as an appropriate recent-demand average before relying on a complex model.

Inspect a simplified demand estimate

Prepare and run

Use the course environment with NumPy and scikit-learn. This example isolates one relationship: bookings known beforehand and orders later observed. It is not a full seasonal time-series forecasting system.

Python · complete runnable example

import numpy as np
from sklearn.linear_model import LinearRegression

# Fictional training days: bookings known beforehand, then observed orders.
bookings = np.array([[0], [10], [20], [30]])
orders = np.array([20, 30, 40, 50])
model = LinearRegression().fit(bookings, orders)
print("Estimated orders for 15 bookings:", round(model.predict([[15]])[0]))

Expected output

Estimated orders for 15 bookings: 35

The fictional training rows follow orders = 20 + bookings. Fit recovers that line, and 15 new bookings produces an estimate of 35 orders. The twenty-order starting value summarizes this invented relationship; it is not an operational promise about every unbooked day. Rounding displays an integer estimate, not a confidence guarantee.

A real forecasting evaluation would keep later days for checking, compare suitable baselines and account for relevant changes. The example does not prescribe making exactly 35 sandwiches, because the stock decision also needs a cost and capacity policy.

Recognition: turn pixels or sound into useful outputs

An image classifier can estimate which object category appears in a picture. Pixels are numerical measurements; training examples may pair images with known categories. Detecting where objects appear is a different task from assigning one label to the whole image. A category prediction is not a complete understanding of the scene.

Speech recognition estimates text from audio. Sound measurements, context and the learned representation contribute to a sequence of words, not simply a single class. Accents, background noise, recording devices and unfamiliar terms can change performance.

Evaluation should resemble intended use. A model tested only on clear daylight pictures may perform differently in a dim room; a speech system tested in silence may fail in a crowded café. Check relevant conditions rather than assuming one headline result covers every user and environment. No image or audio model is trained by the short text examples in this lesson.

Chatbots: retrieving a fact is different from generating a reply

A library chatbot may answer “When do you close?” from an approved timetable. A fixed lookup can return a stored answer without a learned model. A trained language model can generate text from patterns learned during training. A system may also retrieve relevant records and use them as context for a generated response.

These mechanisms can share the same chat interface. What matters is how the answer is produced and checked. A generated sentence can sound confident while containing a wrong opening time. Retrieving the current timetable can help ground the answer, but does not guarantee every generated statement follows it.

Keep the current source visible, handle missing information honestly and offer a route to a person when needed. A conversation’s text can be used as context during that interaction without changing the model’s trained parameters. Updating authoritative facts, changing retrieved records and retraining a model are different operations.

Trace a recommendation and question a decision

Task 1: the reader’s interests change to {science, space}. Book tags are Space: {science, space}, Ancient Cities: {history, travel}, Cooking: {food}. Using the stated rule—shared-tag count, then alphabetical tie-break—what order and scores result?

Worked answer

Space scores two. Ancient Cities and Cooking score zero, and their tie is broken alphabetically. The order is Space (2), Ancient Cities (0), Cooking (0). This is still a programmed rule; changing the input does not turn it into training.

Task 2: a spam system blocks a genuine appointment message and allows an unwanted advertisement. Name the mistakes and explain why one percentage may hide an important issue.

Blocking the genuine message is a false positive; allowing the advertisement is a false negative. Their consequences differ. A high overall accuracy could coexist with costly blocked appointments, so inspect the error types for the intended use.

Task 3: a café forecast is excellent when tomorrow’s actual orders are included as an input. Is that useful evidence for today’s planning? No: that value is not available today. It leaks the outcome into the evaluation and does not reflect the real prediction task.

Changing data, missing signals and feedback loops

A system can face data drift: the distribution of inputs changes. The relationship between inputs and outcomes can also change. New spam wording, different café customers or changing book availability can make earlier results less relevant. Monitor suitable outcomes and decide when data or model updates are justified; merely receiving requests does not guarantee improvement.

Recommendations also affect what can be observed. If the library only shows science books, readers have few chances to choose history books. Later interactions may appear to confirm a preference created partly by exposure. A lack of clicks on an unseen book does not demonstrate dislike. This is a feedback loop: outputs influence the data collected next.

Missing history matters for new readers and new books. Suitable defaults, explicit preferences or exploration can help, but each has trade-offs. Avoid treating one person’s few interactions as a complete account of their interests.

Use information appropriate to the task, protect it and inspect who is missing or poorly served by the examples. Evaluate the complete workflow, including final actions and recovery from errors. A model score is evidence within that workflow, not a complete understanding of a person.

Further reading: how models fit into larger ML systems.

Quiz: identify where learning occurs

Which program in this lesson learns from examples?
Choose one answer. You can try again.

Answer and explanation

The message pipeline, because fit uses labeled messages.

Its vocabulary and classifier are fitted from training data. The later prediction uses those learned components.

Quiz: inspect the consequence of a mistake

A genuine appointment message is placed in spam. What happened?
Choose one answer. You can try again.

Answer and explanation

A false positive: an ordinary message was flagged as spam.

The spam-positive decision was incorrect. Its cost should be considered separately from missed spam in the application.

Quiz: what does missing interaction mean?

A reader never clicked a book that the interface never displayed. What can we conclude?
Choose one answer. You can try again.

Answer and explanation

The record alone does not show whether the reader would choose it.

The recommendation controls exposure, which influences observable behavior. Evaluate this feedback loop before interpreting absence as dislike.

Recap: explain the job before choosing a model

For any application, name the information available at prediction time, the estimated output and the final action. Recommendations rank candidates; classifiers estimate categories or scores; forecasts estimate future quantities. Recognition and generation have their own outputs and evaluation needs.

Our tag-overlap ranking was an inspectable programmed baseline. The message classifier and demand estimator fitted parameters from examples. Their tidy outputs explain a mechanism; they do not establish deployment readiness.

Check relevant errors, compare a suitable simple alternative and watch what changes after use. A false alarm, missing exposure or unavailable future input can undermine a convincing result. Keep final decisions distinct from predictions and provide a way to handle mistakes.

Before the next lesson: choose one application you use and write its input, output and one costly mistake. For a spam filter: message text, spam decision, and incorrectly hiding a genuine message. The next step is learning how to load and inspect the examples a model will actually use.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Loading datasets: read and inspect data with pandas →