Train Your First AI: Flower Classifier

Train a Decision Tree model to classify iris flowers by measurements.

Introduction

30 Second Summary

When you ask a voice assistant to identify a song, or when your email automatically filters spam, there's a machine learning model behind the scenes making predictions based on patterns it learned from data.

In this project, you will build a Python script that teaches a computer to identify flower species from real measurements, training your very first machine learning model from scratch.

What You'll Build

A Python script that loads 150 real iris flower measurements, trains a Decision Tree model to recognize patterns, and produces a visual diagram showing exactly how the model makes its predictions.

By the end of this project, you'll have:

  • A working machine learning model that predicts flower species with high accuracy.
  • A decision tree diagram showing the exact yes/no questions the model asks to classify each flower.
  • Firsthand experience with the train/test split, the most critical concept in ML that prevents your model from just memorizing the answers.
  • Secret Mission: Pit two different AI algorithms against each other and see which one wins.

Are there any prerequisites?

You should be comfortable with basic Python concepts like variables, lists, functions, and print statements. No machine learning experience is needed.

Set Up Your ML Environment

Before you can train a flower classifier, you need a clean workspace with the right tools installed.

In this step, you'll create a project folder, set up an isolated Python environment, and install three libraries: scikit-learn for machine learning, pandas for viewing data as tables, and matplotlib for creating visualizations.

In this step, get ready to:
  • Create a project folder and virtual environment.
  • Install scikit-learn, pandas, and matplotlib.
  • Verify everything works by running a test script.
Create a project folder and virtual environment

A virtual environment is an isolated space where you install packages without affecting the rest of your system. This keeps your project's dependencies separate from other Python projects on your machine.

  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Visual Studio Code and press Enter to open it.
  • Open the integrated terminal by pressing Ctrl+` (the backtick key, above Tab on your keyboard).

Where is the backtick key?

The backtick (`) is the key above Tab and to the left of 1 on most keyboards. If the shortcut doesn't work, click Terminal in the top menu bar, then click New Terminal.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir flower-classifier
cd flower-classifier
  • Create and activate a virtual environment by running the commands for your operating system:

macOS

python3 -m venv venv
source venv/bin/activate

Windows

python -m venv venv
venv\Scripts\activate

You should see (venv) appear at the start of your terminal prompt. This confirms the virtual environment is active.

What does (venv) mean?

The (venv) prefix tells you that any packages you install with pip will go into this isolated environment instead of your system-wide Python installation. When you close the terminal, the environment deactivates automatically.

Don't see (venv) in your prompt?

  • On Windows, make sure you ran venv\Scripts\activate with a backslash, not a forward slash.
  • On macOS, make sure you included source before the path.
  • If you see a permissions error on Windows, try running Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned in PowerShell first, then retry the activate command.

Why can't I activate my virtual environment?

Install the ML packages
  • Install scikit-learn, pandas, and matplotlib by running:
pip install scikit-learn pandas matplotlib

What does this install?

  • scikit-learn provides machine learning algorithms (like the Decision Tree you'll train).
  • pandas lets you view and manipulate data as tables (called DataFrames).
  • matplotlib creates charts and visualizations (like the decision tree diagram you'll generate).

These packages also install their own dependencies (like NumPy for math), so you'll see more than three packages being downloaded.

You should see Successfully installed messages in your terminal once everything finishes.

Seeing an installation error?

  • Make sure (venv) is showing in your prompt. If it's not, re-run the activate command from the previous substep.
  • If you see a network timeout, check your internet connection and try running the install command again.

Why is my pip install failing inside my virtual environment?

Verify everything works

Now let's open your project folder in VS Code's file explorer so you can create and edit files easily.

  • Click File in the VS Code menu bar.
  • Click Open Folder.
  • Navigate to Desktop, select the flower-classifier folder, and click Open (macOS) or Select Folder (Windows).

VS Code reloads with your project folder in the Explorer sidebar. Open a new terminal by pressing Ctrl+`.

  • Re-activate your virtual environment since the terminal session reset:

macOS

source venv/bin/activate

Windows

venv\Scripts\activate

Confirm you see (venv) in your prompt again before continuing.

  • Create a new file by clicking the New File icon at the top of the Explorer sidebar (it looks like a page with a plus sign).
  • Name the file flower_classifier.py and press Enter.
  • Paste the following test code into flower_classifier.py:
import sklearn
import pandas
import matplotlib
print(f"scikit-learn version: {sklearn.__version__}")
print(f"pandas version: {pandas.__version__}")
print(f"matplotlib version: {matplotlib.__version__}")
print("All packages installed correctly!")

What does this code do?

  • The three import lines load each library into Python so you can use it.
  • The __version__ attribute is a built-in property that every well-maintained Python package exposes. It tells you exactly which version is installed.
  • If any import fails, Python throws an error immediately, so this script doubles as a quick health check.
  • Save the file by pressing Cmd+S (macOS) or Ctrl+S (Windows).
  • Run the script by entering this command in your terminal:
python flower_classifier.py

You should see three version numbers printed followed by the message All packages installed correctly!.

Seeing a ModuleNotFoundError?

  • Check that (venv) appears in your terminal prompt. If not, re-run the activate command.
  • Make sure you ran pip install scikit-learn pandas matplotlib while the virtual environment was active.
  • On macOS, if you see command not found: python, try python3 flower_classifier.py instead.

Why am I getting a ModuleNotFoundError when running my script?

✔️ Awesome, I've got everything!

Great. Double check you've saved flower_classifier.py and move on to the next step.

ⓧ I'd like to double check the full code

Here is the complete flower_classifier.py file at this point:

import sklearn
import pandas
import matplotlib
print(f"scikit-learn version: {sklearn.__version__}")
print(f"pandas version: {pandas.__version__}")
print(f"matplotlib version: {matplotlib.__version__}")
print("All packages installed correctly!")

Your environment is ready with all the tools you need. Next up, you'll load real flower data and see exactly what the model will learn from.

Load and Explore the Flower Data

Your Python environment is set up with all the packages you need. Now it's time to meet the data your model will learn from.

Every machine learning project starts with data. In this step, you'll load 150 real flower measurements and explore their structure.

In this step, get ready to:
  • Load the Iris flower dataset from scikit-learn.
  • Convert it into a readable table using pandas.
  • Explore the shape and balance of the data.
Load the built-in Iris dataset

The Iris dataset contains 150 real flower samples with 4 measurements each and a species label. It lives inside scikit-learn so you can load it with a single function call.

  • Select all the test code in flower_classifier.py and delete it.
  • Add these imports at the top of the empty file:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
import matplotlib.pyplot as plt

What do these imports do?

  • load_iris loads the 150-flower dataset built into scikit-learn.
  • train_test_split splits data into training and testing groups (used in a later step).
  • DecisionTreeClassifier and plot_tree create and visualize the model (used in a later step).
  • accuracy_score and classification_report measure how well the model performs (used in a later step).
  • pandas (imported as pd) displays data as readable tables.
  • matplotlib.pyplot (imported as plt) generates charts and diagrams.

You won't see output yet. The next chunk uses these imports to load the flower data.

  • Below the imports, add a blank line and then paste this code to load the dataset and convert it into a pandas table:
# --- Step 2: Load and explore the data ---

iris = load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

What does this code do?

  • load_iris() fetches 150 flower samples with 4 measurements each (sepal length, sepal width, petal length, petal width) and a species label (0, 1, or 2).
  • pd.DataFrame(...) turns the raw numbers into a table (called a DataFrame) with named columns so you can read it easily.
  • df['species'] = iris.target adds the species label as a new column in the table.

You won't see output yet. The next chunk prints the data to your terminal.

  • Below the DataFrame code, add these print statements to explore the data:
print("First 5 rows of the dataset:")
print(df.head())
print()
print(f"Dataset shape: {df.shape[0]} rows, {df.shape[1]} columns")
print()
print("Samples per species:")
print(df['species'].value_counts().sort_index())
print()
print("Species labels: 0 = setosa, 1 = versicolor, 2 = virginica")
print()

What does this code do?

  • df.head() prints the first 5 rows of the table so you can see what flower data looks like.
  • df.shape tells you how many rows (flowers) and columns (measurements + species) the dataset has.
  • value_counts().sort_index() counts how many flowers belong to each species. A balanced count means the model gets equal practice on each type.
  • Save flower_classifier.py.
  • Run the script by entering this command in your terminal:
python flower_classifier.py

You should see a table of flower measurements, the dataset shape (150 rows, 5 columns), and a count showing 50 samples per species.

Seeing an error instead of the table?

  • If you see ModuleNotFoundError, your virtual environment may not be active. Check that (venv) appears at the start of your terminal prompt. If it does not, re-activate by running venv\Scripts\activate in the terminal.
  • If you see SyntaxError, double-check that you deleted all of the old test code before pasting the new imports.
  • Make sure you saved the file before running the command.

Still stuck? Help me debug why my flower_classifier.py script isn't running

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here is the complete flower_classifier.py file at this point:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
import matplotlib.pyplot as plt

# --- Step 2: Load and explore the data ---

iris = load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

print("First 5 rows of the dataset:")
print(df.head())
print()
print(f"Dataset shape: {df.shape[0]} rows, {df.shape[1]} columns")
print()
print("Samples per species:")
print(df['species'].value_counts().sort_index())
print()
print("Species labels: 0 = setosa, 1 = versicolor, 2 = virginica")
print()
Understand what you are looking at

What does the output mean?

  • Each row is one flower that was measured in real life.
  • Each column is a measurement. In ML terms, these are called "features."
  • The species column is what the model will try to predict. In ML terms, this is called the "target."
  • There are exactly 50 samples of each species (0, 1, and 2). This means the data is balanced, so the model gets equal practice on each flower type.

What are the three species?

The numbers 0, 1, and 2 map to real iris flower species: setosa, versicolor, and virginica. Each has a different combination of petal and sepal sizes that the model will learn to distinguish.

Your data is loaded and you can see exactly what the model will learn from. Next up, you'll split this data into training and testing sets, then teach a Decision Tree model to recognize the patterns.

Split the Data and Train Your Model

You have explored 150 flowers and seen what the data looks like as a table. Now it is time for the most important concept in machine learning: honest evaluation.

If you train a model and then test it on the same data it learned from, it could score perfectly by memorizing answers rather than learning patterns. To prevent this, you split the data into two groups: one for training and one for testing. In this step, you will perform that split and train your first model.

In this step, get ready to:
  • Split the 150 flowers into training (120) and testing (30) groups.
  • Train a Decision Tree model to find patterns in the training data.
  • Understand what prediction means before testing your model in the next step.
Split data into training and testing sets

The golden rule of machine learning is: never test your model on data it trained on. This is like giving a student the exact exam questions to study, then being surprised when they score 100%.

To get an honest score, you hide 20% of the flowers from the model during training. After training, you hand it those hidden flowers and see if it can identify them correctly.

  • In flower_classifier.py, scroll to the bottom of the file (below the last print() statement).
  • Add the data-splitting code by copying this below your existing code:
# --- Step 3: Split data and train the model ---

X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

print(f"Training samples: {len(X_train)}")
print(f"Testing samples: {len(X_test)}")
print()

What does this code do?

  • X = iris.data stores the 150 rows of flower measurements (the inputs).
  • y = iris.target stores the 150 species labels (the answers the model will learn to predict).
  • train_test_split shuffles the data and splits it into two groups. test_size=0.2 means 20% goes to testing (30 flowers) and 80% to training (120 flowers).
  • random_state=42 locks the shuffle so everyone gets the same split. This makes results reproducible.
  • stratify=y ensures each species is represented proportionally in both groups. Without this, you might get 25 setosa flowers in training but only 5 in testing.

Why split before training?

This split creates your honest exam. The model learns patterns from 120 flowers. Then you hand it 30 flowers it has never seen and ask it to identify them. If it still scores well, it genuinely learned patterns rather than memorizing specific flowers.

This train/test split is the foundation of every ML project, from spam filters to medical diagnosis systems.

  • Save flower_classifier.py.
  • Run the script to confirm the split by running:
python flower_classifier.py
  • You should see your existing dataset output from Step 2, followed by Training samples: 120 and Testing samples: 30.

Not seeing the sample counts?

  • Make sure your new code is at the bottom of the file, after the existing Step 2 code. It should not replace anything.
  • Check that X and y are uppercase. Python is case-sensitive.
  • Verify that iris = load_iris() still exists earlier in your file.

Still stuck? Help me debug why my train_test_split output is not printing.

Create and train the Decision Tree model

Now that your data is split, you can train the model. Training is where the actual learning happens: the model examines the 120 training flowers and builds a set of yes/no rules to distinguish between species.

  • Add the model training code below your print() statements by copying this at the bottom of the file:
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)

print("Model trained!")
print()

What does this code do?

  • DecisionTreeClassifier(random_state=42) creates a blank model. It does not know anything about flowers yet.
  • .fit(X_train, y_train) is where learning happens. The model looks at the 120 training flowers, finds patterns in their measurements, and builds a tree of yes/no questions (like "if petal length > 2.45 cm, it is probably not setosa").
  • random_state=42 ensures the tree-building process is reproducible. Without it, you might get a slightly different tree each time.

What is a Decision Tree?

A Decision Tree is a machine learning algorithm that makes predictions by asking a series of yes/no questions about the data. Think of it like a flowchart: "Is petal length greater than 2.45 cm? If yes, go right. Is petal width greater than 1.75 cm? If yes, it is virginica."

Decision Trees are one of the few ML algorithms where you can read the model's reasoning in plain language. You will visualize this tree in the next step.

  • Save flower_classifier.py and run the script again:
python flower_classifier.py
  • At the bottom of your terminal output, you should now see Training samples: 120, Testing samples: 30, and Model trained!.

Seeing a NameError?

  • If you see NameError: name 'DecisionTreeClassifier' is not defined, check that your import line at the top of the file still reads from sklearn.tree import DecisionTreeClassifier, plot_tree.
  • If you see NameError: name 'X_train' is not defined, make sure the train_test_split code from the previous substep comes before the model code.

Still stuck? Help me fix the error when training my Decision Tree model.

Understand what prediction means

Your model has learned patterns from 120 flowers. The next question is: did it actually learn, or did it just memorize?

To answer this, you use .predict() to hand the model the 30 test flowers it has never seen. The model applies its learned rules to these new measurements and guesses each flower's species. In the next step, you will run this prediction and measure how many it gets right.

Why is this the honest test?

Imagine a student who studied by memorizing every answer on a practice test. Give them that same test and they score 100%. Give them a new test with different questions on the same material, and their real understanding shows.

That is exactly what .predict() on test data does. It reveals whether the model learned generalizable patterns or just memorized training examples. This concept is called overfitting when a model memorizes instead of learning.

✔️ Awesome, I've got everything!

Great. Double check you have saved flower_classifier.py with all the new code at the bottom.

ⓧ I'd like to double check the full code

Here is the complete flower_classifier.py file so far:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
import matplotlib.pyplot as plt

# --- Step 2: Load and explore the data ---

iris = load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

print("First 5 rows of the dataset:")
print(df.head())
print()
print(f"Dataset shape: {df.shape[0]} rows, {df.shape[1]} columns")
print()
print("Samples per species:")
print(df['species'].value_counts().sort_index())
print()
print("Species labels: 0 = setosa, 1 = versicolor, 2 = virginica")
print()

# --- Step 3: Split data and train the model ---

X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

print(f"Training samples: {len(X_train)}")
print(f"Testing samples: {len(X_test)}")
print()

model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)

print("Model trained!")
print()

Your model is trained and ready to make predictions. Next up, you will put it to the test: run predictions on the 30 hidden flowers, measure its accuracy, and visualize exactly how it makes decisions.

Evaluate Your Model and See Its Thinking

Your model is trained and ready to prove itself. Right now it has a set of rules it learned from 120 flowers, but you have no idea whether those rules actually work on flowers it has never seen.

In this step, you will put the model to the test with those 30 held-out flowers, generate a visual map of its decision-making process, and feed it a completely new flower to classify.

In this step, get ready to:
  • Check your model's accuracy on unseen data and get a per-species performance report.
  • Generate a visual decision tree diagram showing how the model thinks.
  • Make a prediction on a brand-new flower the model has never encountered.
Check accuracy and get a performance report

The model learned patterns from 120 training flowers. Now you need to find out whether it can generalize those patterns to the 30 test flowers it has never seen.

  • In flower_classifier.py, scroll to the bottom of the file (after print("Model trained!")).
  • Add this code to predict on the test data and print the results:
# --- Step 4: Evaluate and visualize ---

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy * 100:.1f}%")
print()

print("Detailed performance report:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))

What does this code do?

model.predict(X_test) feeds the 30 test flowers into the model and gets its species guesses. These predictions are stored in y_pred.

accuracy_score(y_test, y_pred) compares the model's guesses against the real answers. It returns a decimal (like 0.96) that you multiply by 100 to get a percentage.

classification_report gives you a breakdown per species. Precision tells you how often the model is correct when it says "this is versicolor." Recall tells you how many of the actual versicolor flowers it found.

  • Save flower_classifier.py.
  • Run the script by running:
python flower_classifier.py
  • Scroll to the bottom of your terminal output. You should see a model accuracy percentage (likely 96% or higher) followed by a table with precision, recall, and f1-score for each species.

Seeing 0% accuracy or an error?

Make sure y_pred uses X_test (not X_train). Predicting on training data is a common mistake that gives misleadingly perfect results.

Check that target_names=iris.target_names is passed to classification_report. Without it, you will see numbers (0, 1, 2) instead of species names.

Help me debug my model accuracy code.

Why is testing on unseen data so important?

If you tested on the same data the model trained on, it could score 100% by memorizing rather than learning. That is called overfitting. Testing on held-out data gives you an honest measure of whether the model can handle new inputs in the real world.

Visualize the decision tree

A Decision Tree is special because you can literally read how it makes decisions. Each node in the tree is a yes/no question about a measurement.

  • Add this code below the classification_report line to generate and save a tree diagram:
plt.figure(figsize=(20, 10))
plot_tree(
    model,
    feature_names=iris.feature_names,
    class_names=list(iris.target_names),
    filled=True,
    rounded=True
)
plt.title("How the Model Makes Decisions")
plt.tight_layout()
plt.savefig("decision_tree.png", dpi=150, bbox_inches="tight")
plt.show()
print("Decision tree visualization saved as 'decision_tree.png'")
print()

What does this code do?

  • plt.figure(figsize=(20, 10)) creates a large canvas so the tree is readable.
  • plot_tree() draws every decision node. filled=True colors each box by its predicted class, so you can see the pattern at a glance.
  • plt.savefig() saves the image to disk as decision_tree.png. plt.show() also pops up an interactive window so you can zoom in.
  • Save flower_classifier.py and run the script again:
python flower_classifier.py
  • A matplotlib window should pop up showing a colorful tree diagram. Each box contains a yes/no question about a flower measurement. Close the window when you are done exploring.
  • Confirm decision_tree.png was saved by running:
ls
  • You should see decision_tree.png listed alongside flower_classifier.py in the output.

No window popping up?

Some environments (like remote servers or WSL) cannot display GUI windows. If the script hangs at plt.show(), close the terminal, remove the plt.show() line, and re-run. The image is still saved as decision_tree.png and you can open it directly from VS Code's file explorer.

Help me get the decision tree visualization working.

Make a prediction on brand-new data

The test set came from the original dataset. Now you will simulate what happens in production: handing the model measurements it has never encountered in any form.

  • Add this code at the bottom of flower_classifier.py to predict on a completely new flower:
# --- Make a prediction on new data ---

new_flower = [[5.1, 3.5, 1.4, 0.2]]
prediction = model.predict(new_flower)
species_name = iris.target_names[prediction[0]]
print(f"New flower measurements: {new_flower[0]}")
print(f"Predicted species: {species_name}")

What does this code do?

new_flower is a list of four measurements (sepal length, sepal width, petal length, petal width) that you made up. It is wrapped in double brackets because .predict() expects a 2D array (a table of rows), even if you only have one row.

The model runs these measurements through its decision tree and returns an integer (0, 1, or 2). You then look up the species name using iris.target_names.

  • Save flower_classifier.py and run the script one final time:
python flower_classifier.py
  • At the very bottom of your terminal output (after closing the tree window), you should see the new flower's measurements and its predicted species name printed.

Seeing a ValueError about array shape?

Make sure new_flower uses double brackets: [[5.1, 3.5, 1.4, 0.2]]. A single bracket gives the model a 1D array, but it expects a 2D array (one row with four columns).

Help me fix my prediction code.

✔️ Awesome, I've got everything!

Great. Double check you have saved flower_classifier.py and that decision_tree.png exists in your project folder.

ⓧ I'd like to double check the full code

Here is the complete flower_classifier.py file at the end of this step:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd
import matplotlib.pyplot as plt

# --- Step 2: Load and explore the data ---

iris = load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target

print("First 5 rows of the dataset:")
print(df.head())
print()
print(f"Dataset shape: {df.shape[0]} rows, {df.shape[1]} columns")
print()
print("Samples per species:")
print(df['species'].value_counts().sort_index())
print()
print("Species labels: 0 = setosa, 1 = versicolor, 2 = virginica")
print()

# --- Step 3: Split data and train the model ---

X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

print(f"Training samples: {len(X_train)}")
print(f"Testing samples: {len(X_test)}")
print()

model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)

print("Model trained!")
print()

# --- Step 4: Evaluate and visualize ---

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy * 100:.1f}%")
print()

print("Detailed performance report:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))

plt.figure(figsize=(20, 10))
plot_tree(
    model,
    feature_names=iris.feature_names,
    class_names=list(iris.target_names),
    filled=True,
    rounded=True
)
plt.title("How the Model Makes Decisions")
plt.tight_layout()
plt.savefig("decision_tree.png", dpi=150, bbox_inches="tight")
plt.show()
print("Decision tree visualization saved as 'decision_tree.png'")
print()

# --- Make a prediction on new data ---

new_flower = [[5.1, 3.5, 1.4, 0.2]]
prediction = model.predict(new_flower)
species_name = iris.target_names[prediction[0]]
print(f"New flower measurements: {new_flower[0]}")
print(f"Predicted species: {species_name}")

Secret mission

Pit Two Algorithms Against Each Other

Your Decision Tree works well, but is it the best approach? In this bonus challenge, you'll train a completely different algorithm on the same data and compare their results head-to-head. Different algorithms "think" in fundamentally different ways, and choosing the right one is a real skill in machine learning.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your resources on your machine or delete them entirely.

Resources you used:

  • flower-classifier project folder (contains your Python script, decision tree image, and virtual environment).
  • venv virtual environment with scikit-learn, pandas, and matplotlib installed.
  • decision_tree.png saved visualization image.

Keep everything running

No action needed. Choose this if you want to keep experimenting with your classifier or try new datasets.

  • Your virtual environment and code are stored locally inside the flower-classifier folder. They take minimal disk space.
  • To return to the project later, open the folder in VS Code and reactivate the virtual environment with venv\Scripts\activate (Windows) or source venv/bin/activate (macOS/Linux).

Pause - I'll come back to this later

Since everything is local and free, there is nothing to pause. Your files sit on disk until you delete them.

  • Close VS Code when you are done. Your project stays in the flower-classifier folder on your Desktop.
  • No background processes are running after you close the terminal.

Delete - I don't want to use this again

Remove all project files. You can always recreate the environment later with a fresh pip install.

  • Close VS Code if it is still open.
  • Delete the entire flower-classifier folder. This removes your script, the decision tree image, and the virtual environment (including all installed packages).

On macOS/Linux, open a terminal and run:

rm -rf ~/Desktop/flower-classifier

On Windows, open Command Prompt and run:

rmdir /s /q %USERPROFILE%\Desktop\flower-classifier

That is everything. No accounts, cloud services, or background processes need to be cleaned up.

That's a Wrap!

That's a Wrap!

Nice work! You just trained your first machine learning model from scratch and watched it accurately identify flower species from raw measurements.

You've learned how to:

  • Trained a Decision Tree model on 150 real flower measurements and made accurate predictions on brand-new data.
  • Split data into training and testing sets to honestly evaluate whether a model learned patterns or just memorized answers.
  • Generated a visual decision tree diagram showing the exact yes/no questions the model asks to classify each flower.
  • Secret Mission: Compared two different ML algorithms (Decision Tree vs K-Nearest Neighbors) on the same dataset to see which one performs better.

Ready to quiz yourself?