Two Ways to Sort Flowers
The iris dataset, included with scikit-learn, describes 150 iris flowers from three species: setosa, versicolor and virginica, 50 of each. For every flower it records four measurements in centimetres: sepal length, sepal width, petal length and petal width. The task is to name a flower's species from its four measurements.
You could solve this the traditional way: look at the measurements, notice a pattern and write a rule. Or you could give the labelled flowers to a learning algorithm and let it derive the rules. This lesson does both on the same flowers, so you can see what "learning from data" actually produces and when it is worth using.
A Rule Written by a Person
Setosa flowers have much shorter petals than the other two species. A person who noticed this could write:
If the petal is shorter than 2.5 cm, it is a setosa; otherwise, call it a versicolor.
That rule is easy to understand and check, but it cannot be right about virginica flowers, because it never predicts virginica. Improving it means studying the measurements again and adding more conditions by hand.
Rules Learned From Examples
A decision tree is a model made of yes-or-no questions about the features, such as "is the petal width at most 0.8 cm?". Training a decision tree means letting an algorithm choose the questions: at each step it picks the feature and threshold that best separate the labelled examples it was given. Once trained, the tree classifies a new flower by answering its questions from the top down until it reaches an answer.
In scikit-learn, every model is trained the same way: you create it, call
fit with the training samples and their labels, and then call predict on
new samples. You will meet that pattern in almost every exercise from here on.
Testing Both Fairly
To compare the rule and the tree, both must be judged on flowers that the tree
did not learn from. Otherwise the tree could simply memorise its examples. The
script below sets aside a quarter of the flowers, 38 of them, before training,
with one line using train_test_split. The lesson on splitting training and
test data explains that line fully; for now, it is enough to know that the
tree learns from 112 flowers and both methods are scored on the other 38.

Follow each column from top to bottom. The only difference is where the rules come from: a person's study of the data on the left, an algorithm's search through labelled examples on the right. The bottom row is shared, because both must be judged on the same held-back flowers.
Exercise: Rule or Model
Starting state: the course environment from the setup lesson, active in your terminal. The iris data ships with scikit-learn, so nothing is downloaded.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/rule-or-model cd ~/ai-practice/rule-or-modelWindows PowerShell:
mkdir $HOME\ai-practice\rule-or-model cd $HOME\ai-practice\rule-or-modelSave this as
rule_or_model.pyin that folder:"""Compare a hand-written rule with a decision tree learned from the same flowers.""" from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, export_text iris = load_iris() X, y = iris.data, iris.target # 150 flowers, 4 measurements each, 3 species print("Species:", ", ".join(iris.target_names)) # Hold back some flowers for checking; the split lesson explains this line. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y) def rule(flower): petal_length = flower[2] # measurements: sepal length, sepal width, petal length, petal width if petal_length < 2.5: return 0 # setosa return 1 # versicolor, for now rule_correct = sum(rule(flower) == species for flower, species in zip(X_test, y_test)) print(f"Rule: {rule_correct} of {len(y_test)} correct") tree = DecisionTreeClassifier(max_depth=2, random_state=0) tree.fit(X_train, y_train) tree_correct = (tree.predict(X_test) == y_test).sum() print(f"Tree: {tree_correct} of {len(y_test)} correct") print(export_text(tree, feature_names=iris.feature_names)) -
Predict how many of the 38 held-back flowers the rule will classify correctly, given that it never predicts virginica. Then run the script:
python rule_or_model.pyOutput:
Species: setosa, versicolor, virginica Rule: 26 of 38 correct Tree: 36 of 38 correct |--- petal width (cm) <= 0.80 | |--- class: 0 |--- petal width (cm) > 0.80 | |--- petal width (cm) <= 1.75 | | |--- class: 1 | |--- petal width (cm) > 1.75 | | |--- class: 2The held-back flowers include 12 or 13 of each species. The rule gets the setosa and versicolor flowers right and every virginica wrong: 26 of 38. The tree gets 36 right.
How the Script Works
load_iris() returns the dataset. iris.data holds the measurements as a
table of numbers, 150 rows by 4 columns, and iris.target holds each flower's
label as a number: 0 for setosa, 1 for versicolor, 2 for virginica.
iris.target_names gives the names in that order.
train_test_split divides the flowers into training and test parts.
random_state=0 makes the division the same every time you run the script,
and stratify=y keeps the three species in equal proportions in both parts.
The rule function receives one flower's four measurements. flower[2] is
the third measurement, petal length, because Python counts from 0. The line
that computes rule_correct applies the rule to each test flower and adds up
the cases where its answer equals the real species; Python counts each True
as 1.
DecisionTreeClassifier(max_depth=2) creates a tree allowed at most two
levels of questions, and random_state=0 keeps its training repeatable.
fit(X_train, y_train) trains it on the 112 training flowers only.
tree.predict(X_test) gives a species for each test flower, comparing that
with y_test gives True or False for each, and .sum() counts the
True values. Finally, export_text prints the questions the tree learned.
Notice what the tree chose: petal width, not petal length, with
thresholds of 0.80 cm and 1.75 cm. Nobody told it which measurement to use.
If you change max_depth=2 to max_depth=1, the tree can ask only one
question, so it can separate setosa from the rest but must give the same
answer for versicolor and virginica, and its score drops.
Success: the script prints the rule's and the tree's scores on the same 38 flowers, and the tree's learned questions. You can explain why the rule cannot exceed 26 and where the tree's rules came from.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
ModuleNotFoundError: No module named 'sklearn' | The course environment is not active | Activate it and rerun |
Different counts, such as Rule: 25 of 38 | random_state=0 or stratify=y was changed or left out, so a different set of flowers was held back | Restore the line exactly as shown |
IndentationError | Indentation was lost while pasting | Paste the script again with its indentation |
NameError: name 'rule' is not defined | The def rule block was not pasted | Paste the whole script again |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf rule-or-model lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse rule-or-model lsCheck that the first
lsshowsrule-or-modelbefore removing it. Do the independent task first.
When Machine Learning Is the Right Tool
The iris flowers separate cleanly, so a careful person can write a good rule, as the independent task shows. Learning from data earns its place when:
- the pattern is too complicated to write down, for example when the features are 64 pixel values of a handwritten digit;
- there are many labelled examples, but few people who could state the rules;
- the patterns change over time, and retraining on new examples is easier than rewriting rules.
It is the wrong tool, or at least not the first tool, when:
- an exact rule already exists, such as a tax calculation or a unit conversion;
- there are no labelled examples, or too few to learn from;
- there is no real pattern to find, such as fair lottery numbers;
- a mistake would be serious and there is no way to check the model's answers before acting on them.
Independent task: improve the hand-written rule so that it also predicts virginica, by adding one more condition on petal length. Choose the threshold by thinking about the species' petal sizes, run the script again and compare the rule's score with the tree's.
Check Your Understanding
For each problem, choose fixed rules, machine learning or neither, and give a reason:
- Calculating the sales tax on a purchase.
- Flagging likely fraudulent card payments, using two years of payments labelled fraud or not fraud.
- Predicting next week's winning lottery numbers.
- Converting temperatures from Celsius to Fahrenheit.
- Sending support emails to the right department, using 20,000 past emails already sorted by staff.
- Deciding who should receive a new medical treatment, when no outcomes from the treatment have been recorded yet.
Answer and Reasoning
Independent task
Replace the line return 1 # versicolor, for now with:
if petal_length < 4.8:
return 1 # versicolor
return 2 # virginica
With 4.8 cm as the threshold, the rule classifies all 38 test flowers correctly here, slightly better than the tree's 36. That does not make hand-written rules better in general. Iris is a small, cleanly separated dataset, and you chose 4.8 after reading about the species, so the rule benefits from your knowledge of these very flowers. With 5.0 cm instead, one test flower is misclassified; try it. The split lesson explains why a score measured on flowers that influenced your choices is optimistic.
Understanding check
- Fixed rules: the tax rate and calculation are exact and known.
- Machine learning: many labelled examples, and fraud patterns are complex and change over time.
- Neither: fair lottery draws have no pattern for any method to learn.
- Fixed rules: an exact formula exists.
- Machine learning: plenty of labelled examples, and the wording that marks each department is hard to list by hand.
- Neither, as stated: there are no labelled outcomes to learn from, and the decision is serious. It needs medical evidence and expert judgement; a model could only help later, once outcomes have been recorded and checked.