Phase 0B · AI-PRE-01 Prerequisite Java Examples

What is AI? & Machine Learning Fundamentals

Start here with zero AI knowledge assumed. This note builds your mental model of what Artificial Intelligence is, how it differs from the software you already know, and how Machine Learning — its most important subset — actually works under the hood. These concepts underpin every chapter of the CT-AI syllabus.

Covers AI-PRE-01 + AI-PRE-02 (merged)
Part 1 What is AI?
Part 2 ML Fundamentals
Language Java examples
Next note AI-PRE-02 · Neural Nets & GenAI
Part 1 — What is AI?

Why AI Exists — History & Motivation

Before any technical definition, understand the problem AI is trying to solve. Traditional software works by a programmer writing explicit rules: if this happens, do that. This works brilliantly for problems where the rules are known and finite — calculating tax, sorting a list, processing a payment. But many real-world problems have rules that are too complex, too numerous, or simply unknown to write by hand.

Consider teaching a computer to recognise a cat in a photo. You could try writing rules: "it has pointy ears, whiskers, fur…" — but cats appear in every lighting condition, angle, size, breed, and pose. You would need millions of rules, and you'd still miss cases. The rules approach breaks down.

💡 The Core Insight of AI

Instead of telling the computer the rules, what if we showed it thousands of examples and let it figure out the rules itself? That shift in thinking is the origin of Machine Learning — and it is the most important sentence in this entire note.

A Brief Timeline (So You Have Context)

Understanding the era matters because the CT-AI exam references AI technologies across generations:

1
1950s–1980s — Rule-Based / Expert Systems
AI was hand-crafted: expert systems encoded human knowledge as thousands of if-then rules. A medical diagnosis system might have 50,000 rules written by doctors. It worked for narrow domains but couldn't generalise, and maintaining the rule set was a nightmare. This is what people mean by "classical AI" or GOFAI.
2
1990s–2000s — Statistical ML Emerges
Researchers discovered that algorithms could learn patterns from data. Support Vector Machines, decision trees, and early neural networks showed promise, but data and compute were limited. Results were modest by today's standards.
3
2010s — Deep Learning Explosion
Three things converged: massive datasets (the internet), GPU compute (NVIDIA), and better algorithms (deep neural networks). In 2012, AlexNet demolished image recognition benchmarks. Everything changed. From 2012–2020, deep learning took over computer vision, NLP, speech, and games.
4
2020s — Generative AI & LLMs
Large Language Models (GPT-3, then ChatGPT, then many others) demonstrated that a single model trained on internet-scale text could answer questions, write code, translate, summarise, and reason. GenAI became mainstream. This is the primary AI paradigm you will test in CT-AI v2.0.

Part 1 — What is AI?

AI-Based vs Conventional Software — The Key Difference

This comparison is directly examinable in CT-AI. You must be able to identify which properties belong to which type of system, and explain why AI-based systems need a different testing approach.

✓ Conventional Software
  • Deterministic — same input always produces same output, every single time
  • Explicit rules — logic is written by a developer and is readable
  • Explainable by design — you can trace exactly which line of code made a decision
  • Static behaviour — doesn't change after deployment unless you redeploy
  • Binary correctness — output is either right or wrong
  • Reproducible — run the same test 1000 times, get the same result
vs
⚡ AI-Based System
  • Probabilistic — same input can produce different outputs in different runs
  • Learned behaviour — the "logic" is encoded in millions of numerical weights, not code
  • Black box — often impossible to trace exactly why a decision was made
  • Can adapt — some AI systems update themselves after deployment (adaptive)
  • Statistical correctness — correctness is measured over a distribution of inputs
  • Non-reproducible — the same prompt to an LLM might return different wording each time
⚠️ Why This Matters for Testing

Traditional testing assumes: write a test, run it, get a definitive pass or fail. That contract breaks with AI. You can't write a traditional test oracle (the thing that says "this output is correct") for a system whose output is inherently probabilistic. This is the test oracle problem — a major topic in CT-AI Chapter 4. Everything you learn here is the foundation for understanding why AI needs its own testing discipline.

The Java Analogy — If-Else vs Model

Imagine building a loan approval system. Here's how the two paradigms differ in code:

Java — Conventional Approach Deterministic, explicit rules
// CONVENTIONAL: Rules explicitly written by a developer
// Every decision path is readable, traceable, reproducible

public class LoanApprovalConventional {

    public boolean approve(Applicant applicant) {

        // Rule 1: minimum credit score
        if (applicant.getCreditScore() < 650) {
            return false;  // ALWAYS false for score < 650
        }

        // Rule 2: debt-to-income ratio must be under 40%
        double dti = applicant.getMonthlyDebt() / applicant.getMonthlyIncome();
        if (dti > 0.40) {
            return false;
        }

        // Rule 3: employment history
        if (applicant.getYearsEmployed() < 2) {
            return false;
        }

        return true;
        // Testing this is straightforward:
        //   Input: creditScore=700, dti=0.30, years=3  → ALWAYS approves
        //   Input: creditScore=600                      → ALWAYS rejects
        // Same test, same result, every single time.
    }
}
Java — AI/ML Approach (Conceptual) Probabilistic, learned behaviour — no explicit rules
// AI-BASED: The "rules" are not written — they are LEARNED
// from 10 million historical loan decisions

public class LoanApprovalML {

    private MLModel model;  // loaded trained model (thousands of weights)

    public Prediction approve(Applicant applicant) {

        // Features extracted from applicant data
        // The model was trained to understand which combinations
        // of these features historically led to repayment vs default
        double[] features = {
            applicant.getCreditScore(),
            applicant.getMonthlyIncome(),
            applicant.getMonthlyDebt(),
            applicant.getYearsEmployed(),
            applicant.getLoanAmount(),
            applicant.getAge()
            // ... potentially 50+ more features
        };

        // The model outputs a PROBABILITY (0.0 to 1.0)
        // NOT a hard yes/no — a confidence score
        double approvalProbability = model.predict(features);

        // Testing challenge:
        //   Same applicant data → model might give 0.73 one run, 0.71 next
        //   (due to non-determinism in some model types)
        //
        //   WHY did it approve? You can't read the reason from the code.
        //   The "reason" is distributed across thousands of weights.
        //   This is the BLACK BOX problem.
        //
        //   Is 0.73 correct? Who decides the threshold? What if the
        //   training data had historical bias against certain demographics?

        return new Prediction(approvalProbability > 0.7, approvalProbability);
    }
}
🔍 Tester's Lens

With the conventional system, you can enumerate all paths and achieve 100% branch coverage. With the ML system, you're testing statistical behaviour across a distribution of inputs. "Correct" is no longer binary. The entire CT-AI certification exists because of this gap.


Part 1 — What is AI?

The AI → ML → Deep Learning Nesting

These three terms are used interchangeably in everyday conversation, but in the exam they have precise, distinct meanings with a specific containment relationship.

The Containment Relationship — AI ⊃ ML ⊃ Deep Learning
Artificial Intelligence (AI)

Any technique that enables machines to mimic human intelligence — including rule-based systems, search algorithms, expert systems, and learning systems. The broadest possible umbrella.

Machine Learning (ML)

The subset of AI where systems learn patterns from data without being explicitly programmed. The rules are inferred, not written. Includes SVMs, decision trees, random forests, neural networks, and more.

Deep Learning (DL)

The subset of ML using multi-layered neural networks (deep = many layers). Powers image recognition, speech, LLMs. Requires large data and GPU compute. Tends to be the "black box" due to its complexity. Examples: CNNs, RNNs, Transformers.

⚠️ Common Exam Trap

Not all AI is ML. An expert system with 10,000 hand-coded rules is AI, but it is not ML — it doesn't learn from data. Not all ML is Deep Learning. A logistic regression model (simple linear ML) is ML but not DL. The exam will test these distinctions.

Term Definition Learns from data? Needs neural nets? Example
AI Any system simulating human-like intelligence Not necessarily Not necessarily Chess engine (rule-based search)
ML AI that learns patterns from data without explicit rules Yes — required Not necessarily Decision tree for spam detection
Deep Learning ML using deep multi-layer neural networks Yes — required Yes — required GPT-4, image classifiers, AlphaGo

Part 1 — What is AI?

Narrow AI / General AI / Super AI

The CT-AI syllabus explicitly requires you to distinguish these three categories. They describe scope of capability, not the underlying technique.

Narrow AI (ANI)
One task, done extremely well
Everything that exists today. AlphaGo plays Go — but can't write an email. GPT-4 writes text — but can't drive a car. Each system is a specialist.
General AI (AGI)
Human-level, any domain
Hypothetical. An AGI could switch from debugging code to writing poetry to diagnosing illness — just like a human does. Does not exist yet (as of 2025).
Super AI (ASI)
Beyond human in all domains
Theoretical. Would surpass the best human experts in every field simultaneously. The subject of much ethical debate. Does not exist.
🎯 Exam Focus

CT-AI is entirely about Narrow AI in practice. Every testing technique, every quality characteristic, every dataset consideration in the syllabus applies to real-world Narrow AI systems. AGI and ASI appear only as definitional K1 knowledge — you need to define them, not test them.


Part 1 — What is AI?

AI Technology Types — The Landscape

The CT-AI syllabus lists specific AI technology categories. You need to recognise each, understand what it does, and map it to a real-world example. The table below is your reference:

TechnologyWhat it doesReal-world exampleExam relevance
Supervised ML Learns from labelled examples (input→output pairs) Spam filter, loan approval, image classifier High — core of Ch.3
Unsupervised ML Finds hidden patterns in unlabelled data Customer segmentation, anomaly detection Medium
Reinforcement Learning Agent learns by trial-and-error via rewards/penalties AlphaGo, robotics, ad bidding systems Medium
Deep Learning / Neural Networks Multi-layer networks learning complex representations Image recognition, speech-to-text High — Ch.3 neural network testing
Natural Language Processing (NLP) Understanding and generating human language Chatbots, sentiment analysis, translation Medium
Computer Vision Extracting meaning from images and video Medical imaging, autonomous vehicles, facial recognition Medium
Fuzzy Logic Handles imprecision and vague rules (degrees of truth) Washing machine cycles, HVAC systems Low — definitional K1
Expert Systems Encodes human expert knowledge as IF-THEN rules Medical diagnosis support (1980s MYCIN) Low — historical context
Generative AI (GenAI) Creates new content — text, images, code, audio ChatGPT, DALL-E, Midjourney, GitHub Copilot Very High — Ch.4 dedicated section
Agentic AI AI that takes actions autonomously towards a goal, often using tools AI agents that browse web, run code, call APIs Medium — growing topic in v2.0

GenAI Sub-technologies (CT-AI v2.0 Specific)

CT-AI v2.0 added dedicated GenAI coverage. Know these three sub-types:

LLMs (Large Language Models)
Neural networks trained on massive text datasets to predict the next token (word-piece). Scale gives emergent capability: they can answer questions, write code, summarise, translate. Examples: GPT-4, Claude, Gemini, Llama. The primary GenAI type in CT-AI testing scope.
GANs (Generative Adversarial Networks)
Two networks compete: a Generator creates fake data, a Discriminator tries to tell real from fake. They train against each other until the generator produces convincing outputs. Used for: image generation (deepfakes), synthetic data generation for training. Notable for testing: generated data can look real but contain subtle errors — important for data quality testing.
Diffusion Models
Learn to reverse a gradual noise-adding process. Training: take a real image, add noise step by step until it's pure random noise. Then train the model to reverse that process. At inference: start from noise, repeatedly denoise to generate an image. Examples: Stable Diffusion, DALL-E 3, Midjourney. Output is creative and non-deterministic — same prompt produces different images each time. A significant testing challenge for correctness.

Part 1 — What is AI?

Real-World AI Decoded — What's Actually Happening

Before moving to ML mechanics, ground your understanding in everyday AI systems. For each, identify what type it is, what it learned, and why it's hard to test.

SystemAI TypeWhat the model learnedTesting challenge
Gmail spam filter Supervised ML (classification) Patterns in email headers, links, language that correlate with spam vs not-spam labels Spam evolves — what was spam yesterday might not trigger today; false positives lose legitimate emails
Netflix recommendations Unsupervised + Supervised ML Viewing patterns of millions of users; which users are similar; which content correlates with satisfaction No single "correct" recommendation; success measured statistically by watch-time and ratings
Siri / Alexa Deep Learning (NLP + Speech) Audio → text (speech recognition model) + text → intent (NLP model) Accents, background noise, ambiguity — "play songs by rocks" vs "play songs by The Rock"
Credit card fraud detection Supervised ML (binary classification) Historical transaction patterns that were labelled as fraud or legitimate Class imbalance — fraud is rare, so a model that always says "not fraud" is 99.9% accurate but useless; precision vs recall tradeoff
ChatGPT / Claude Deep Learning (LLM, GenAI) Next-token prediction across trillions of internet text tokens No ground truth for most responses; hallucinations; safety testing; prompt injection; non-determinism

Part 2 — ML Fundamentals

What is a Model? — The Central Object

The word "model" appears hundreds of times in the CT-AI syllabus. You need a precise mental picture of what it actually is — not "an AI thing," but a specific mathematical object.

A model is a mathematical function. It takes input numbers and returns output numbers. What makes it interesting is that its internal parameters (called weights and biases) were not written by hand — they were determined through a training process on example data.

Think of it this way: in Java, you write a function like double predictPrice(double size, double bedrooms). The body of that function — the actual math — was learned from thousands of house sales. You don't write the body. The training algorithm writes it for you by adjusting the weights until predictions match the training examples.

Java — Conceptual What a model IS, mathematically
// A simple linear model (most basic form) for house price prediction
// y = w1*x1 + w2*x2 + b
//
// x1 = house size (sq ft)
// x2 = number of bedrooms
// w1, w2 = WEIGHTS — numbers the training process determines
// b       = BIAS — a constant offset term, also learned
// y       = predicted price

public class LinearModel {

    // These values were NOT written by a programmer.
    // They were found by the training algorithm after seeing
    // thousands of (size, bedrooms, actual_price) examples.
    private double w1 = 150.5;   // weight for house size
    private double w2 = 8200.0;  // weight for bedrooms
    private double b  = -12000.0; // bias

    public double predict(double sizeSqFt, double bedrooms) {
        return w1 * sizeSqFt + w2 * bedrooms + b;
        // For a 1500 sqft, 3-bedroom house:
        // = 150.5 * 1500 + 8200 * 3 + (-12000)
        // = 225750 + 24600 - 12000
        // = $238,350 predicted price
    }
}

// A real model might have MILLIONS of weights instead of 2.
// The math is the same — just vastly more dimensions.
// The key insight: the weights ARE the model.
💡 Key Vocabulary Locked In
  • Weight — a learnable number that determines how much influence one input has on the output
  • Bias — a learnable offset constant that shifts the output independently of inputs
  • Parameter — collective term for all weights and biases in a model (GPT-4 has ~1.7 trillion parameters)
  • Inference / Prediction — using the trained model to produce an output for a new input (production use)

Part 2 — ML Fundamentals

Features & Labels — The Language of Training Data

Every ML training dataset has the same structure: a set of features (input columns) and a label (the answer column). The model's job is to learn the mapping from features to label.

Feature (also: input variable, predictor, attribute)
A measurable property of the thing you're trying to make predictions about. For a loan application: credit score, monthly income, age, employment years, loan amount requested. For an email spam model: word frequencies, presence of links, sender domain, time sent. Feature engineering — the process of choosing, transforming, and creating features — is one of the most impactful parts of ML (covered in CT-AI Ch.5 data testing).
Label (also: target, output, ground truth)
The correct answer you want the model to predict. For loan approval: approved or rejected. For house prices: the actual sale price. Labels in the training dataset are provided by humans (or derived from historical data). Label quality is critical: wrong labels teach the model wrong things — a major focus of CT-AI Chapter 5 (Input Data Testing).
Training Example (also: data point, sample, observation)
One row in your dataset: one complete set of features plus its label. A training dataset might have 100,000 such rows. The model learns by processing all of these examples and adjusting its weights to minimise prediction errors.
Java — Conceptual Feature-Label structure in a training dataset
// A training example for spam classification
public class EmailTrainingExample {

    // ── FEATURES (inputs) ────────────────────────────────────
    int    wordCount;         // total words in email
    double freqOfWord_FREE;  // how often "FREE" appears (per 100 words)
    double freqOfWord_CLICK; // how often "CLICK" appears
    int    numLinks;          // number of hyperlinks in email
    boolean hasAttachment;  // does it have an attachment?
    String senderDomain;    // domain of sender email address

    // ── LABEL (the correct answer for training) ──────────────
    boolean isSpam;
    // This was determined by a human labeller who read the email
    // and marked it spam=true or spam=false.
    // Quality of this label is critical — CT-AI Ch.5 covers label
    // correctness testing and inter-annotator agreement.
}

// Training dataset = List<EmailTrainingExample> with 500,000 rows
// Model learns: which feature combinations correlate with isSpam=true?

Part 2 — ML Fundamentals

Supervised Learning — Learning with a Teacher

Supervised learning is the most common ML paradigm and the primary focus of CT-AI testing. The word "supervised" means the training data includes the correct answers (labels) — the model is supervised by this ground truth during training.

The Two Tasks of Supervised Learning

Classification
  • Output: a discrete category / class
  • Examples: spam / not-spam, cat / dog / bird, approve / reject
  • Binary classification: exactly 2 output classes (most common in exam examples)
  • Multi-class: 3+ classes (e.g., digit recognition: 0–9)
  • Key metrics: Accuracy, Precision, Recall, F1-score (Ch.3 deep dive)
  • Tester focus: confusion matrix, threshold selection, class imbalance
vs
Regression
  • Output: a continuous numerical value
  • Examples: house price ($238,350), tomorrow's temperature (22.3°C), stock return (3.7%)
  • Key metrics: MAE, MSE, RMSE
  • Tester focus: error tolerance ranges, outlier predictions, distribution of errors
  • CT-AI focus: regression metrics are less emphasised than classification metrics in the exam
Java — Conceptual Classification vs Regression — output type difference
// CLASSIFICATION — output is a CLASS (category)
public enum SpamLabel { SPAM, NOT_SPAM }

public SpamLabel classifyEmail(double[] features) {
    double spamProbability = model.predict(features);  // e.g., 0.87
    return spamProbability > 0.5
        ? SpamLabel.SPAM
        : SpamLabel.NOT_SPAM;
    // The threshold (0.5) is a design decision.
    // Changing it affects Precision vs Recall tradeoff (CT-AI Ch.3).
}

// REGRESSION — output is a NUMBER (continuous)
public double predictHousePrice(double[] features) {
    return model.predict(features);  // e.g., 238350.72 (dollars)
    // There's no threshold decision here.
    // Correctness is measured by how far off the prediction is
    // from the actual sale price (MAE, RMSE etc.)
}

Part 2 — ML Fundamentals

Unsupervised Learning — Finding Hidden Structure

Unsupervised learning operates on data with no labels. There is no "correct answer" to learn from. Instead, the algorithm discovers hidden structure or patterns in the raw feature space.

💡 The Key Intuition

Supervised: "I'll show you 10,000 labelled cat photos and dog photos — you learn the difference."
Unsupervised: "Here are 10,000 photos with no labels — you tell me what groups or patterns you see."
The algorithm finds structure humans didn't pre-specify.

Common Unsupervised Tasks

Clustering e.g., K-Means, DBSCAN
Groups data points into clusters based on similarity. Example: An e-commerce company has 5 million customers with purchase history, demographics, and browsing data — no labels. K-Means clustering might discover 4 natural customer segments: "budget shoppers," "premium brand loyalists," "occasional gift-buyers," and "tech enthusiasts." The company didn't define these segments — the algorithm found them. Used for: customer segmentation, document grouping, anomaly detection.

Testing challenge: No ground truth labels mean you can't use a confusion matrix. Quality is measured by internal metrics like silhouette score — subjective and domain-dependent.
Dimensionality Reduction e.g., PCA, t-SNE
Reduces hundreds of features down to 2–3 while preserving as much information as possible. Used for: visualising high-dimensional data, removing noise from datasets, preprocessing before supervised learning. PCA is the classic example — it finds new axes in feature space that capture the most variance.
Association Rule Mining
Discovers items that frequently co-occur. Classic example: "customers who buy diapers also tend to buy beer on Friday evenings" (the famous supermarket basket analysis). Used for: product recommendation, cross-selling strategies, fraud pattern detection.

Part 2 — ML Fundamentals

Reinforcement Learning — Learning by Doing

Reinforcement Learning (RL) is fundamentally different from both supervised and unsupervised learning. There is no dataset of examples. Instead, an agent learns by interacting with an environment, taking actions, and receiving feedback in the form of rewards or penalties.

Reinforcement Learning — The Agent-Environment Loop
Environment
Game board, robot world, stock market
State (s)
Current situation observed by agent
Agent
The ML model choosing actions
Action (a)
Move left, place bid, adjust motor
Reward (r)
+1 for win, -1 for loss, 0 for neutral

The agent's goal: learn a policy (strategy) that maximises cumulative reward over time

Policy
The strategy the agent uses to choose actions given the current state. The goal of RL training is to find the optimal policy.
Reward Signal
Feedback from the environment after each action. Can be sparse (reward only at game end) or dense (reward after every step). Reward design is crucial and difficult — a poorly designed reward can lead to unexpected or harmful agent behaviour.
Exploration vs Exploitation
Should the agent try new actions (explore) to potentially find better strategies, or stick with what it knows works (exploit)? This tradeoff is a core challenge in RL. Testing insight: RL agents can exhibit unexpected emergent behaviours when deployed in real environments that differ slightly from training — a significant robustness testing concern.

Real examples: AlphaGo (played millions of Go games against itself), OpenAI Five (Dota 2 game-playing), robotics arm control, dynamic ad bidding systems, and — increasingly relevant — RLHF used to align LLMs like ChatGPT and Claude to human preferences.

🎯 CT-AI Exam Focus for RL

RL appears in the syllabus as a category to recognise (K1/K2). You won't be asked to implement RL algorithms. Focus on: the agent-environment-reward loop concept, and why RL systems are particularly hard to test — emergent behaviour in novel environments, reward function quality, and the fact that you may not know the optimal policy to compare against.


Part 2 — ML Fundamentals

The Training Process — Step by Step

This is the core mechanical process of ML. Understanding it is essential for CT-AI because many testing concepts (overfitting, hyperparameter tuning, dataset splits) only make sense once you understand what training actually does.

The Big Picture

Training is fundamentally an optimisation problem. You have a model with many weights. You want those weights to be set to values that make the model's predictions as accurate as possible. Training is the iterative process of finding those values.

1
Initialise Weights Randomly
Before training, all the weights in the model are set to small random numbers. The model at this point is useless — it makes random predictions. This is the starting point of the optimisation journey. The exact initialisation method can affect how well training converges (a hyperparameter decision).
2
Forward Pass — Make a Prediction
Take one (or a batch of) training example(s). Run the features through the model's current weights to produce a predicted output. For example, the model might predict spamProbability = 0.3 for an email that is actually spam (label = 1.0). The prediction is far off — but that's expected at the start.
3
Calculate Loss (Error)
Compare the prediction to the actual label. The loss function (also called cost function or error function) quantifies this difference as a single number. For classification, a common loss is cross-entropy loss. For regression, common losses are MSE or MAE. A high loss = bad predictions. The training goal is to minimise this number.
4
Backward Pass — Backpropagation
Using calculus (specifically, the chain rule of differentiation), backpropagation calculates the gradient of the loss with respect to every weight. A gradient tells you: "if I increase this weight slightly, does the loss go up or down, and by how much?" You don't need to understand the calculus — just the concept: each weight gets a signal saying which direction to move to reduce the error.
5
Weight Update — Gradient Descent
Each weight is nudged in the direction that reduces the loss. The size of the nudge is controlled by the learning rate (α) — a critical hyperparameter you'll see in the exam context.
new_weight = old_weight − α × gradient Imagine a ball rolling down a hill — gradient descent finds the valley (minimum loss). The learning rate controls the step size: too large and the ball overshoots the valley and bounces around, too small and it takes forever to reach the bottom.
6
Repeat for All Examples — One Epoch
Repeat steps 2–5 for every training example in the dataset. One complete pass through the entire training dataset is called an epoch. After one epoch, every training example has contributed to updating the weights.
7
Repeat for Many Epochs — Convergence
Run many epochs. After each epoch, the model should be making progressively better predictions. Training continues until the loss stops improving significantly (convergence) or a set number of epochs is reached. Typical training runs might be 10 to hundreds of epochs for traditional ML, and months of continuous training for large LLMs.
Java — Conceptual Pseudocode The training loop — skeleton structure
// The Training Loop — conceptual skeleton
// Real ML frameworks (TensorFlow, PyTorch) hide most of this,
// but understanding it is essential for CT-AI

public void train(
        List<TrainingExample> dataset,
        int numEpochs,
        double learningRate    // α — a HYPERPARAMETER you set before training
) {
    // Step 1: initialise weights randomly
    model.initializeWeightsRandomly();

    for (int epoch = 0; epoch < numEpochs; epoch++) {

        double totalLoss = 0.0;

        for (TrainingExample example : dataset) {

            // Step 2: forward pass — predict
            double prediction = model.predict(example.features);

            // Step 3: calculate loss (how wrong was the prediction?)
            double loss = lossFunction.compute(prediction, example.label);
            totalLoss += loss;

            // Step 4: backward pass — compute gradients (which direction
            //         to nudge each weight to reduce the loss?)
            double[] gradients = model.computeGradients(loss);

            // Step 5: update weights — gradient descent
            //   new_weight = old_weight - (learningRate * gradient)
            model.updateWeights(gradients, learningRate);
        }

        // Log progress — we want loss to decrease each epoch
        System.out.printf("Epoch %d | Loss: %.4f%n", epoch, totalLoss / dataset.size());
    }
    // After training: model.weights now contain the learned values.
    // The model is ready for inference (making predictions on new data).
}

Part 2 — ML Fundamentals

Training vs Inference — Two Very Different Phases

These two phases of an ML system's life are fundamentally different in purpose, resource requirements, and testing implications. CT-AI has separate testing considerations for each.

🏋️ Training Phase
  • Purpose: Find optimal weights by minimising loss over training data
  • When: Done once (or periodically for model updates) — before deployment
  • Speed: Slow — hours, days, or months for large models
  • Compute: Massive GPU clusters; training GPT-4 cost ~$100M
  • Data needed: The full labelled training dataset
  • Testing focus: Dataset quality, bias, train/val/test split, overfitting detection, algorithm selection, hyperparameter tuning
  • Who does it: ML engineers, data scientists — but testers review the process
vs
🚀 Inference Phase
  • Purpose: Use trained model to make predictions on new, unseen data
  • When: Continuously in production, for every user request
  • Speed: Fast — milliseconds per prediction (the whole point)
  • Compute: Much smaller — often a single server or even a mobile device
  • Data needed: Just the current input features
  • Testing focus: Functional correctness, performance, adversarial inputs, drift detection, integration with surrounding system
  • Who does it: The deployed model serving user requests
⚠️ The Training-Serving Skew Problem

A model can perform well on the training and test datasets but behave unexpectedly in production. This happens when the production data distribution differs from what the model saw during training. For example: a fraud detection model trained on 2022 transaction data may struggle with 2024 fraud patterns that didn't exist during training. This is called distribution shift or drift — a major CT-AI topic in Chapters 5 and 6 (data testing and model testing respectively).


Part 2 — ML Fundamentals

Hyperparameters — Settings You Choose Before Training

A hyperparameter is a configuration setting that you (or the ML engineer) choose before training begins. Hyperparameters are not learned from data — they control how the learning process itself works.

💡 Parameters vs Hyperparameters — Critical Distinction

Parameters (weights, biases) — learned FROM the training data automatically.
Hyperparameters — set BY the developer BEFORE training. They control the training process itself.

HyperparameterWhat it controlsToo high →Too low →Typical range
Learning Rate (α) Size of each weight update step during gradient descent Overshoots, diverges — loss explodes Learns too slowly, might get stuck 0.0001 to 0.1
Number of Epochs How many full passes through the training data Overfitting — memorises training data Underfitting — hasn't learned enough 10 to 1000+
Batch Size How many examples are processed before each weight update Stable but slow; needs more memory Noisy updates; might not converge well 16 to 512
Number of Layers / Neurons Architecture depth and width — model capacity Overfit on small data; slower inference Underfit — can't learn complex patterns Domain-specific
Regularisation (λ) Penalty for large weights — prevents overfitting Underfitting — model too constrained Overfitting — no regularisation effect 0.0001 to 0.1

Hyperparameter Tuning — Finding the Right Values

Finding good hyperparameters is itself a process that requires running multiple training experiments. Common strategies: Grid Search, Random Search, and Bayesian Optimisation. The validation dataset (separate from training and test) is used to evaluate performance during hyperparameter tuning — this is why you need three separate datasets, which CT-AI Chapter 3 and 5 cover in depth.


Part 2 — ML Fundamentals

Java: Full ML Pipeline — Putting It All Together

Here is a complete conceptual ML pipeline in Java pseudocode — from raw data to deployed inference. This ties together every concept from Part 2: features, training loop, evaluation, and inference. Real ML is done in Python with frameworks, but the structure is identical.

Java — Conceptual Pseudocode Full ML pipeline: data → train → evaluate → infer
// ══════════════════════════════════════════════════════════════
//  FULL ML PIPELINE — Spam Classification Example
//  This illustrates the complete lifecycle that CT-AI tests at
//  each stage (data testing, model testing, deployment testing)
// ══════════════════════════════════════════════════════════════

public class MLPipeline {

    public static void main(String[] args) {

        // ── STEP 1: Load raw data ─────────────────────────────────
        // CT-AI Ch.5 (Input Data Testing) tests this stage:
        //   - Is the data biased?
        //   - Are labels correct?
        //   - Is the data representative of production?
        List<Email> rawEmails = dataLoader.load("emails.csv");

        // ── STEP 2: Feature extraction ────────────────────────────
        // Convert raw emails into numerical feature vectors the model can process
        List<double[]> features = rawEmails.stream()
            .map(FeatureExtractor::extract)  // word freq, link count, sender domain etc.
            .collect(Collectors.toList());

        double[] labels = rawEmails.stream()
            .mapToDouble(e -> e.isSpam ? 1.0 : 0.0)
            .toArray();

        // ── STEP 3: Split dataset into 3 sets ────────────────────
        //   Training set:   80% — used to train the model
        //   Validation set: 10% — used for hyperparameter tuning
        //   Test set:       10% — used ONCE for final evaluation
        //
        //   CT-AI Ch.3 and Ch.5 cover why all 3 sets are needed.
        //   The test set must NEVER be seen during training or tuning —
        //   using it for tuning would give falsely optimistic results.
        DataSplit split = DataSplitter.split(features, labels,
            /*trainRatio=*/ 0.80,
            /*valRatio=*/   0.10,
            /*testRatio=*/  0.10,
            /*shuffle=*/    true   // always shuffle to avoid ordering bias
        );

        // ── STEP 4: Define model and hyperparameters ──────────────
        //   These are chosen BEFORE training — not learned from data
        HyperParameters hp = new HyperParameters();
        hp.learningRate = 0.001;   // step size for gradient descent
        hp.numEpochs    = 50;      // training passes through the data
        hp.batchSize    = 32;      // examples per weight update
        hp.hiddenLayers = 2;       // neural network depth

        NeuralNetworkModel model = new NeuralNetworkModel(hp);

        // ── STEP 5: TRAINING ──────────────────────────────────────
        //   Forward pass → compute loss → backprop → update weights
        //   Repeated for numEpochs passes over the TRAINING set
        model.train(split.trainFeatures, split.trainLabels);

        // ── STEP 6: Evaluate on VALIDATION set ───────────────────
        //   Used to detect overfitting and tune hyperparameters.
        //   If training accuracy is 99% but validation is 70%,
        //   the model is OVERFITTING (memorising, not generalising).
        Metrics valMetrics = model.evaluate(split.valFeatures, split.valLabels);
        System.out.printf("Validation Accuracy: %.2f%%%n", valMetrics.accuracy * 100);

        // ── STEP 7: Final evaluation on TEST set ─────────────────
        //   The test set is used EXACTLY ONCE for the honest final score.
        //   CT-AI Ch.3 covers the full confusion matrix metrics computed here.
        Metrics testMetrics = model.evaluate(split.testFeatures, split.testLabels);
        System.out.printf("Test Accuracy:  %.2f%%%n", testMetrics.accuracy  * 100);
        System.out.printf("Test Precision: %.2f%%%n", testMetrics.precision * 100);
        System.out.printf("Test Recall:    %.2f%%%n", testMetrics.recall    * 100);
        System.out.printf("Test F1-Score:  %.2f%%%n", testMetrics.f1        * 100);

        // ── STEP 8: Save and deploy model ────────────────────────
        //   CT-AI Ch.7 covers deployment testing:
        //   - Model format conversion (ONNX, TensorFlow SavedModel)
        //   - Model compression / quantisation (reduces size for edge devices)
        //   - Re-testing is required after format/compression changes
        //   - Monitoring after deployment: performance drift, data drift
        model.save("spam_model_v1.onnx");

        // ── STEP 9: INFERENCE — using the deployed model ──────────
        //   Completely separate from training. Just uses learned weights.
        Email newEmail = emailService.receive();
        double[] newFeatures = FeatureExtractor.extract(newEmail);
        double spamProb = model.predict(newFeatures);
        boolean isSpam = spamProb > 0.5;  // classification threshold

        System.out.printf("Email '%s' → spam probability: %.2f → %s%n",
            newEmail.subject, spamProb, isSpam ? "SPAM" : "NOT SPAM");
    }
}

Summary

Tester Takeaways — Why This All Matters

Everything in Part 1 and Part 2 directly maps to testing challenges you'll encounter in the CT-AI syllabus chapters. Here's the connection bridge:

Concept learned hereCT-AI chapter where it mattersWhy it creates a testing challenge
AI outputs are probabilistic Ch.4 — Testing AI Systems Traditional pass/fail test oracles don't work; need statistical approaches
Model is a black box Ch.2 — Quality Characteristics Explainability and transparency become quality requirements to test for
Labels might be wrong Ch.5 — Input Data Testing A model trained on wrong labels produces wrong learned behaviour; label correctness must be tested
Data distribution matters Ch.5 — Input Data Testing Biased or unrepresentative data produces biased models; data must be tested before training
Overfitting — too many epochs Ch.6 — Model Testing A model that memorises training data fails on real-world inputs; overfitting is a model defect
Training vs test dataset split Ch.3 — Machine Learning Contaminating test data with training info gives falsely optimistic evaluation metrics
Drift — distribution changes over time Ch.6 — Model Testing A model accurate at deployment may degrade as the world changes; requires monitoring and re-testing
Hyperparameters affect behaviour Ch.3 — ML Workflow Hyperparameter selection is a design decision with testing implications (reproducibility, fairness)

Exam

Exam Insights for This Prerequisite Material

🎯 Direct Exam Relevance

Phase 0 is prerequisite material — it doesn't appear as standalone exam questions. However, every question in CT-AI chapters 1–7 assumes this knowledge. If you can't picture what training data is, or why the test oracle problem exists, you'll misread scenario questions. These concepts are the vocabulary the exam questions are written in.

AI vs ML vs DL
Guaranteed to appear in Ch.1 questions. Remember: All DL is ML, All ML is AI — but not vice versa. "A decision tree that learns from data" = ML but NOT DL. "A hand-coded rule system" = AI but NOT ML.
Narrow / General / Super AI
K1 recall. Know that everything that exists today is Narrow AI. AGI and ASI do not exist. Common trap: "advanced AI" or "powerful AI" does not mean General AI — it's still Narrow.
Classification vs Regression
Appears frequently as scenario context. If the output is a category → classification (confusion matrix applies). If the output is a number → regression (MAE/MSE applies). Don't mix up the metrics.
Parameters vs Hyperparameters
A trap question will describe a setting and ask if it's learned from data or set by the developer. "Learning rate" = hyperparameter (set before training). "Weight values in the network" = parameters (learned during training).
Training vs Inference
Ch.7 (deployment testing) questions are based on understanding that training and inference are different phases. Testing after deployment is inference-phase testing. Testing the training process itself is a different activity.

Reference

Quick Reference Card — AI-PRE-01 in One View

AI Definition
Systems that mimic human intelligence — learned OR rule-based
ML Definition
Subset of AI — learns patterns from data without explicit rules
Deep Learning
Subset of ML — uses deep multi-layer neural networks
Narrow AI
Only type that exists today — one task, done well
TermOne-line definitionExam trap to avoid
FeatureInput variable fed into the modelFeatures ≠ labels; features are inputs, labels are answers
LabelThe correct answer in the training datasetLabels can be wrong — that's why Ch.5 tests them
Weight / ParameterLearnable number inside the model, determined by trainingParameters are LEARNED; hyperparameters are SET
HyperparameterConfiguration set before training (learning rate, epochs)Not learned from data — set by the developer
Loss FunctionMeasures how wrong the model's predictions areMinimising training loss ≠ good generalisation (overfitting)
EpochOne complete pass through the training datasetToo many epochs → overfitting; too few → underfitting
TrainingThe process of finding optimal weights by minimising lossTraining the model ≠ testing the model
InferenceUsing the trained model to make predictions on new dataInference is what happens in production — this is what users experience
Supervised MLLearns from labelled examples (features + labels)Supervised ≠ always classification; regression is also supervised
Unsupervised MLFinds structure in unlabelled dataNo labels means no confusion matrix; evaluation is harder
Reinforcement LearningAgent learns by trial-and-error via rewardsRL has no dataset — it learns from environment interactions
OverfittingModel memorises training data but fails on new dataHigh training accuracy + low validation accuracy = overfitting
DriftProduction data distribution shifts away from training data over timeDrift doesn't mean the model broke — the world changed
✅ You're ready for AI-PRE-02

You now have the mental model needed to understand how neural networks compute their outputs (the forward pass in detail), what activation functions do, how LLMs generate text token by token, why outputs are probabilistic, and what the "black box" problem really means at an architecture level. That's exactly what AI-PRE-02 covers.