Foundations

Machine Learning for Programmers: What Changes When Rules Come From Data

How your code, tests, bugs and releases change when a program's behavior is fitted from examples instead of written by hand.

Key takeaways

  • A trained model is a function whose behavior comes from code, data and settings together, so all three need to be versioned and reviewed.
  • You test a model by measuring its error on examples it never saw during fitting, because it will rarely be right on every case.
  • Many machine learning bugs fail silently: the program runs, the numbers look plausible, and the predictions are wrong.
  • Inputs in production can drift away from the training data, so a model that passed yesterday can degrade without any code change.
  • If you can state the rule exactly and cheaply, write it; learning pays off when the pattern is real but too tangled to spell out.

In ordinary programming you write the rules and the computer applies them to data. In machine learning you supply data, usually with the answers attached, and a training procedure produces the rules. The result is still a function you can call, but nobody typed its logic.

That one change moves the center of your work. The behavior of the system now depends on the examples as much as on the code, correctness becomes a matter of measured error rates, and some of the worst bugs raise no exception at all.

Two ways to build the same function

Suppose you need is_spam(message). The traditional approach is to inspect some spam and write conditions: too many links, certain phrases, a sender that is not in the address book. Each new trick from spammers means another branch, and the branches start to interfere with one another.

The learned approach starts with a pile of messages that people have marked as spam or not spam. You decide how to turn a message into numbers, pick a family of functions, and let an algorithm search that family for the member that makes the fewest costly mistakes on your pile.

The numbers you compute from each message are called features, and the known answers are labels. The vocabulary of examples, features and labels is worth settling early, because every library assumes it. The adjustable values the algorithm sets are parameters.

Where the behavior of the program comes from
Handwritten program A person writes the logic Tests assert exact outputs Bugs usually trace to a line Changes when code changes Learned model A fitting procedure sets parameters Tests measure error rates Bugs may trace to data Changes when code, data or settings change VS Handwritten program A person writes the logic Tests assert exact outputs Bugs usually trace to a line Changes when code changes Learned model A fitting procedure sets parameters Tests measure error rates Bugs may trace to data Changes when code, data or settings change

A rule you can watch being learned

Here is the smallest useful example. Each pair below is the number of links in a message and whether a person called it spam (1) or not (0). Rather than guessing a cutoff, the code tries each one and keeps the best.

# (number of links, is_spam)
examples = [(1, 0), (2, 0), (3, 0), (4, 1),
            (5, 0), (6, 1), (7, 1), (8, 1)]

def errors(t):
    return sum((x >= t) != bool(y) for x, y in examples)

best = min(range(1, 10), key=errors)
print(best, errors(best))   # 4 1

The learned rule is "spam if there are at least 4 links", and it gets one of the eight examples wrong: the legitimate message with 5 links. A cutoff of 6 also makes exactly one mistake. Python's min returns the first of the tied values, which is an arbitrary choice that your data cannot settle.

Everything in larger systems is already here. You chose the input (link count), the family of rules (single cutoffs), the objective (count of mistakes) and the search method (try everything). A neural network changes the scale of each choice and keeps the structure.

Notice also what the code cannot tell you. One error in eight describes these eight messages. It says little about the next thousand.

What your source code becomes

In a conventional service, reading the repository tells you what the service does. With a learned component, the repository holds the recipe, and the behavior lives in a file of fitted parameters produced by running that recipe on a particular dataset.

To reproduce or explain a model you need several things pinned down together:

Ingredient What to record
Training code Commit identifier
Data Snapshot, query or content hash, plus how rows were selected
Settings Hyperparameters, which are the choices you make before fitting
Environment Library versions and, where relevant, hardware
Randomness Seeds for shuffling and initialization

Even with all of this recorded, results can differ slightly between runs, since some parallel arithmetic is not exactly repeatable. Why two training runs disagree explains the sources and how far you can control them.

Saved model files deserve the same suspicion as executables. Some formats, Python's pickle among them, can run arbitrary code when loaded, so load only artifacts you trust.

Testing moves from assertions to measurements

A unit test says that add(2, 2) returns 4, every time. A spam model that is right 97 times in 100 is neither passing nor failing in that sense. You need to decide what error rate is acceptable, on which examples, and which mistakes matter more.

The essential discipline is to measure on data the fitting process did not touch. A model can memorize its training examples and score perfectly on them while being useless on new ones. So you hold some data back, and usually hold back two portions: one for making choices and one for the final report. See the jobs of training, validation and test sets.

Ordinary tests still matter, and they catch a lot:

  • Feature functions return the expected values for hand-made inputs.
  • Tensor or array shapes match what the next step expects.
  • The training loop can drive the error near zero on a tiny batch.
  • A saved and reloaded model gives the same predictions on a fixed input.
  • Known easy cases are still classified correctly after retraining.

Bugs that do not crash

If you swap two columns, scale the inputs differently at serving time, or let a copy of the answer slip into the features, the program often runs happily. The only symptom is a score that is worse than it should be, or suspiciously better.

That last case is called leakage: information that would not be available at prediction time reaches the model during training. A classic form is computing an average or a scaling factor over the whole dataset before splitting it. Fit every such statistic on the training portion alone, then apply it to the rest.

Debugging therefore looks more like investigation than stack-trace reading. You inspect rows, compare distributions, read the examples the model gets wrong, and shrink the problem until the expected behavior is obvious. A structured routine for debugging a model that will not learn saves days.

Your data is now a dependency

A library you depend on changes only when you upgrade it. The world that generates your inputs changes whenever it likes. A new product category appears, a sensor is recalibrated, an upstream team starts sending a field in different units, or spammers adapt to your filter.

The model's code is identical, yet its error rises. This means a release is the beginning of a monitoring duty. You log inputs and predictions (within your privacy rules), watch for shifts in their distributions, and collect true outcomes when they eventually arrive. What to monitor after launch covers the practical list.

It also changes the interface contract. A type signature says a field is a float. It does not say the values were mostly between 0 and 1 during training. Add explicit checks for ranges, missing values and unseen categories at the boundary, and decide in advance what the system does when a check fails.

Which of your habits carry over

Most of them do. Version control, code review, small reproducible cases, automated pipelines and clear interfaces are as valuable here as anywhere, and many machine learning projects struggle because those habits are missing.

Some instincts need adjusting. You cannot specify the behavior fully in advance, so plan work as experiments with a recorded result each. A change that should help can hurt, which makes it worth changing one thing at a time. Performance claims need an uncertainty, since a gain of a few tenths of a percent on a small test set may be noise.

When to reach for learning at all

Use a handwritten rule when the logic is known, stable and compact: tax arithmetic, format validation, access permissions. Consider learning when people can judge individual cases but cannot write down how, when the pattern involves many weak signals, or when it shifts often enough that retraining beats rewriting.

Either way, build the simplest version first. A majority-class guess or a one-line heuristic tells you what a model has to beat, which is the point of starting with a simple baseline. The comparison between rules and learned models is often closer than expected, and the best production systems frequently contain both.

A sensible first week on a new model

Start by reading raw examples, a few hundred if they are small, and note anything that surprises you. Then write the evaluation script before the training code, so that every later idea is judged the same way. Next, get a trivial predictor through the whole path from data file to score. Only then swap in a real model.

This order feels slow, but it exposes broken joins, misread columns and impossible labels while they are still easy to trace.

Common questions

Do I need advanced math to start?

No. With school algebra and basic Python you can train and evaluate useful models. Linear algebra, probability and calculus become important when you want to understand why a method fails or to build new ones.

Is a trained model still deterministic?

At prediction time most models return the same output for the same input, apart from small numerical differences across hardware. Some systems add randomness on purpose, for instance when sampling generated text. The uncertainty you should worry about is different: whether the output is right.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic