How to Build Your First Machine Learning Model Using Python
Suppose your school science club wants to develop a program that can identify different types of iris flowers from their measured petals and sepals. You could spend weeks inventing rules for every possible flower. A more practical experiment is to provide a learning algorithm with examples of flowers whose species are already known, allow it to discover measurement patterns, then test whether its predictions hold up on flowers it has never trained on.
That is exactly what you will build in this step-by-step Python machine learning tutorial. Starting with a free dataset, you will inspect four numerical features, create training and test sets, train a small decision tree, make predictions, evaluate actual mistakes, save the trained model and safely reload your own file. We will not stop at an impressive accuracy percentage: you will learn what each command does, why the order matters and what your final model does not prove.
This is a practical continuation of our machine learning beginner’s guide and supervised versus unsupervised learning comparison. Read those introductions if you need definitions; here, we focus on completing one runnable project you can understand, modify and document.
By the end: You will have trained a classifier on the public Iris dataset, evaluated 38 held-out records, obtained a verified 89.47% test accuracy, visualized the actual decision tree and confusion matrix, and saved and reloaded a trusted local model file. The demonstration is educational, not a validated flower-identification product.
What does building a machine learning model actually mean?
A learning algorithm is the procedure that adjusts a mathematical or computational model using data. A trained model is the resulting fitted object containing the learned parameters, such as decision thresholds inside a tree. Features are input values available for a prediction, while labels are known answers used by a supervised learning algorithm. A prediction is the model’s output for a new input, and evaluation compares predictions with trustworthy reference answers.
For example, a decision-tree algorithm might learn a question about petal length that divides very short-petaled flowers from longer-petaled flowers. Its next branch could examine petal width. The program does not begin with those specific threshold values; the fitting procedure learns useful splits from labeled measurements. This is why the algorithm and its trained model are related but not interchangeable concepts.
An important limitation is that a model can identify a statistical pattern without understanding plants as a botanist does. Even when a prediction matches the observed label, it remains a prediction based on the chosen features and training examples. Our goal is to build a defensible beginner experiment, not to claim that a 150-row dataset can support consequential scientific decisions.
The project workflow: from data to saved model
A reliable sequence begins with a question and the data needed to answer it. Load and inspect the observations, separate your training and held-out evaluation samples, fit an appropriate model, predict withheld outcomes and interpret mistakes. Only then should you compare possible improvements using an independent development method. Finally, save the trained object, record the software environment and check that your own trusted saved file produces the same predictions when loaded.

That sequence guards against data leakage, which occurs when information unavailable during genuine prediction influences a model or its evaluation. For example, adjusting a model repeatedly after seeing a supposedly final test score means the test set is no longer a fully independent check. In this tutorial we use the designated test set to report one completed example and illustrate train-only cross-validation separately.
Your tools and preparation
You need beginner Python skills such as running cells, assigning variables, importing a library and reading tabular output. NumPy represents numerical arrays; Pandas helps inspect a dataset; Matplotlib generates the genuine charts; scikit-learn provides the built-in Iris data, the decision-tree algorithm, splitting utilities and evaluation functions; and joblib can save a fitted model for controlled local reuse.
A compatible computer with Python and a notebook or terminal is sufficient. Alternatively, Google Colab runs Python in a browser, subject to an internet connection and its current usage limits. The Notes for SHS Google Colab tutorial and Jupyter Notebook tutorial explain these environments in more depth. You can complete the exercises without buying cloud computation or collecting any personal information.
Step 1 — Set up Python and the required packages
First open a local terminal or create a Python notebook. If the libraries are not installed, run the following in the relevant environment. On some systems the executable is named python3. A notebook may use a different interpreter from your system terminal, so always confirm which environment your code actually runs in.
python -m pip install numpy pandas matplotlib scikit-learn joblib
The Python and scikit-learn ecosystem changes over time. This tutorial’s executable results were verified with Python 3.13.5, scikit-learn 1.8.0, NumPy 2.3.5, Pandas 2.2.3, Matplotlib 3.10.8 and joblib 1.5.3. The current official scikit-learn getting-started documentation provides installation and API guidance; do not assume that an arbitrary old code example will behave identically under every version.
Step 2 — Import the project libraries
import pandas as pd
import matplotlib.pyplot as plt
import joblib
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, confusion_matrix, ConfusionMatrixDisplay
Each import contributes to one stage. load_iris supplies the public dataset. train_test_split reserves records for unbiased checking. DecisionTreeClassifier trains a species predictor, while accuracy_score and confusion_matrix summarize how it performs. plot_tree and ConfusionMatrixDisplay draw real figures rather than invented diagrams. joblib stores the fitted model for a trusted local reload.
Step 3 — Load the public Iris dataset
The Iris teaching dataset contains 150 flower observations, four measurements in centimetres and a known species label for each flower. The dataset has three classes: setosa, versicolor and virginica. We will build a classification model because we want a species category, not a continuous numerical measurement. A classification problem is supervised because its species targets are already known for the training examples.
iris = load_iris()
X = iris.data
Y = iris.target
print('Feature shape:', X.shape)
print('Target shape:', Y.shape)
print('Species:', iris.target_names)
The verified shapes are (150, 4) for the inputs and (150,) for the targets. This means every row has four input measurements and one species identifier. Species are stored as numeric codes 0, 1 and 2; the readable names are available in iris.target_names. The two shapes also confirm that the dataset is small enough to explore without expensive hardware.

Step 4 — Inspect and understand the observations
Before you fit any model, examine the feature names and a few real rows. This helps you recognize the units, discover unexpected columns, and avoid accidentally training with the answer already included as a feature. A data table may appear clean but still contain misrecorded measurements or misleading sampling; descriptive statistics provide clues, not proof that data quality is perfect.
df = pd.DataFrame(X, columns=iris.feature_names)
df['species'] = [iris.target_names[i] for i in Y]
print(df.head())
print(df.dtypes)
print(df.isna().sum())
print(df.describe())
The resulting DataFrame displays sepal length, sepal width, petal length, petal width and an explanatory species column. Its first rows are setosa flowers, but the original dataset order is not a reason to train on the first 75% and test on the last 25% without consideration: doing so could make training and evaluation classes unrepresentative. The built-in measurements do not contain missing numerical values in this verified copy.
Notice that the species column is created for inspection only. Our actual X array still contains only the four numerical measurements. Keeping the species target out of the input features is essential: including it would be a form of target leakage and could create unrealistically impressive results.
Step 5 — Choose your features and target
The feature array X answers ‘What do I know about each flower before prediction?’ The target array Y answers ‘What is the known species of each flower?’ We deliberately use all four standard measurements to avoid an arbitrary feature-selection decision before understanding the task. Later projects can study whether fewer measurements would be sufficient, using training-only validation rather than changing features to maximize a final test score.
Features and labels are not always this straightforward. In a weather project, rainfall may be the target while pressure and earlier observations are features. In document classification, the original text may be transformed into a numerical representation. Whatever the domain, make the prediction-time information boundary explicit so that training does not depend on data that would only be known after the event.
Step 6 — Split into training and test datasets
X_train, X_test, y_train, y_test = train_test_split(
X, Y, test_size=0.25, random_state=42, stratify=Y
)
print('Training:', X_train.shape, y_train.shape)
print('Testing:', X_test.shape, y_test.shape)
This method creates 112 training observations and 38 test observations. The test_size=0.25 argument requests approximately 25% of the 150 rows for testing, rounded here to 38. The random_state=42 argument fixes the random sampling to reproduce the same educational split. stratify=Y keeps approximately equal species proportions in both sets, which is helpful for this balanced multiclass problem.

Training and test variables must remain paired correctly. X_train contains the training measurements and y_train their known species labels; X_test and y_test form the held-out evaluation pair. If several rows came from the same patient, person or device, or were ordered through time, you might need a group-aware or time-aware split instead. A random split is appropriate for this simple Iris illustration, not for every dataset.
Step 7 — Choose an understandable classifier
A decision tree learns a sequence of questions about the input values. Each decision node tests a condition such as whether a petal width is below a threshold. Following the yes-or-no branches eventually reaches a leaf node, which contains a predicted class based on the training examples reaching that leaf. The tree’s actual threshold values are learned during fitting, not manually entered by us.

Decision trees are helpful for newcomers because their questions can be visualized and discussed. They also have limitations: small changes in training data may change branches, and a highly flexible tree can memorize details rather than generalize. For this exercise, a maximum depth of three gives a modest-sized diagram. That is a teaching choice rather than proof that depth three is always the best model.
Step 8 — Create and train the model
model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)
print('Training accuracy:', round(model.score(X_train, y_train), 4))
Creating the object specifies an algorithm and its settings, known as hyperparameters. Calling fit() learns split rules from the 112 training rows and their species labels. The training accuracy in this verified example is 0.9643, or about 96.43%. This describes how well the model classifies examples it was allowed to learn from; it is not the final measure of how well the system handles unfamiliar flowers.
Changing max_depth controls the number of decision levels the algorithm may build. Larger is not always better. A model that performs almost perfectly on training data may still make mistakes on held-out observations. To assess generalization, we must make predictions on the test set and compare them with its unseen labels.
Step 9 — Make predictions on the held-out flowers
predictions = model.predict(X_test)
print('First 10 numeric predictions:', predictions[:10])
print('First 10 species names:', [iris.target_names[i] for i in predictions[:10]])
The verified first ten predicted numeric labels are [0, 1, 1, 1, 0, 1, 1, 2, 2, 2]. The corresponding readable classes are setosa, versicolor, versicolor, versicolor, setosa, versicolor, versicolor, virginica, virginica and virginica. Your program is not merely printing stored species labels; the values come from the fitted tree’s learned rules applied to measurements in X_test.
There is a crucial difference between making a prediction and verifying its correctness. The model cannot know the actual species from the input features alone; that is why the separate y_test array matters. We compare predicted labels against those held-out answers only after training. If you later feed your own flower measurement, check that the four feature values appear in the same order and use the same centimetre units.
Step 10 — Calculate and interpret the classification accuracy
accuracy = accuracy_score(y_test, predictions)
correct = (predictions == y_test).sum()
print('Correct predictions:', correct, 'of', len(y_test))
print('Test accuracy:', round(accuracy, 4))
This executed code produced 34 correct predictions out of 38, giving an accuracy of 0.8947 (89.47%). The formula is simply correct classifications divided by total tested classifications: 34 ÷ 38 ≈ 0.894736. If a different split or algorithm setting is used, the actual result may change. Never copy the printed figure from this tutorial and report it as though your modified experiment necessarily produced the same output.
An accuracy figure is useful, but incomplete. It does not reveal which classes are misclassified, whether some groups are substantially more affected than others, or whether the dataset represents all conditions in which a model might be used. For example, a hypothetical 95% accuracy on a highly imbalanced problem could conceal a model that misses every rare positive case. Classification tasks may require precision, recall and specific error-cost analysis.
Step 11 — Use a confusion matrix to find mistakes
matrix = confusion_matrix(y_test, predictions)
print(matrix)
ConfusionMatrixDisplay(matrix, display_labels=iris.target_names).plot(
cmap='Greens', colorbar=False
)
plt.title('Held-out Iris flower predictions')
plt.show()
| Actual species | Predicted setosa | Predicted versicolor | Predicted virginica |
|---|---|---|---|
| Setosa | 12 | 0 | 0 |
| Versicolor | 0 | 12 | 1 |
| Virginica | 0 | 3 | 10 |

Read rows as the actual species and columns as the model’s predicted species. The diagonal entries are correct predictions, adding to 12 + 12 + 10 = 34. The off-diagonal entries reveal four errors: one actual versicolor was called virginica, and three actual virginica flowers were called versicolor. Setosa was perfectly recognized among the twelve held-out setosa flowers in this particular split.
That last fact does not guarantee perfect setosa classification in every environment. Small datasets can give unstable estimates, and real observations may include new conditions or species missing from training. More reliable research may require repeated validation, independent data collection and evaluation on settings unlike the original teaching dataset. The confusion matrix is an important way to ask better questions, not a certificate of universal reliability.
Step 12 — Visualize the trained decision tree
plt.figure(figsize=(16, 7))
plot_tree(model, feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True, fontsize=9)
plt.title('Our trained Iris decision tree')
plt.show()

The top decision in this fitted tree checks petal length. Each internal node shows a comparison threshold; its branches lead to later questions or terminal leaf predictions. The printed samples value tells you how many training observations reached a node, and the value entries summarize class frequencies at that node. The model selects thresholds to separate classes according to its splitting criterion; these thresholds are not rules that a botanist necessarily endorses.
Visualizing the tree makes model complexity tangible. Some leaves contain mixed species, which helps explain why the final classifier cannot always distinguish versicolor from virginica. Although tree diagrams are interpretable compared with many models, they still require caution: the learned rules depend on the dataset, label quality and training procedure.
Step 13 — Recognize overfitting and underfitting
Overfitting occurs when the model learns training-specific details or noise that do not transfer well to new examples. Underfitting occurs when a model or its features are too limited to capture an important relationship. A model that scores well on its training rows but substantially worse on independent rows raises questions about generalization; a model that performs poorly on both sets may be too simple or poorly matched to the data.
For this run, training accuracy is about 96.43%, compared with the held-out test accuracy of 89.47%. That gap is worth reporting, but on a small dataset and one split it does not by itself establish severe overfitting. We should avoid declaring a particular amount of difference ‘good’ or ‘bad’ without considering dataset size, class proportions, model stability and the consequences of errors.
A decision tree with unlimited depth may memorize more local exceptions, and a tree forced to depth one may fail to represent meaningful distinctions. Complexity controls such as max_depth and min_samples_leaf can help regulate flexibility. However, the setting should be chosen on development evidence, not by repeatedly inspecting the supposedly final test set.
Step 14 — Improve the model without misusing the test set
One responsible way to compare tree depths is cross-validation using only the training observations. In five-fold cross-validation, training data are divided into five parts. Each fold serves temporarily as validation data while the model is fitted on the remaining training folds. The scores can be summarized for different settings. Only after the model choice is fixed should the final untouched test set be consulted for a last estimate.
from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for depth in [1, 2, 3, 4, 5]:
candidate = DecisionTreeClassifier(max_depth=depth, random_state=42)
scores = cross_val_score(candidate, X_train, y_train, cv=cv)
print(depth, round(scores.mean(), 4))
Using the verified training subset and code, the mean five-fold cross-validation scores were approximately 65.18%, 92.89%, 95.53%, 93.75% and 94.66% for depths one through five respectively. These are development-stage scores, not independent final test results for every candidate. With different folds or versions, results may differ. The exercise shows that adding complexity does not always improve performance.

For a stronger project, also examine data quality, alternative algorithms, uncertainty across validation folds, different feature sets and task-appropriate metrics. If you decide to select a different model based on the cross-validation exercise, retrain it on all allowed training data and report its result on a genuinely untouched test set. Since we already used this tutorial’s test set to demonstrate a specific depth-three tree, the cleanest independent comparison would use a fresh held-out evaluation dataset rather than pretending we had not examined the original test score.
Step 15 — Save the trained decision tree
Training a model produces an in-memory Python object. If you close the notebook, that object disappears unless you save it. Model persistence stores the fitted object so you can reuse the same trained rules later without repeating the fitting step. For this simple local demonstration, the joblib library can serialize the trained scikit-learn tree into a file, including its learned thresholds and classes.
from pathlib import Path
import joblib
output_dir = Path('models')
output_dir.mkdir(exist_ok=True)
model_path = output_dir / 'iris_classifier.joblib'
joblib.dump(model, model_path)
print('Saved:', model_path)
Keep the saved model together with source code, a list of dependencies, the date of training, the dataset description, feature order and a record of evaluation. Be aware that model files created using one version of scikit-learn may not be reliably loadable under a different version: the official persistence guidance describes these compatibility issues. A saved model is not self-documenting, and it should never be treated as a substitute for reproducible training code.
Security warning: joblib.load() is based on Python’s pickle serialization and can execute malicious code when opening an untrusted file. Only reload a model you created yourself in a trusted environment, or a file whose provenance you have independently verified. Do not download unknown model files and load them simply because they claim to be useful. scikit-learn model persistence documentation explains alternatives and tradeoffs.
Step 16 — Reload your own trusted model and predict again
trusted_model = joblib.load(model_path) # only the file just created
assert (trusted_model.predict(X_test) == predictions).all()
new_flower = [[5.1, 3.5, 1.4, 0.2]] # illustrative cm values
species_id = int(trusted_model.predict(new_flower)[0])
print('Predicted species:', iris.target_names[species_id])
The saved-and-reloaded model produced the same predictions as the in-memory tree on the original held-out examples, confirming that local persistence worked in the tested environment. For the illustrative observation [5.1, 3.5, 1.4, 0.2], the saved classifier predicted setosa. These numbers are deliberately presented as an illustrative flower with input features in the original order: sepal length, sepal width, petal length and petal width, all in centimetres.
If you swap the order of measurements, change units or preprocess future data inconsistently, the model’s output may be meaningless even though Python runs without an error. In advanced systems, feature names, preprocessing transformations and data schema should be bundled or strictly validated. We have not established that this educational model is safe for any deployment, especially not applications involving healthcare, student records or automated decisions about people.

Step 17 — Organize the model files like a small research project
first-machine-learning-model/
README.md
iris_machine_learning_model.py
first-machine-learning-model-python.ipynb
models/
iris_classifier.joblib
model_metadata.json
outputs/
confusion_matrix.png
trained_decision_tree.png
A clean folder makes your investigation reproducible by someone else. Put the script and notebook beside an explanation of the environment in README.md. Place saved trained artifacts in models and charts in outputs. The accompanying learning package uses these ideas and includes verified output graphics, source code, dependencies and a trusted local model file. Do not add private student datasets or unnecessary credentials to the project folder.
Step 18 — Write a useful project findings report
A good findings report states the research question, the dataset and its provenance, number of rows and features, selected algorithm, train/test procedure, code version, test accuracy, error distribution, project limitations and what you would investigate next. Do not claim that one holdout score describes all possible conditions or that the model ‘understands’ flowers. Educational honesty makes your work more valuable.
Sample findings: We trained a depth-three decision-tree classifier using four measurements from the public 150-observation Iris dataset. A stratified 75/25 split produced 112 training flowers and 38 test flowers. On the held-out test set, the model correctly classified 34 of 38 observations (approximately 89.47%). Its confusion matrix showed one versicolor predicted as virginica and three virginica predicted as versicolor. The fitted tree was saved with joblib and successfully reloaded locally. Because the dataset is small and structured, these results are an introductory demonstration rather than evidence of robust real-world performance.
Where can a basic classification workflow be useful?
The general workflow—define a target, inspect permitted measurements, train on labeled examples, test independently and report errors—can be adapted to educational investigations in biology, environmental monitoring, document categorization and scientific research. For instance, a properly collected dataset could help study categories in plant observations or distinguish document topics using suitably represented text features. Different domains need different data collection and evaluation methods; this particular Iris classifier accepts four measured lengths, not photos or arbitrary text.
Real applications are substantially more demanding than a classroom model. Medical research and high-stakes decisions require carefully governed data, strong external validation, fairness assessments, transparent oversight and appropriate professionals. A model trained on 150 easy-to-observe flowers is not evidence that the same workflow could safely diagnose diseases or determine student opportunities without those additional safeguards.
Common mistakes and responsible machine learning
- Testing on training rows: Reserve an appropriate test set before fitting a classifier.
- Leaking known labels into features: Keep the species target out of the four input measurements.
- Using the wrong metric: Accuracy is a classification metric; use numerical error metrics for regression.
- Memorizing training data: Compare development evidence with genuinely held-out behavior.
- Ignoring class-specific errors: Read the confusion matrix rather than citing only 89.47%.
- Changing the feature order: Use sepal length, sepal width, petal length, petal width in the same units at inference.
- Tuning on final test performance: Use training-only cross-validation for model selection.
- Trusting arbitrary serialized files: Unknown joblib or pickle files may execute code when loaded.
- Omitting dependency versions: Record the training environment, data provenance and feature schema.
- Overclaiming results: A successful small demonstration does not prove real-world reliability.
Responsible practice also includes avoiding the collection of classmates’ private records for homework, checking whether data represent the population of interest, and documenting uncertainty. An apparently accurate classifier could still be biased or unsuitable for its proposed application. Students should develop the habit of explaining both what their experiment found and where its evidence ends.
Ten student practice activities with explained answers
Try each activity before expanding its answer. The questions refer to the executed example, so you can verify calculations directly against the notebook and diagrams rather than guessing.
1. Identify the Iris features and label.
The four features are sepal length, sepal width, petal length and petal width, each measured in centimetres. The target is the known species category.
2. What do X.shape = (150, 4) and Y.shape = (150,) mean?
There are 150 flower observations, four input measurements per flower and one known species label per observation.
3. Why are there 112 training rows and 38 test rows?
A requested 25% test split of 150 rows yields 38 held-out rows and 112 for training. The independent test set is for evaluation.
4. How many predictions were correct, and what percentage is that?
34 out of 38 were correct. Accuracy = 34 ÷ 38 × 100 = approximately 89.47%.
5. Which class confusion appears most often?
Three actual virginica test flowers were predicted as versicolor. One versicolor flower was predicted as virginica.
6. Why is max_depth=3 not necessarily optimal for other datasets?
The best complexity depends on data structure, sample size and evaluation design; extra splits can overfit training-specific details.
7. Compare training accuracy with test accuracy.
The model reached about 96.43% on training records and 89.47% on held-out test records. This gap merits investigation but does not by itself prove severe overfitting.
8. Explain how to compare tree depths while protecting test independence.
Use stratified cross-validation within training data to compare candidate depths. Save the final independent test set for the finished model.
9. How can you verify a model was saved and reloaded correctly?
Save your own trained model, load only that trusted local file in a compatible environment, and assert the reloaded model reproduces the original predictions.
10. Write a one-sentence research conclusion with a limitation.
A depth-three decision tree classified 34 of 38 held-out Iris flowers correctly, but one small split on a structured teaching dataset does not demonstrate universal reliability.
A flexible four-week Python machine learning roadmap
| Week | Objective | Practical result |
|---|---|---|
| 1 | Python and Iris dataset | Run notebook cells, identify all four features and inspect the 150-row table. |
| 2 | Model training and prediction | Split the dataset, fit a depth-three decision tree and identify predicted species names. |
| 3 | Evaluation and improvement | Read confusion matrix errors; compare depths with training-only cross-validation. |
| 4 | Model persistence and reporting | Safely save and reload your own model; write a reproducible README and project conclusion. |
This schedule is a guide, not a deadline. If your Python foundation is developing, revisit the Python for Data Science Beginners guide or practise reading tables before advancing. Learning to explain one model’s data, settings and errors is a stronger foundation than rapidly copying many unrelated algorithms.
Download the beginner project worksheet and answer guide
You can practise away from the computer using the Topic 56 student worksheet (PDF) and the separate explained answer guide (PDF). Both resources have been created and uploaded to the Notes for SHS media library. The complete project code is also displayed in this article and has been executed in the accompanying notebook.
The original executable notebook, Python script, model and complete project ZIP exist as companion files but are supplied separately with the publication report because the currently available WordPress media upload route does not accept all those file types. Do not follow any invented WordPress download links for them. The saved joblib artifact is an educational local file and must only be loaded if you trust its provenance; it is safest to run the script and create your own fresh model file.
Optional Coursera and Udemy learning recommendations
These are optional learning resources after you complete the free Iris project. Disclosure: the pages below are verified official course destinations, but an approved affiliate tracking URL was not available for verification. They are presented as ordinary links rather than claimed affiliate-tracked advertisements. Prices, enrollment conditions and access may change.

Supervised Machine Learning: Regression and Classification
Coursera — Introductory supervised modeling with Python and scikit-learn, including regression and classification.

Python for Data Science and Machine Learning Bootcamp
Udemy — Broader Python, data analysis, visualization and machine learning practice.
Frequently asked questions
Can a beginner really build a machine learning model?
Yes. Basic Python skills plus a small, suitable public dataset and a well-documented scikit-learn tutorial are sufficient to complete an educational first project.
Which Python libraries are required?
The tutorial uses scikit-learn for the model, Pandas for inspection, Matplotlib for charts and joblib for local persistence; NumPy supports numerical data.
Which model is simplest for a first classification project?
A small decision tree is easy to train and visualize. It is not universally the most accurate or appropriate algorithm.
What does scikit-learn do?
It supplies Python utilities for datasets, preprocessing, training algorithms, evaluation and model selection.
Why do we use separate training and test data?
A held-out set estimates behavior on examples the model was not allowed to learn from, reducing the risk of reporting memorized performance.
How do I evaluate a classifier?
Start with predictions on held-out records, compare with known labels, calculate accuracy and inspect the confusion matrix for class-specific mistakes.
What is a confusion matrix?
A table with actual categories as rows and predicted categories as columns, showing both correct classifications and which labels are confused.
Why can a decision tree overfit?
An overly complex tree may fit small training-specific details or noise that do not transfer to new data.
How can I safely save and load my model?
Save your own fitted object with joblib and reload only the file you created in a trusted environment with compatible package versions. Unknown joblib files can run malicious code.
What should I study after this project?
Explore training-only cross-validation, data preprocessing pipelines, model calibration, precision and recall, other classifiers and responsible model development.
Related reading and official technical references
This practical tutorial follows our Machine Learning for High School Students guide and Supervised vs. Unsupervised Learning. Review Python for Data Science Beginners, Pandas for Data Analysis, Jupyter Notebook for Data Science or Your First Data Science Project for related skills. These are confirmed WordPress posts on the staging site.
Official documentation consulted: scikit-learn Getting Started, Common Pitfalls, Model Evaluation, Model Persistence, DecisionTreeClassifier, plot_tree and the Python documentation.
Conclusion: build, evaluate and understand your first model
You have now followed a complete machine learning process: form a clear species-prediction question, load and inspect a suitable dataset, separate inputs and targets, reserve an appropriate test set, fit a decision tree, make predictions, visualize errors, compare model complexity on training-only folds, and save and safely reload the trained object. The working example achieved 34 correct predictions out of 38 held-out flower observations; the confusion matrix revealed exactly where four mistakes occurred.
The most important achievement is not an 89.47% score by itself. It is the ability to reproduce the result, understand the feature schema, explain the validation design and document what remains uncertain. Practise changing one aspect of the project at a time, keep test-set independence in mind, use only appropriate public or permissioned data, and never treat an unverified model as suitable for high-stakes decisions. With these habits, you are ready to investigate more advanced Python machine learning projects.
2 responses to “How to Build Your First Machine Learning Model Using Python”