AI + Python · Grade 10 · Chapter 10
Building a Simple AI Model
Using everything from this year — Python, data, logic — to build and understand your first rule-based and trained classifier.
Learning objectives
What We'll Cover
- Connect Python knowledge (Ch. 5–9) to AI model building
- Understand what a "model" actually is
- Build a rule-based classifier in pure Python
- Understand supervised learning: training data, features, labels
- Run a real ML model using scikit-learn (conceptually)
- Evaluate a model with accuracy, precision, recall
- Reflect on the full journey: from variables to AI
Connecting the dots
This Is What It Was All Leading To
Every Python chapter this year was a stepping stone:
Ch5Variables & input
Ch6Data types
Ch7Conditionals
Ch8Loops
Ch9Functions
Ch10AI Model 🤖
AI is not magic — it is these concepts, used at scale, with data.
What is a model?
A Model Is a Function
At its simplest, every AI model is a function: it takes input, does some processing, and returns an output.
# A "model" in its most basic form
def model(input_features):
# Processing (learned from data or hand-coded)
return prediction
The difference: A rule-based model's processing is hand-coded logic. A trained model's processing is learned from data. Both are functions.
Rule-based vs. learned
Two Approaches to "Intelligence"
Rule-Based Model
Humans write the rules.
if temperature < 0: classify("freezing")
✅ Transparent, explainable
❌ Breaks on edge cases humans didn't anticipate
Machine Learning Model
Algorithm finds rules from data.
Feed 10,000 examples → model learns patterns → can handle unseen inputs
✅ Handles complexity, scales
❌ Black box, requires lots of data
Build it · 1
A Rule-Based Spam Classifier
Our first "AI model": a spam detector using conditional logic.
def is_spam(message):
spam_keywords = ["win", "free", "click here", "guaranteed"]
message_lower = message.lower()
for word in spam_keywords:
if word in message_lower:
return True # spam!
return False # not spam
print(is_spam("You've won a FREE iPhone!")) # True
print(is_spam("Hi, how are you?")) # False
Testing the model
Can We Break the Spam Classifier?
Class challenge: The class tries to break the model. Can you write a spam message that isn't detected? Can you write a legitimate message that gets flagged as spam (false positive)?
- Test: "Congratulations, you've been selected!" → spam or not?
- Test: "I will give you this for FREE" → ?
- Test: "Click here to see my portfolio" → ?
- Test: "We guarantee quality results in your project" → ?
Key lesson: Rule-based models are brittle. The word "free" in a legit email is a false positive. This is exactly why we need machine learning.
Quick check · 1
What is a "false positive" in a classifier?
AA spam email that was correctly caught
BA legitimate item incorrectly classified as spam
CA spam email that slipped through the filter
DThe model predicting "True" for everything
Click to reveal answer
Supervised learning
What Is Supervised Learning?
In supervised learning, we train a model by showing it many examples that already have the correct answer (the label).
1Collect labelled data
Spam: 0/1
2Extract features
Word counts, length…
3Train the model
Algorithm finds patterns
4Evaluate
Test on unseen data
5Deploy
Predict on new inputs
Training data
Features and Labels
In machine learning, each training example has:
- Features: The input data the model uses to learn — measurable attributes
- Label: The correct output we want the model to predict
# Each row: [word_count, has_link, all_caps] → label
training_data = [
{"words": 8, "link": True, "caps": True, "label": "spam"},
{"words": 45, "link": False, "caps": False, "label": "legit"},
# ... 10,000 more examples
]
Training the model
What Happens During Training?
The algorithm looks for patterns: which combinations of features predict "spam"? It adjusts internal numbers (weights/parameters) to minimise errors.
Model discovers: IF caps AND link AND word_count < 15 → 92% chance spam
This is not programmed by humans — it's found by the algorithm from data patterns.
The magic: The model can find patterns humans would never think to look for — or patterns too complex to write as rules.
Build it · 2
A Scored Spam Classifier
A more sophisticated rule-based model that assigns scores — closer to how ML works.
def spam_score(message):
score = 0
m = message.lower()
if "free" in m: score += 3
if "win" in m: score += 2
if "click" in m: score += 2
if message == message.upper(): score += 3
if len(message) < 20: score += 1
return score
msg = input("Message: ")
s = spam_score(msg)
print(f"Spam score: {s} → {'SPAM' if s >= 4 else 'OK'}")
Quick check · 2
In machine learning, what is a "feature"?
AThe correct answer for a training example
BA measurable input attribute the model uses to learn patterns
CA function in the model code
DThe model's performance score
Click to reveal answer
scikit-learn
Real ML: scikit-learn in Python
Python's scikit-learn library provides ready-made ML algorithms. The interface is always: create model → fit (train) → predict.
from sklearn.tree import DecisionTreeClassifier
# Features: [word_count, has_link, has_caps]
X = [[8, 1, 1], [45, 0, 0], [10, 1, 0], [60, 0, 0]]
y = [1, 0, 1, 0] # 1=spam, 0=legit
model = DecisionTreeClassifier()
model.fit(X, y) # train
prediction = model.predict([[5, 1, 1]])
print(prediction) # [1] → spam
Demystifying AI
What the fit() Function Is Actually Doing
When you call model.fit(X, y):
- The algorithm loops through all training examples
- For a Decision Tree: it finds which feature to split on at each node to best separate spam from legit
- It builds a tree of if/elif rules — similar to what we wrote manually
- The tree is stored in the model object for future predictions
Key insight: Machine learning replaces "human writes the rules" with "algorithm discovers the rules from data". Under the hood — it's still conditionals and loops.
Evaluation
How Do We Know If a Model Is Good?
We split data into training set and test set. The model is trained on the training set, then evaluated on the test set (data it has never seen).
Accuracy
Correct predictions / total predictions
90% accuracy = 9/10 correct
Precision
Of all spam predictions, how many were actually spam?
High precision = few false positives
Recall
Of all actual spam, how many did the model catch?
High recall = few false negatives
Quick check · 3
Why do we use a separate test set instead of testing on the training data?
ATraining data is too large to test on
BA model could memorise training data but fail on new examples — the test set measures real-world performance
CTest sets are always more accurate
DTraining and test sets contain different algorithms
Click to reveal answer
Overfitting
The Overfitting Problem
A model that memorises training data instead of learning patterns performs perfectly on training data but poorly on new data.
Example: A spam filter trained on the exact 1,000 spam emails it saw. It gets 100% on those emails — but fails on any slightly different spam, because it memorised the exact words rather than the pattern.
Fix: Use more diverse training data, simpler models, or techniques like cross-validation. This is why dataset size and diversity matter enormously.
Build it · 3
Manual Train/Test Evaluation
Simulate model evaluation using our rule-based spam scorer.
test_cases = [
("WIN FREE CASH NOW CLICK", 1), # spam
("Please review attached document", 0),
("Free lunch in the cafeteria today", 0), # tricky!
("Click here to claim your prize", 1),
]
correct = 0
for message, actual_label in test_cases:
predicted = 1 if spam_score(message) >= 4 else 0
if predicted == actual_label:
correct += 1
print(f"Accuracy: {correct}/{len(test_cases)}")
Quick check · 4
A model has 100% training accuracy but only 60% test accuracy. What is this an example of?
AUnderfitting
BOverfitting
CA perfectly calibrated model
DA data collection error
Click to reveal answer
Ethical considerations
AI Models Make Decisions With Real Consequences
Medical diagnosis AI
A false negative (missed cancer) could be fatal. High recall is critical — at the cost of some false positives.
Spam filter
A false positive (important email flagged as spam) could cause a missed job offer. Balance matters.
Credit scoring
Wrong predictions deny people loans they deserve — or extend credit to people who will default.
Content moderation
False positives remove legitimate speech. False negatives allow harmful content. Both have costs.
The full picture
What You Now Know About AI
In one school year you went from "what is technology?" to understanding how AI works:
- AI is pattern recognition at scale — learned from data
- It uses the same primitives you coded this year: variables, conditions, loops, functions
- AI can be wrong — biased, brittle, overfit
- Every AI model has trade-offs: accuracy vs. fairness, precision vs. recall
- The humans who build AI are responsible for its outcomes
Quick check · 5
Which best describes what a trained ML model actually contains?
AA copy of all the training data
BLearned parameters (numbers) that encode patterns found in the training data
CA set of rules written by programmers
DThe algorithms the programmer wrote
Click to reveal answer
End of year project
Design Your Own AI Classifier
Working in pairs, design a classifier for a problem of your choice.
- Problem: What are you classifying? (spam, sentiment, disease, animal species…)
- Features: List 3–5 measurable features
- Labels: What outputs can the model produce?
- Training data: How would you collect it? How many examples?
- Risks: What could go wrong? What biases might exist?
- Code: Write a rule-based version in Python as a starting point
Looking ahead
What Grade 11 Builds On This
Neural Networks
How deep learning models learn — layers of mathematical transformations instead of trees
Algorithms & Complexity
Why some algorithms are faster than others — essential for building efficient AI systems
Databases & APIs
Where training data comes from and how AI systems connect to the rest of the world
AI Ethics in Depth
Case studies, regulations, responsible AI design — becoming a practitioner, not just a user
Exit reflection
Your AI Journey This Year
Reflect on everything from Chapter 1 to Chapter 10.
Write and share: What is the most important thing you learned this year about AI or programming? What will you do differently online or with technology because of what you now know? What do you still want to learn?
End of Grade 10
Year Summary: What You Built
- Went from "what is AI?" to building and evaluating a classifier
- Mastered Python: variables, types, conditionals, loops, functions
- Understood how real ML pipelines work: data → features → train → evaluate → deploy
- Identified AI trade-offs: false positives, false negatives, overfitting, bias
- Connected code to real-world systems: spam filters, recommendation engines, medical AI
Congratulations on completing Grade 10! In Grade 11, you'll go deeper: neural networks, system design, databases, and becoming a responsible AI practitioner.