Sub topic 1
What Machine Learning Is
Machine learning (ML) is a way of building programs whose behavior comes from data instead of from rules a programmer wrote by hand. This chapter gives a working definition, contrasts it with rule-based programming, introduces the vocabulary used in the rest of the tutorial, and covers the mistakes people most often make at this stage.
Prerequisites
This chapter assumes you have:
- Basic programming skill, ideally in Python.
- Familiarity with arrays or tables of numbers.
- High-school algebra and the idea of a function.
- Basic descriptive statistics, such as mean and variance.
The code examples use scikit-learn. Install it with pip install scikit-learn numpy before running them.
A working definition
A classic definition, from Tom Mitchell, is that a program learns from experience E with respect to a task T and a performance measure P if its performance at T, measured by P, improves with experience E. Each part maps onto something concrete:
| Part | Meaning | Example: spam filter |
|---|---|---|
| Task (T) | What the program must do | Mark an email as spam or not spam |
| Experience (E) | The data it learns from | Thousands of emails already marked by users |
| Performance (P) | How you score it | Fraction of new emails classified correctly |
In practice, ML means choosing a family of functions, then using data to pick the member of that family that performs best on the task. The family is the model. The numbers inside the model that get adjusted are its parameters. The act of adjusting them is training, also called fitting.
You write the function's shape. The data decides its details.
Rules written by hand versus patterns learned from data
In conventional programming you supply rules and input, and the program produces answers. In ML you supply input and answers, and the training process produces the rules, stored as parameter values.
Hand-written rules work well when the logic is known, stable, and small enough to state exactly. Tax calculations and unit conversions are examples. They break down when:
- The rules are too many or too tangled to write down, as in recognizing handwriting.
- The rules are unknown even to experts, as in predicting which customers will cancel.
- The rules change over time, so a fixed rule set goes stale.
ML is not automatically better. If you can state the rule exactly, write the rule. It will be cheaper, faster, and fully explainable. Reach for ML when examples are plentiful and rules are not.
The same task both ways
The iris dataset contains 150 flowers, each with four measurements and a species. The first program uses rules chosen by a person who looked at petal length. The second learns its rules from labeled data.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
# Approach 1: rules written by hand, using petal length (column 2)
def rule_based(row):
petal_length = row[2]
if petal_length < 2.5:
return 0
if petal_length < 4.8:
return 1
return 2
rule_predictions = [rule_based(row) for row in X_test]
print("rules:", accuracy_score(y_test, rule_predictions))
# Approach 2: rules learned from labeled examples
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
print("learned:", accuracy_score(y_test, model.predict(X_test)))Both print an accuracy between 0 and 1, and on this easy dataset both score well. The difference is where the decision logic came from. In the first program the thresholds 2.5 and 4.8 came from a person's eyes. In the second, fit computed a set of weights from X_train and y_train.
The learned version needed no one to inspect the data and pick thresholds. It also uses all four measurements at once, which would be tedious to do by hand. For a problem with thousands of features, hand-written rules stop being practical, while the learning code stays the same length.
The vocabulary you need
Later chapters treat each of these in detail. These short definitions are enough for now.
- Example (also sample, instance, or row): one item the model sees, such as one flower or one email.
- Feature: a measurable property of an example, used as input. Petal length is a feature.
- Label (also target): the answer you want the model to predict, such as the species. Not every dataset has labels.
- Dataset: a collection of examples. In code, features usually form a 2-D array
Xwith one row per example and one column per feature. Labels form a 1-D arrayy. - Model: a function with adjustable parameters that maps features to a prediction.
- Training: the process of adjusting parameters so predictions match the data.
- Inference (or prediction): using a trained model on new inputs.
You can see these in the code above. X has shape (150, 4): 150 examples and 4 features. y has shape (150,): one label per example.
Two broad families
Whether the data has labels determines the main split in ML.
- Supervised learning uses examples that come with labels. The model learns a mapping from features to labels, then predicts labels for new examples. The iris classifier is supervised.
- Unsupervised learning uses examples with no labels. The model looks for structure in the features alone, such as groups of similar rows.
Other paradigms exist, including semi-supervised, self-supervised, and reinforcement learning. The remaining chapters of this tutorial cover them in order, starting with the two main families.
The central goal: generalization
ML is not about doing well on data you already have. A lookup table of the training examples would score perfectly on them. The goal is to perform well on new data drawn from the same source. This is called generalization.
That is why the model in the example was scored on X_test, which was set aside before fit was called. A score on the training data alone tells you how well the model memorized, not how well it learned. Failing to separate these two is the most common way to fool yourself in ML, and a later chapter on overfitting covers it in full.
Common errors at this stage
- Treating ML as the default. If a short, exact rule solves the problem, it beats a model. ML adds data collection, evaluation, and maintenance costs.
- Evaluating on training data. Any score computed on data the model was fitted on is optimistic. Always keep a held-out test set.
- Confusing correlation in the data with a rule of the world. A model learns whatever patterns separate the labels in your data, including accidental ones. If every sick patient in the training photos was photographed with a particular scanner, the model may learn the scanner.
- Assuming the data represents the future. A model learns from past examples. If new inputs differ from the training data, accuracy can drop without any error message.
- Mixing up a model and its algorithm. The algorithm is the procedure that does the fitting. The model is the fitted result, with specific parameter values. The same algorithm on different data produces different models.
- Expecting certainty. Predictions are estimates. A model that is right 95% of the time is wrong 5% of the time, and you need to decide whether that is acceptable for the task.
Where this chapter fits
The next chapters build on these ideas in order: features and labels in detail, the learning paradigms, supervised tasks (classification and regression), how training minimizes a loss, overfitting and evaluation, then unsupervised tasks (clustering and dimensionality reduction), and finally how to choose between approaches.
Exercises
Exercise
A team wants to convert prices from euros to dollars at a published daily exchange rate. Should they use machine learning or a hand-written rule? Give one reason.
Show answer
A hand-written rule. The logic is exact and known (multiply by the rate), so learning it from data would add cost and error without any benefit.
Exercise
In the iris example, X has shape (150, 4) and y has shape (150,). Name the examples, features, and labels, and say how many of each there are.
Show answer
There are 150 examples (the flowers, one per row of X). There are 4 features (the four measurements, one per column of X). There are 150 labels (one species per flower, stored in y).
Exercise
A model scores 99% on its training data and 70% on new data. What does this suggest, and what should you have done to find out?
Show answer
The model has memorized the training data and generalizes poorly. You should have held out a test set before training and scored the model on it. Only the held-out score estimates performance on new data.