Byte by Byte › Book 7: Networks, Programming and Machine Learning › Chapter 15: Decision Trees and Neural Networks
Chapter 15: Decision Trees and Neural Networks
You will learn: what features and labels are, how a decision tree classifies data, how a tree chooses its questions, how to build a tree by hand and in Python, the nearest-neighbour method and why features must be scaled, how an artificial neuron and a perceptron work, how a perceptron learns, how neural networks and deep learning are built from layers, how training adjusts weights, why explainable AI matters, and how generative AI and GANs create new images.
🔎 The Case
On the whiteboard, Nimo had drawn two boxes. One said Mirror Catcher. The other said Mirror Engine.
"We have a model that looks at frames and decides real or edited," he said. "Somewhere, Glim has a model that makes frames. Right now, both are black boxes to us. Things go in, answers come out, and we have no idea what happens in between."
"Does it matter how ours works," asked Pip, "as long as it works?"
"It stopped working," said Vega flatly.
"And when it did," said Nimo, "we couldn't say why. We couldn't tell the Queen what made a frame suspicious. Imagine standing up in front of all of Memunic to say Simbha is innocent, and when someone asks how do you know?, the only answer is the computer said so."
Memoon thought of the rabbits outside the palace. Of Luna saying are we supposed to ignore our own eyes? "Nobody would believe us," she said. "And they'd be right not to."
"Then today," said Nimo, "we open the boxes."
💡 The Concepts
Features and labels. In supervised learning (Chapter 14), every example has features (the inputs: the facts we know about it) and a label (the answer we want the model to predict). To predict whether a post will go viral, the features might be has a photo, posted by a new account and shares in the first hour; the label is viral or not viral. Choosing good features is one of the most important skills in machine learning.
Classification and regression. As you learned in Book 6, predicting a category (viral or not viral, real or edited) is classification; predicting a number (tomorrow's temperature, a house price) is regression. Both kinds of model below can do either; we will use classification.
Decision trees. A decision tree is a model that classifies an example by asking a series of yes/no questions about its features, like a flowchart (Book 6) or a game of twenty questions.
Shares in first hour > 50?
/ \
Yes No
| |
VIRAL Has a photo?
/ \
Yes No
| |
New account? NOT VIRAL
/ \
Yes No
| |
VIRAL NOT VIRAL
- The first question, at the top, is the root node.
- Each question is a decision node; each line out of it is a branch.
- Each final answer is a leaf node.
- To classify an example, start at the root and follow the branches that match its features until you reach a leaf.
A decision tree is really just a set of nested if statements (Book 6), and you can write one in Python:
def predict_spread(new_account, has_photo, shares_first_hour):
"""A tiny decision tree: will this post go viral?"""
if shares_first_hour > 50:
return "viral"
else:
if has_photo:
if new_account:
return "viral"
else:
return "not viral"
else:
return "not viral"
print(predict_spread(True, True, 10)) print(predict_spread(False, True, 10))
Output: viral then not viral .
The difference between this and ordinary programming is who writes the questions. In machine learning, the computer chooses the questions itself, by learning from labelled data.
How a tree chooses its questions. At each node, the learning algorithm tries every possible question and picks the one that splits the training examples into the purest groups: groups that are as close as possible to all one label. Here are eight training posts:
| Post | Has photo? | New account? | Label |
|---|---|---|---|
| 1 | Yes | Yes | Viral |
| 2 | Yes | Yes | Viral |
| 3 | Yes | No | Not viral |
| 4 | Yes | Yes | Viral |
| 5 | No | Yes | Not viral |
| 6 | No | No | Not viral |
| 7 | Yes | No | Viral |
| 8 | No | No | Not viral |
Try each feature as the first question:
| Question | "Yes" group | "No" group | Mistakes if each group takes its majority label |
|---|---|---|---|
| Has photo? | 4 viral, 1 not | 0 viral, 3 not | 1 |
| New account? | 3 viral, 1 not | 1 viral, 3 not | 2 |
"Has photo?" makes purer groups, with only one example on the wrong side, so it becomes the root. The algorithm then repeats the same process inside each group that is still mixed, until the groups are pure or there is too little data to split further. Real tools measure purity with formulas such as Gini impurity or entropy, but the idea is exactly this counting.
Strengths and weaknesses of decision trees.
| Strengths | Weaknesses |
|---|---|
| Easy to understand and explain: you can follow the path to any answer | A very deep tree can memorise the training data (overfitting) |
| Fast to train and use | Small changes in the data can change the tree a lot |
| Work with numbers and categories | One tree is often less accurate than more complex models |
To prevent overfitting, the tree's depth is limited, or branches with very few examples are cut off (pruning). A random forest trains many different trees on different samples of the data and lets them vote, which is usually much more accurate than one tree.
Nearest neighbours. A completely different idea: to classify a new example, find the training examples most similar to it, and copy their label. This is the k-nearest neighbours (k-NN) method. Similarity is usually measured by distance: plot each example as a point using its features as coordinates (like the scatter graphs in Book 6), and measure the straight-line distance using Pythagoras' theorem:
d = √( (x₁ − x₂)² + (y₁ − y₂)² )
Then look at the k nearest points (k is often 3 or 5) and take a vote.
import math
fruits = [
(7.0, 160, "apple"), (7.5, 170, "apple"), (6.8, 150, "apple"),
(12.0, 120, "banana"), (13.5, 130, "banana"), (11.5, 115, "banana"),
]
def distance(a_length, a_weight, b_length, b_weight):
return math.sqrt((a_length - b_length) ** 2 + (a_weight - b_weight) ** 2)
def knn(length, weight, k=3):
"""Classify a fruit by the labels of its k nearest neighbours."""
dists = []
for f_length, f_weight, label in fruits:
dists.append((distance(length, weight, f_length, f_weight), label))
dists.sort()
nearest = [label for d, label in dists[:k]]
return max(set(nearest), key=nearest.count)
print(knn(8.0, 155)) print(knn(12.5, 125))
Output: apple then banana . (Each fruit is a tuple of length in cm, weight in grams and label. dists.sort() sorts the tuples by their first item, the distance. max(set(nearest), key=nearest.count) picks the label that appears most often among the nearest.)
There is a hidden problem here. The weights are in the hundreds while the lengths are around 10, so weight completely dominates the distance: a 10-gram difference counts as much as a 10-centimetre one. To be fair to every feature, real k-NN models first scale (normalise) the features to similar ranges, such as 0 to 1. Choosing and preparing features carefully is part of Stage 3 of the lifecycle.
Artificial neurons. The models behind modern AI, from Teachable Machine to chatbots, are artificial neural networks, loosely inspired by the brain. The brain has about 86 billion neurons (nerve cells), each receiving signals from others and "firing" a signal of its own when its inputs are strong enough.
An artificial neuron is a tiny calculation:
- It receives several inputs (numbers).
- Each input is multiplied by a weight, which says how important that input is. Weights can be positive (encourage firing) or negative (discourage it).
- The results are added together, along with an extra number called the bias, which makes the neuron easier or harder to fire.
- The total passes through an activation function, which decides the output. The simplest is a step function: output 1 if the total is greater than 0, otherwise 0.
Example: a neuron that decides whether a frame looks edited, with two inputs: edge flicker = 0.9 and colour mismatch = 0.2, weights 0.6 and 0.3, and bias −0.4.
(0.9 × 0.6) + (0.2 × 0.3) + (−0.4) = 0.54 + 0.06 − 0.4 = 0.2
0.2 is greater than 0, so the neuron outputs 1: edited.
The perceptron and how it learns. A single artificial neuron with a step function is called a perceptron, invented by Frank Rosenblatt in 1958. Its knowledge is entirely in its weights and bias, and it learns by adjusting them:
- Start with weights and bias of 0 (or small random numbers).
- For each training example, calculate the output.
- Work out the error: target minus output.
- If the error is not zero, nudge each weight by
learning rate × error × input, and the bias bylearning rate × error. - Repeat for all the examples. One pass through all the training data is called an epoch. Keep going, epoch after epoch, until there are no errors (or few enough).
The learning rate is a small number, such as 0.1, that controls the size of each nudge. Too large, and the weights jump around; too small, and learning takes forever.
Here a perceptron learns the logic of AND (Book 6's truth tables): output 1 only when both inputs are 1.
def perceptron(x1, x2, w1, w2, bias):
total = x1 * w1 + x2 * w2 + bias
return 1 if total > 0 else 0
w1, w2, bias = 0.0, 0.0, 0.0 rate = 0.1 data = [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)]
for epoch in range(1, 11):
errors = 0
for x1, x2, target in data:
output = perceptron(x1, x2, w1, w2, bias)
error = target - output
if error != 0:
errors = errors + 1
w1 = w1 + rate * error * x1
w2 = w2 + rate * error * x2
bias = bias + rate * error
print(f"Epoch {epoch}: errors = {errors}, w1 = {w1:.1f}, w2 = {w2:.1f}, bias
= {bias:.1f}")
if errors == 0:
break
Output:
Epoch 1: errors = 1, w1 = 0.1, w2 = 0.1, bias = 0.1 Epoch 2: errors = 3, w1 = 0.2, w2 = 0.1, bias = 0.0 Epoch 3: errors = 3, w1 = 0.2, w2 = 0.1, bias = -0.1 Epoch 4: errors = 2, w1 = 0.2, w2 = 0.2, bias = -0.1 Epoch 5: errors = 1, w1 = 0.2, w2 = 0.1, bias = -0.2 Epoch 6: errors = 0, w1 = 0.2, w2 = 0.1, bias = -0.2
( 1 if total > 0 else 0 is a one-line if , called a conditional expression.) After six epochs it makes no mistakes. Nobody wrote a rule for AND: the perceptron found weights that work, by correcting itself whenever it was wrong. That is machine learning in its simplest form.
A single perceptron can only separate classes with a straight line, so it cannot learn some simple patterns, such as XOR (output 1 when exactly one input is 1). This limitation, pointed out in 1969, slowed AI research for years, until researchers connected many neurons in layers.
Neural networks. A neural network connects many artificial neurons in layers:
Input layer Hidden layers Output layer (features) (find patterns) (prediction)
O \ / O \ / O \
O --- X --- O --- X --- O --- O edited?
O / \ O / \ O /
- The input layer receives the features: for an image, the colour values of every pixel (Book 6).
- One or more hidden layers combine the inputs. Each neuron's output becomes an input to every neuron in the next layer.
- The output layer gives the prediction, often as a probability for each class, such as edited: 0.83, real: 0.17. This is the confidence score you saw in Teachable Machine.
A network with many hidden layers is called a deep neural network, and learning with one is deep learning. In an image network, the early layers learn to detect simple things such as edges and spots of colour; middle layers combine them into textures and shapes (an eye, the curve of a mane); later layers combine those into whole objects. Nobody programs these detectors: they emerge from training. Networks for images usually use special layers called convolutional layers, which scan the image in small patches, so they are called convolutional neural networks (CNNs).
How a network is trained. Training a network follows the same idea as the perceptron, on a vast scale:
- Forward pass: feed a training example through the network to get a prediction.
- Loss: measure how wrong the prediction is with a loss function (a bigger number means more wrong).
- Backpropagation: work backwards through the layers, calculating how much each weight contributed to the error.
- Update: nudge every weight a little in the direction that reduces the loss. This method is called gradient descent: like walking down a hill in fog by always stepping in the steepest downhill direction.
- Repeat for millions of examples, over many epochs.
Modern networks have millions or billions of weights (called parameters, as you learned with chatbots in Book 6), and training them needs huge amounts of data and powerful computers with GPUs (graphics processing units), chips that can do thousands of calculations at once. Teachable Machine trains quickly because it uses transfer learning: it starts with a network already trained on millions of images and only retrains the last layers on your examples.
Explainable AI. A decision tree can explain itself: just follow the path. A deep neural network with millions of weights cannot easily say why it made a decision; it is a black box. When AI decisions affect people's lives, in loans, hiring, medicine or justice, people need to understand and challenge them. Explainable AI (XAI) is the field of making AI decisions understandable, for example by highlighting which parts of an image most affected the prediction. Sometimes a slightly less accurate but explainable model is the right choice.
Generative AI and GANs. So far, every model has recognised or predicted things. Generative AI creates new content: text (chatbots, Book 6), images, music, voices and video. A generative model learns the patterns of its training data so well that it can produce new examples that look like it.
One famous design for generating images is the generative adversarial network (GAN), invented in 2014. It has two networks that compete:
- The generator creates fake images, starting from random noise.
- The discriminator looks at images, some real and some from the generator, and tries to tell which are fake.
Each round, the discriminator gets better at spotting fakes, and the generator uses the discriminator's verdicts to get better at fooling it. Over thousands of rounds, the generator's fakes become extremely realistic. Many newer image and video generators use a different method called diffusion, which learns to turn random noise step by step into a clear image, but the principle is the same: a network trained on huge amounts of real data learns to produce convincing new data.
This is the technology behind deepfakes (from deep learning and fake): realistic generated or altered images, videos and voices of real people. Chapter 16 looks at how to deal with them.
Real World: Neural networks help Indian doctors read medical scans, help farmers identify crop diseases from photos, translate between Indian languages through Bhashini, and help ISRO analyse satellite images. The same technology, in other hands, generates fake videos and cloned voices for scams. The technology is the same; the use is a choice.
Career Spotlight: AI researcher. AI researchers invent new model designs and training methods, test their limits, and study how to make AI safer, fairer and more explainable. Many have backgrounds in mathematics, statistics or computer science, and India's IITs, IISc and research labs are active in the field.

🛠️ Build It
Activity 1: Build a decision tree by hand. Here is training data about whether students in a class went outdoors at lunchtime:
| Day | Weather | Temperature | Homework due? | Went outdoors? |
|---|---|---|---|---|
| 1 | Sunny | Hot | No | Yes |
| 2 | Sunny | Mild | No | Yes |
| 3 | Rainy | Mild | No | No |
| 4 | Sunny | Mild | Yes | No |
| 5 | Cloudy | Mild | No | Yes |
| 6 | Rainy | Hot | No | No |
| 7 | Sunny | Hot | Yes | No |
| 8 | Cloudy | Hot | No | Yes |
- For each feature, count how the labels split, as in The Concepts. Which feature makes the purest first split? (Hint: try Homework due? and Weather.)
- Draw the complete tree, continuing to split until every leaf is pure.
- Use your tree to predict: Sunny, Mild, no homework; Rainy, Mild, homework due.
- Write your tree as a Python function with nested
ifstatements, and test it on all eight rows.
Activity 2: k-NN with scaling. Run the fruit program. Then try knn(9.5, 140) . Now scale the features: divide every length by 15 and every weight by 200 (inside distance , or by making a scaled copy of the data), so both are roughly between 0 and 1. Run knn(9.5, 140) again. Does the answer change? Explain why scaling matters.
Activity 3: Train a perceptron. Run the perceptron program. Then:
- Change the data to the OR truth table (output 1 if either input is 1). How many epochs does it need?
- Change it to XOR:
[(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]. What happens, even after 10 epochs? Plot the four points on squared paper, coloured by their label, and try to draw one straight line that separates the colours. Why can't a single perceptron learn XOR? - Change the learning rate to 0.5, then 0.01, for AND. What changes?
Activity 4: Play with a neural network. Open playground.tensorflow.org in Edge. This website trains a real small neural network in your browser.
- Choose the dataset in the top-left that has an orange circle inside a blue ring. Click the Play button and watch the network learn to separate them. Watch the Test loss number fall.
- Remove all hidden layers (click the − beside "Hidden layers") and press Play again. Can it still separate the circle? Why not?
- Add hidden layers and neurons back one at a time. What is the smallest network that works?
- Choose the spiral dataset. How many layers and neurons does it need? Try changing the Learning rate.
Activity 5: Look inside Teachable Machine. Reopen your Chapter 14 waste classifier. Click Advanced under Training to see Epochs, Batch size and Learning rate. Train with 5 epochs and then 100 epochs, and compare the accuracy on your test photos. Click Under the hood to see graphs of accuracy and loss during training. Does more training always help?
Unplugged: Human neural network. Arrange 9 people: 3 inputs, 4 hidden neurons, 2 outputs ("cat" and "dog"). Inputs hold up 1 or 0 for a feature: "pointy ears", "barks", "whiskers". Each hidden neuron has a card with their weights for each input and a bias; they add up what they receive and hold up 1 if their total is over 0. The outputs do the same from the hidden layer. Run a few animals through. When the network is wrong, a "trainer" adjusts one weight on one card. How many rounds does it take to get every example right?
✅ Case Closed
They rebuilt the detector's first stage as a decision tree, so that every flag came with a reason anyone could follow: edge flicker above threshold in frames 2 to 4, lip movement out of time with the sound by 120 milliseconds. It was less accurate than the neural network on its own, so they used both: the network to find suspicious frames, the tree to explain them.
Then Frost explained GANs on the whiteboard, and Memoon went very still.
"A generator and a discriminator," she said. "Every time the discriminator catches a fake, the generator learns from it." She turned to the others. "For two days, we published Mirror
Catcher's results on the Truth Desk. Every flagged clip, with its confidence score. Anyone could see them."
Vega understood first. "Glim was using our detector as his discriminator. We trained his generator for him."
The room was silent.
"Then we stop publishing the scores," said Quill at last, "and we stop trying to win a race of detectors. He'll always have the next trick."
"So what do we do instead?" asked Pip.
Memoon looked at the GAN diagram, at the arrow pointing into the generator labelled real training data. "Every generator needs real examples to learn from," she said slowly. "Hours of Simbha's real face, real voice, real mane. Glim didn't make those up. He had to get them from somewhere." She pulled her laptop towards her. "If we can find where the real footage came from, we can find the originals. And the originals will prove what Simbha really did."
❓ Test Yourself
- What are features and labels? Give the features and label for an AI that predicts whether it will rain tomorrow.
- Label the root node, a decision node, a branch and a leaf node on the viral-post tree.
- How does a decision tree learning algorithm choose which question to ask first?
- What is overfitting in a decision tree, and how can it be prevented?
- What is a random forest?
- Explain how the k-nearest neighbours method classifies a new example. Why should features be scaled first?
- A neuron has inputs 1 and 0.5, weights 0.4 and −0.6, and bias 0.1. Calculate the total. Using a step function, what is the output?
- Describe the four steps by which a perceptron learns. What is an epoch? What is the learning rate?
- What are the input, hidden and output layers of a neural network? What makes a network "deep"?
- Explain the steps of training a neural network: forward pass, loss, backpropagation and gradient descent.
- What is a black box model? Why does explainable AI matter? Give an example where it is essential.
- Explain how a GAN works, using the words generator and discriminator.
- Challenge: Using a dataset of at least 12 examples you collect yourself (for example, your classmates' favourite sports with features such as height, team or individual preference, and indoor or outdoor preference), build a decision tree by hand, write it as a Python function, and test it on 4 new examples. Report its accuracy and explain one mistake it made.
📚 Key Terms
- Feature: an input fact about an example, used to make a prediction.
- Label: the answer a supervised model learns to predict.
- Classification / regression: predicting a category / a number.
- Decision tree: a model that classifies by asking a series of questions about features.
- Root node / decision node / leaf node: the first question / any question / a final answer in a tree.
- Branch: a path from one node to the next.
- Purity: how close a group is to containing only one label.
- Pruning: removing branches of a tree to prevent overfitting.
- Random forest: many decision trees that vote together.
- k-nearest neighbours (k-NN): classifying an example by the labels of the k most similar training examples.
- Scaling (normalising): converting features to similar ranges.
- Artificial neuron: a unit that multiplies inputs by weights, adds a bias and applies an activation function.
- Weight: a number showing how important an input is to a neuron.
- Bias (in a neuron): an extra number that makes a neuron easier or harder to activate.
- Activation function: the function that turns a neuron's total into its output.
- Perceptron: a single artificial neuron that learns by adjusting its weights.
- Epoch: one complete pass through all the training data.
- Learning rate: the size of each adjustment during training.
- Neural network: connected layers of artificial neurons.
- Input / hidden / output layer: the layers that receive features / find patterns / give predictions.
- Deep learning: machine learning with neural networks that have many hidden layers.
- Convolutional neural network (CNN): a neural network designed for images.
- Loss function: a measure of how wrong a model's prediction is.
- Backpropagation: working out how much each weight contributed to an error.
- Gradient descent: adjusting weights step by step to reduce the loss.
- GPU: a chip that performs many calculations at once, used to train neural networks.
- Transfer learning: starting from a model trained on one task and retraining it for another.
- Black box: a model whose reasons for its decisions cannot easily be seen.
- Explainable AI (XAI): making AI decisions understandable to people.
- Generative AI: AI that creates new text, images, sound or video.
- GAN: a generator and a discriminator network trained in competition.
- Deepfake: realistic AI-generated or altered media showing real people.
Keep learning with Byte by Byte
Explore Book 7: Networks, Programming and Machine Learning. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment