✦ New Age Learning 🔍
Home › Library › AI for New Learner- Senior 2 › Chapter 5: Neural Networks Demystified

📖 Chapter 5 of 13 · AI for New Learner- Senior 2 · Class 10

Chapter 5: Neural Networks Demystified

In this chapter

  • Krish from Pune builds a leaf-species classifier from scratch.
  • A perceptron — the simplest neural net. The maths fits on one line.
  • Why ‘deep’ learning means many layers.
  • Build a 3-layer net in pure numpy. No magic.
  • Then meet TensorFlow / PyTorch — what real engineers use.
  • Train a digit classifier on the MNIST dataset.

The Big Idea

Neural networks are not magic. They are stacks of multiplications and additions, with one small twist — a non-linear function between layers. That twist is what lets them learn faces, languages, leaf species, and the rules of Go. By the end of this chapter, you will have BUILT one with your bare hands. Then we will hand it over to PyTorch — the framework that runs ChatGPT, Krutrim, and ISRO’s vision systems.

Did you know?

PyTorch was started at Facebook AI Research in 2016. Today it is used by OpenAI, Tesla, ISRO, IIT labs, and every serious Indian AI startup. Learning PyTorch is one of the highest-paid skills for Indian engineers.

Builder Profile: Krish

Pune, MH · Krish, age 15

Krish builds a 3-layer network by hand: each line is a weight the network tunes to recognise leaf species.

Krish lives near Pashan in Pune. His school has an Atal Tinkering Lab with two laptops. He took 1,200 leaf photos around his colony — mango, neem, peepal, banyan, tulsi — labelled each, and trained a small neural network.

His first model: 51% accuracy. Barely better than a coin flip. He didn’t quit. He read about image augmentation — rotating, flipping, adjusting brightness on each leaf to teach the network that a tilted mango leaf is still a mango leaf. Accuracy jumped to 86%.

He deployed it. Now anyone at his school can scan a leaf with a phone and his AI tells them the species in Marathi or English. The botany teacher uses it. Two younger kids asked Krish to teach them. He started the school’s first AI club.

⊕ MATH MINUTE The Perceptron Formula

A perceptron takes inputs (x1, x2, ...), multiplies each by a weight (w1, w2, ...), adds a bias (b), then passes the sum through an activation function f. The OUTPUT is one number. The ‘learning’ is just finding the right weights. That is ALL it does.

output = f(w₁x₁ + w₂x₂ + ... + wₙxₙ + b)

💻 CODE LAB A Perceptron in 6 Lines of numpy

import numpy as np

# Inputs: leaf length, leaf width
x = np.array([12.5, 4.2])
w = np.array([0.7, -0.3])   # weights
b = 0.5

z = np.dot(w, x) + b
output = 1 if z > 0 else 0   # activation (step function)
print('Prediction:', output)  # 1 = mango leaf, 0 = not mango

Why ‘deep’ learning?

One neuron can’t learn much. A million can. A single perceptron can only draw a STRAIGHT line between two classes, but real life is curved. So we stack them into a LAYER of neurons; each neuron in the next layer takes the outputs of the previous one. With 3 layers, a network can learn ANY pattern in theory (the Universal Approximation Theorem, proved in 1989). “Deep” learning means networks with many layers — ChatGPT has 96, Krutrim has 32, and Krish’s leaf network has 3.

Krish builds a 3-layer network by hand: each line is a weight the network tunes to recognise leaf species.

💻 CODE LAB Forward Pass — a 3-layer Network in numpy

import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))     # activation function

x = np.array([12.5, 4.2])            # input: leaf [length, width]

# Layer 1: 2 inputs -> 4 hidden neurons
W1 = np.random.randn(4, 2)
b1 = np.random.randn(4)
h1 = sigmoid(W1 @ x + b1)            # hidden layer output

# Layer 2: 4 hidden -> 2 outputs (mango or not)
W2 = np.random.randn(2, 4)
b2 = np.random.randn(2)
output = sigmoid(W2 @ h1 + b2)

print('Class scores:', output)
print('Prediction:', np.argmax(output))

⚙ TRY IT TODAY

The code above does a FORWARD pass with RANDOM weights. To learn, the network needs a BACKWARD pass — adjusting weights based on errors. This is called BACKPROPAGATION. Search ‘backpropagation numpy’ and add training code to make this net actually learn. Once you can train this from scratch, you understand neural nets better than 99% of engineers.

💻 CODE LAB Same 3-layer Net — in PyTorch

import torch
import torch.nn as nn

class LeafNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(2, 4)     # input -> hidden
        self.fc2 = nn.Linear(4, 2)     # hidden -> output

    def forward(self, x):
        x = torch.sigmoid(self.fc1(x))
        x = torch.sigmoid(self.fc2(x))
        return x

model = LeafNet()
x = torch.tensor([12.5, 4.2])
print(model(x))   # PyTorch handles everything for us!

💻 CODE LAB Train an MNIST Digit Classifier in 25 Lines

import torch, torch.nn as nn, torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

train = datasets.MNIST('.', train=True, download=True,
                       transform=transforms.ToTensor())
loader = DataLoader(train, batch_size=64, shuffle=True)

model = nn.Sequential(
    nn.Flatten(),
    nn.Linear(28*28, 128), nn.ReLU(),
    nn.Linear(128, 10))

opt = optim.Adam(model.parameters(), lr=0.001)
loss_fn = nn.CrossEntropyLoss()

for epoch in range(3):
    for xb, yb in loader:
        opt.zero_grad()
        loss = loss_fn(model(xb), yb)
        loss.backward()
        opt.step()
    print('Epoch', epoch, 'loss', round(loss.item(), 3))
# After 3 epochs: ~97% accuracy on the test set

Solved illustrations

1. What does a perceptron actually do?

Show answer

Answer: Takes inputs, multiplies each by a weight, adds a bias, passes through an activation function. Output is one number that represents a class or value.

2. Why do we need MULTIPLE layers?

Show answer

Answer: One perceptron can only draw a straight line between classes. Real problems (images, language) need curved decision boundaries. Multiple layers can learn ANY pattern.

3. What is backpropagation in one sentence?

Show answer

Answer: An algorithm that adjusts every weight in the network based on how much it contributed to the error — using calculus (the chain rule).

4. Why do most engineers use PyTorch, not numpy, for real networks?

Show answer

Answer: PyTorch handles backprop automatically, runs on GPUs for 100x speedup, and is the standard in industry.

5. What is the MNIST dataset?

Show answer

Answer: 60,000 handwritten digit images (0-9), each 28×28 pixels. It is the ‘Hello World’ of deep learning — the standard benchmark every network is tested against first. You can train on it in under 60 seconds on free Colab.

Questions — Chapter 5

  1. Write the perceptron formula.
  2. What activation function did our examples use? Name one other.
  3. ChatGPT has how many transformer layers? (Hint: a number from this chapter.)
  4. Convert the numpy 3-layer net to PyTorch — write the LeafNet class.
  5. Why did Krish’s accuracy jump from 51% to 86%? What technique did he use?

Ship-It Challenge

Run the MNIST code on Google Colab. Get 95% accuracy. Screenshot it.

Check your understanding — Chapter 5

Tap an answer to check it instantly. These are for practice — nothing is saved or sent.

Q1. What does a perceptron actually do?

  1. Nothing useful
  2. Takes inputs, multiplies each by a weight, adds a bias, and passes the sum through an activation function
  3. Stores images
Show answer

B. Takes inputs, multiplies each by a weight, adds a bias, and passes the sum through an activation function

Q2. Why do neural networks need MULTIPLE layers?

  1. To use more electricity
  2. One perceptron can only draw a straight line; multiple layers can learn curved boundaries and any pattern
  3. Layers are just decoration
Show answer

B. One perceptron can only draw a straight line; multiple layers can learn curved boundaries and any pattern

Q3. What is backpropagation in one sentence?

  1. A way to delete the model
  2. An algorithm that adjusts every weight based on how much it contributed to the error, using the chain rule
  3. A type of dataset
Show answer

B. An algorithm that adjusts every weight based on how much it contributed to the error, using the chain rule

Q4. Why do most engineers use PyTorch instead of raw numpy for real networks?

  1. numpy is illegal
  2. PyTorch handles backpropagation automatically, runs on GPUs for ~100x speedup, and is the industry standard
  3. PyTorch is only for games
Show answer

B. PyTorch handles backpropagation automatically, runs on GPUs for ~100x speedup, and is the industry standard

All chapters in AI for New Learner- Senior 2

  1. Chapter 1: Where You Are Now — The ML Lifecycle
  2. Chapter 2: From Idea to Dataset
  3. Chapter 3: Linear Models — The Workhorses
  4. Chapter 4: Decision Trees & Random Forests
  5. Chapter 5: Neural Networks Demystified
  6. Chapter 6: Evaluation — Does It Actually Work?
  7. Chapter 7: Indian Datasets & Real Problems
  8. Chapter 8: Deploy Your AI — Get a Public URL
  9. Capstone Build-It Projects
  10. Final Book Exam
  11. AI / ML / Python Glossary
  12. Career & College Pathways
  13. Series Completion Diploma

Practise for Class 10