RohitSahera.com›Articles›Machine learning

A little café experiment · Field note 01

One cup
at a time.

11 min readBeginner friendlyLinear regression · SGD

Two café cats. One recipe. A growing pile of failed cups. And a surprisingly useful way to understand how a machine can learn from examples.

Cartoon scene of a large ginger cat pouring coffee while a small white cat reads The Perfect Coffee Recipe in a Parisian café.
The Perfect Cup? · Paris, 8:07 a.m.Ginger is improvising. Chutki is concerned.

What you'll leave with: the difference between regression and a regressor, what linear regression is trying to learn, why SGD adjusts one example at a time, and where this kind of prediction is useful in the real world.

01 / Meet the café crew

A recipe, two cats,
and a very messy counter.

At a little café on a quiet Paris street, Ginger has decided today is the day they make the perfect cup. Chutki has the recipe book. Ginger has confidence. You can probably guess which one is causing trouble.

The first cup is weak. The second is bitter. The third is… technically coffee. Ginger keeps changing things at once: a little more water, a longer pour, a different grind. Chutki cannot work out what helped because nobody wrote anything down.

So Chutki takes charge of the notebook. They agree on a tiny experiment: keep the beans, grind, coffee dose, and water temperature the same. Change only the brewing time. After every cup, record the time and give the result a taste score from 1 to 10.

Ginger gets the kettle. Chutki gets the data. The counter gets progressively messier.

Ginger · Head barista (self-appointed)“I made it stronger. And faster. And… more.”
Chutki · Recipe supervisor“That is three changes, Ginger. We need to know which one did what.”
Ginger“Fine. One thing at a time. But I’m still in charge of the kettle.”
Portrait crop of the large ginger cat from the café illustration

Ginger

The enthusiastic barista

Big ideas, quick paws, questionable pouring technique. Ginger creates the experiments.

Portrait crop of the small white cat from the café illustration

Chutki

The careful note-taker

Small, focused, and armed with a recipe book. Chutki records what happened.

A small but important note: the café, tasting scores, and dataset in this article are fictional teaching examples. Coffee taste is subjective and depends on many variables. We're holding most of those variables steady so the machine-learning idea is easier to see.

02 / From cups to examples

Chutki starts a data notebook.

Each row is one example. The brewing time is the input (also called a feature); the recorded taste score is the answer we want the model to learn to estimate (the target or label).

TrialBrew time · featureTaste score · targetChutki's note
012.0 min4.3 / 10A little underdeveloped
022.5 min4.6 / 10Still quite sharp
033.0 min5.7 / 10Getting more balanced
043.5 min5.5 / 10One odd cup
054.0 min6.6 / 10Closer!
064.5 min6.9 / 10Smoother finish
075.0 min7.8 / 10Ginger's favourite
085.5 min8.0 / 10Worth repeating

Illustrative data only—not a real coffee study or a recommended recipe. The small bump in trial 04 is useful: real observations rarely line up perfectly.

Look at the notebook. There seems to be a broad pattern: in these examples, longer brew times tend to come with higher scores. But the scores don't rise perfectly every time. That little bit of messiness is exactly why a model is useful: we want it to learn the overall relationship rather than memorise a rigid sentence such as “every extra half-minute adds exactly one point.”

03 / Why machine learning?

Instead of writing every rule,
learn from examples.

Chutki has a question: “Could we teach a little program to spot the pattern in our notebook?” That's the basic idea behind supervised machine learning.

With ordinary rule-based programming, someone writes the rules explicitly: if this happens, do that. Rules are excellent when the logic is clear and stable. But when a problem involves many examples and a pattern that's hard to describe by hand, we can instead give a learning algorithm examples with known answers. It adjusts a model so its predictions become more useful.

In our café, the examples are the tasting notes. The model sees brew times paired with scores, looks for a relationship, and uses what it learns to estimate a score for a brew time it hasn't seen before. It isn't developing a sense of taste. It's learning a statistical pattern from the data we gave it.

01

Examples

Past brews with their measured inputs and recorded scores. In ML, this is the training data.

02

A model

A mathematical relationship that turns inputs—like brew time—into a prediction.

03

Learning

An algorithm adjusts the model's parameters to reduce the difference between predictions and known answers.

Why is this useful? Because once a pattern has been learned, we can use it to make estimates for new cases—without hand-writing a separate rule for every possible input. It can be especially helpful when there are lots of examples or several variables interacting. But ML is not magic: it needs relevant data, a sensible target, and honest testing on examples it did not train on.

04 / What kind of answer?

Numbers or names?
That changes the task.

Machine learning problems are often grouped by the kind of answer we want.

Regression → a number

Estimate a quantity that can take many numerical values.

“What taste score might this cup get?” · 7.2 / 10

Classification → a category

Choose a label from a set of categories.

“How does this cup taste?” · bitter / balanced / weak

Our café question is a regression problem because the target is a numerical score. A model built for this kind of job is called a regressor. The word sounds grand, but it simply means a model or estimator designed to predict numerical values.

05 / Meet linear regression

Give the pattern
a line to live on.

Imagine placing every row in Chutki's notebook on a graph: brewing time along the bottom, taste score up the side. A straight line can summarise the general trend.

A simple linear regression model uses a line to estimate the target from an input. It won't pass through every dot—and it shouldn't try to. Its job is to capture the overall relationship, including the fact that individual cups vary.

ŷ = wx + bŷ is the predicted score · x is brew time · w controls the slope · b is the intercept, which shifts the line up or down.

With more than one feature—say brew time, grind size, water temperature, and coffee dose—the model can combine them:

ŷ = b + w₁x₁ + w₂x₂ + … + wₚxₚEach feature gets a weight. The model adds their contributions to make one numerical prediction.

How does the model know whether its line is any good? It makes a prediction, compares it with the recorded score, and measures the miss with a loss function. For our demonstration we'll use squared error: the difference is squared, so a larger miss is penalised more heavily. Training is the process of adjusting the weights and intercept to reduce that loss.

06 / A tiny learning lab

Watch the line learn,
one cup at a time.

The dots are the eight tasting notes. The teal line is the model's current guess. Each step uses one selected example to nudge the line.

Chutki says: “One cup. One update. Let's see if the line gets a little wiser.”
Brew time vs. taste scoreReady · 0 updates
024681023456Brew time (minutes)Taste score (out of 10)
Recorded scoreCurrent modelMost recent example

Try a very large learning rate and watch the error grow or the line jump wildly. Then reset and use smaller steps. This playground is a simplified, unregularised, one-feature example of per-sample SGD—not a complete reproduction of every setting used by scikit-learn.

07 / So what is SGD?

The little adjustment
behind the learning.

Linear regression tells us what kind of model we're fitting. Stochastic gradient descent is one way to adjust that model's parameters.

Imagine measuring the model's error on every cup, then recalculating the best adjustment using the whole notebook. That's the idea behind a batch update. SGD takes a different route: it estimates the direction of improvement using one training example at a time, then updates the parameters before moving to another example. The path can wobble because one cup may suggest a slightly different adjustment from the next, but each update is relatively small and inexpensive.

01Make a guess

Use the current line to predict the score for one cup.

02Measure the miss

Compare the prediction with Chutki's recorded score.

03Find a direction

Use the gradient to see how the parameters affect that error.

04Nudge and repeat

Move against the gradient, then look at another example.

What does “stochastic” mean here? It means the update uses a randomly selected or shuffled individual example, rather than the entire dataset at once. In practice, training usually makes multiple passes through the data (called epochs) and shuffles examples so the order doesn't become a hidden pattern of its own.

The learning rate: don't overdo it.

The learning rate controls how large each update is. Too small, and training may crawl. Too large, and the model can overshoot a useful solution or even diverge. Finding a sensible learning rate is part of training a model.

A loss function gives us a target.

For one example, our squared-error loss is the square of prediction minus actual score. The gradient tells us how that loss changes as we move the line's slope and intercept.

One sample · squared-error loss

L = (ŷ − y)²
w ← w − η · 2(ŷ − y) · x
b ← b − η · 2(ŷ − y)

η (eta) is the learning rate. y is the recorded score; ŷ is the model's prediction. These are the updates for our one-feature, unregularised example with squared-error loss.

A practical Python glimpse · scikit-learn

# Our fictional brewing-time examples and taste scores
import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X = np.array([[2.0], [2.5], [3.0], [3.5],
              [4.0], [4.5], [5.0], [5.5]])
y = np.array([4.3, 4.6, 5.7, 5.5, 6.6, 6.9, 7.8, 8.0])

model = make_pipeline(
    StandardScaler(),
    SGDRegressor(
        loss="squared_error",
        penalty=None,       # no regularisation for this demo
        learning_rate="invscaling",
        eta0=0.01,
        max_iter=2000,
        tol=1e-4,
        random_state=42
    )
)

model.fit(X, y)
predicted_score = model.predict([[4.0]])[0]
print(round(predicted_score, 2))

Why the scaler? Gradient-based methods are often easier to tune when input features are on comparable scales. This example scales the input feature in a pipeline. In real work, keep preprocessing inside a pipeline and fit it only on training data to avoid data leakage.

08 / Outside the café

Where can a regressor
actually be useful?

Whenever a useful answer is a number, regression may be part of the solution. The features and data change; the underlying question is familiar.

🚚

Delivery estimates

Estimate how many minutes a delivery may take from distance, traffic, weather, and past delivery records.

⚡

Energy demand

Estimate electricity consumption from time, temperature, day type, and historical usage.

🛒

Demand planning

Estimate how many units of a product may be needed, helping a team plan stock.

🌾

Crop yield estimates

Estimate output using rainfall, soil measures, growing conditions, and historical farm data.

🏭

Predictive maintenance

Estimate a sensor reading or remaining useful time from machine behaviour—when the target and data support it.

🏠

Price estimation

Estimate a numerical price from property or product features, while accounting for uncertainty and local context.

These are examples of regression tasks, not a promise that linear regression or SGD is always the right model. Some relationships are curved, change over time, or depend on interactions between features. In those cases, another model may work better. The right choice comes from testing performance on data the model has not seen.

09 / A useful reality check

What this little line
cannot tell us.

Our example is deliberately simple. Real coffee flavour depends on grind size, dose, water temperature, bean variety, roast, water chemistry, equipment, and the person tasting it. A single line using only brew time cannot capture all of that. The made-up scores are designed to create a visible trend, not to prescribe a real recipe.

The same warning applies to real ML projects. A model can learn patterns in incomplete or biased data. A strong training score doesn't guarantee it will work on new cases. We need to check its errors, compare it with a sensible baseline, and test it on data kept aside from training.

And one more distinction: “regression” is the prediction task, “linear regression” is the model family we're using, and “SGD” is an optimisation method for fitting model parameters. SGDRegressor is scikit-learn's estimator that fits a linear model using stochastic gradient descent. SGD is not a separate kind of prediction problem.

10 / Keep exploring

For curious paws
and curious people.

If this was your first look at machine learning, these are good next stops. They go deeper without assuming you already know everything.

The last cup

Learning isn't getting it right on the first try.

Ginger still hasn't mastered the pour. Chutki still has notes to take. But now they have a better way to improve: observe, measure, make a prediction, check the miss, and adjust. That's the heart of this little lesson. Linear regression gives us a model for describing a numerical relationship. Stochastic gradient descent gives that model a way to learn through many small updates.

One more cup, Ginger. And this time, read the recipe.
Rohit Sahera · Knowledge, technology & ideasField note 01 · Machine learning