← All posts

AI basics › From statistics to AGI

What is machine learning? Learning rules from data

What machine learning is, how it differs from writing rules by hand, and how training, testing, and overfitting work, with a small scikit-learn example.

You probably meet machine learning several times a day without hearing its name. It’s at work when a photo app finds every picture of your dog, when your phone turns speech into text, and when a shop suggests what to buy next. A 2015 Nature review by Yann LeCun, Yoshua Bengio, and Geoffrey Hinton opens with much the same list (Deep learning). The term comes up even more often lately because the AI tools in the news are built on it too. Google’s introductory course, for one, counts generative AI, the kind that writes text and draws images, as a category of machine learning (What is ML?).

Put simply, machine learning is a way of getting a computer to learn rules from data, instead of having a person write them. Tom Mitchell’s 1997 textbook pins down more precisely what it means for a program to learn. “A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E” (Machine Learning). For a spam filter, T is sorting mail, P is the share sorted correctly, and E is a pile of emails people have already marked.

This is the second post in the series “From statistics to AGI.” Statistics draws conclusions from data under uncertainty, and machine learning puts that same data to work predicting cases it hasn’t seen yet.

Rules written by people and rules learned from data

In traditional programming, a person writes the rules. A spam filter built that way is a list of conditions like “if the subject has this word and the sender is unknown, it’s spam,” and the list grows every time spammers change tactics. Machine learning turns this around. You give the computer many examples with the right answers, and a learning algorithm works out rules that connect them. The result is called a model, and it makes predictions for new inputs. In his 2006 essay The Discipline of Machine Learning, Mitchell put the difference this way. Computer science has focused mostly on how to program computers by hand, while machine learning asks how to get computers to program themselves, from experience plus some initial structure.

Two words come up often from here on. A feature is a measurable property of an example, such as the number of links in an email, and a label is the answer the model should predict, such as spam or not spam.

Supervised, unsupervised, and reinforcement learning

Machine learning is usually divided by what the data offers to learn from. Supervised learning learns from labeled examples. It’s called classification when the answer is a category, and regression when it’s a number like a house price. Unsupervised learning gets no labels and finds structure on its own, for example by grouping customers who shop alike, which is called clustering. In reinforcement learning, a program acts in an environment and learns from the rewards or penalties its actions bring, the way a game-playing program improves by winning and losing. Google’s course describes the three in these terms and adds generative AI as a fourth.

Trying it on tumor data

Let’s try a small supervised example. scikit-learn ships with the Breast Cancer Wisconsin (Diagnostic) dataset, which holds 569 samples. Each has 30 numbers measured from an image of cells drawn from a breast mass with a fine needle, plus a label saying whether the mass was malignant or benign.

from sklearn.datasets import load_breast_cancer

# Each row is one sample; each column is a feature measured from an image
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape)
print(X.iloc[:3, :3])
print(y.value_counts())  # label: 0 = malignant, 1 = benign
(569, 30)
   mean radius  mean texture  mean perimeter
0        17.99         10.38           122.8
1        20.57         17.77           132.9
2        19.69         21.25           130.0
target
1    357
0    212
Name: count, dtype: int64

The 30 columns of X are the features, and y is the label. Next, I split the data in two. The models learn from the training set, while the test set stays hidden until the end to show how they do on samples they’ve never seen. stratify=y keeps the label mix the same in both parts, and a fixed random_state gives the same split every time.

For comparison, I first wrote a rule by hand. In the training set, the mean radius of the cell nuclei averaged about 17.4 for malignant samples and 12.1 for benign ones, so I drew the line at 15 and called anything above it malignant. In a sense, I learned a little from the data myself. The three models do the same automatically, using all 30 features.

from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

# Keep 25% of the samples aside as a test set the models never learn from
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42)

def hand_rule(X):
    # Written by hand: a mean radius above 15 means malignant (0)
    return (X["mean radius"] <= 15).astype(int)

def report(name, predict):
    train = (predict(X_train) == y_train).mean()
    test = (predict(X_test) == y_test).mean()
    print(f"{name:<18} train {train:.3f}  test {test:.3f}")

report("hand-written rule", hand_rule)
models = {
    "decision tree": DecisionTreeClassifier(random_state=42),
    "random forest": RandomForestClassifier(random_state=42),
    "gradient boosting": GradientBoostingClassifier(random_state=42),
}
for name, model in models.items():
    model.fit(X_train, y_train)  # learn rules from the training data
    report(name, model.predict)
hand-written rule  train 0.890  test 0.888
decision tree      train 1.000  test 0.923
random forest      train 1.000  test 0.958
gradient boosting  train 1.000  test 0.958

The numbers are accuracy, the share of samples answered correctly. Of the 143 test samples, the hand-written rule missed 16, which isn’t bad for one line, while the decision tree missed 11 and the other two missed 6 each. Look at the train column, though. All three models score a perfect 1.000 there, so that column alone couldn’t tell them apart. That’s why we keep a test set. Still, a single test sample moves the score by about 0.007, so small gaps can flip with a different split. And of course, this is a teaching dataset, not a diagnostic tool.

Overfitting, and why we keep data aside

The decision tree’s 1.000 in training and 0.923 in testing shows a problem that runs through all of machine learning. Left unchecked, a tree keeps asking questions until every training sample is sorted, and along the way it memorizes quirks and noise that won’t come back. This is called overfitting. It’s a bit like a student who memorizes last year’s exam answers and then stumbles on new questions. What we want is generalization, doing well on data the model hasn’t seen. The scikit-learn guide to cross-validation says it plainly: a model that just repeated the labels it had seen would score perfectly, yet fail to predict anything useful on new data.

Overfitting can also creep in through the test set. Settings you choose before training are called hyperparameters, and a tree’s maximum depth (max_depth) is one of them. The decision tree guide lists limiting it as one way to keep a tree from overfitting. But if you keep tuning such settings while watching the test score, what you know about the test set leaks into your choices. So people hold out a validation set for comparing settings and look at the test set only once, at the end. When data is scarce, cross-validation splits the training data into parts and takes turns holding each one out.

Four algorithms you’ll hear about

There are many learning algorithms, but a handful come up again and again for data in rows and columns like ours.

Algorithm How it predicts Good to know
Linear regression Adds up the features, each multiplied by a learned weight Easy to read; assumes a straight-line relationship
Decision tree Asks a chain of yes-or-no questions about the features Easy to explain, but overfits easily
Random forest Combines many trees, each grown on a random resample Steadier than a single tree
Gradient boosting Adds trees one at a time, each fixing earlier mistakes A strong choice for tabular data

Linear regression, covered in scikit-learn’s guide to linear models, is the same regression you meet in statistics. Random forests and gradient boosting are described in 2001 papers by Leo Breiman and Jerome Friedman, respectively, and scikit-learn’s ensemble guide calls gradient-boosted trees an excellent model, in particular for tabular data.

How it relates to statistics and deep learning

Statistics and machine learning share many tools, regression among them, so the line between them can look blurry. In the same 2006 essay, Mitchell calls machine learning a natural outgrowth of the intersection of computer science and statistics. He describes the question that largely defines statistics as what can be inferred from data plus a set of modeling assumptions, and with what reliability. Perhaps the clearest difference in practice is what gets measured. Statistics often wants to explain a relationship and say how sure we can be, while machine learning usually judges a model by how well it predicts unseen data, as we did with the test set.

Deep learning, on the other hand, is a kind of machine learning, and the difference lies in who prepares the features. The 30 features in our example were chosen by people, who decided what to measure in each image. LeCun, Bengio, and Hinton note that conventional machine learning needed careful engineering and considerable domain expertise to design such features. In deep learning, they write, the layers of features are learned from data instead of being designed by human engineers.

When it fits and when it doesn’t

Machine learning tends to fit when rules are hard to write down but examples are easy to collect. Spotting spam, recognizing what’s in a photo, and guessing what someone might buy are all hard to spell out as rules. Yet examples pile up on their own as people mark spam, tag photos, and shop. It also helps when patterns shift, since you can retrain on fresh data instead of rewriting code.

On the other hand, if a rule is clear and fixed, like calculating a tax, plain code is simpler and easier to trust. Machine learning also struggles with little data, or with training data that doesn’t look like what comes later. Mitchell’s textbook notes that learning is most reliable when the training examples follow a distribution similar to that of future test examples. Google’s Rules of Machine Learning, written by Martin Zinkevich, even opens with this rule: don’t be afraid to launch a product without machine learning. Machine learning requires data, it explains, and if machine learning would give you a 100% boost, a heuristic will get you 50% of the way there. Our one-line rule at 0.888 is a small taste of that, though the same guide also advises moving to machine learning once a heuristic grows complex.

Where to start

To try it yourself, install scikit-learn with pip install -U scikit-learn as its installation guide shows, and run the two blocks above in order. Then try changing random_state or adding max_depth=3 to the tree, and watch the scores move. For a more structured path, Google’s Machine Learning Crash Course covers linear regression, classification, and overfitting with hands-on exercises.

The next post in this series looks at deep learning, where neural networks with many layers learn their own features from raw data. I ran the examples here on October 27, 2026 with Python 3.13.12, scikit-learn 1.9.1, and pandas 3.1.0.

AI tools helped with the research for this post.