Chapter 1 / 16

AI, Machine Learning and Generative AI Fundamentals

Beginner 2โ€“3 h

Learning objectives

  • Distinguish AI, machine learning, deep learning and generative AI precisely
  • Explain supervised, unsupervised, self-supervised and reinforcement learning
  • Describe the machine-learning workflow from data to deployment
  • Judge when ML is the right tool โ€“ and when it is not

Introduction

Artificial intelligence is everywhere in today's software โ€“ but the words around it are often used loosely. This chapter builds a precise foundation: what AI, machine learning, deep learning and generative AI actually are, how they relate, how a model learns from data, and how an ML project is structured from the first dataset to production. You do not need any prior AI knowledge; basic programming experience is enough.

Traditional software follows rules a developer writes down. Many real problems resist explicit rules: recognising a handwritten digit, judging whether an e-mail is spam, translating a sentence. Machine learning exists because for such problems it is easier to collect examples of the desired behaviour than to write the rules. The program โ€“ the model โ€“ is then derived from data by an optimisation procedure. Generative AI extends this idea: instead of predicting one label, models learn the structure of data well enough to produce new text, images or code.

AI, ML, deep learning and generative AI โ€“ how they relate

Artificial intelligence (AI) is the broad field of building systems that perform tasks we associate with intelligence: perception, language, planning, decision-making. It includes rule-based expert systems and search algorithms as well as learning systems.

Machine learning (ML) is the part of AI in which behaviour is learned from data rather than programmed. An ML model is a function with adjustable parameters; training adjusts these parameters so the function performs well on examples.

Deep learning is machine learning with neural networks of many layers. Depth lets a model learn its own intermediate representations โ€“ edges, shapes and objects in images, or syntax and meaning in text โ€“ instead of relying on hand-crafted features.

Generative AI uses (mostly deep) models that produce new content. Large language models (LLMs) generate text one token at a time by repeatedly predicting a probability distribution over the next token. They are generative, but they are still ML models: trained on data, evaluated on data, and limited by data.

  • AI โŠƒ machine learning โŠƒ deep learning; generative AI is a family of (mostly deep-learning) models defined by what they output.
  • An LLM does not look facts up: it produces likely continuations. Retrieval (chapter 10) and tools (chapter 12) are added when facts must be correct and current.

How models learn: four paradigms

Supervised learning learns a mapping from inputs to known outputs (labels): house features to price (regression) or e-mail text to spam / not spam (classification). It needs labelled examples, which are often expensive.

Unsupervised learning finds structure without labels: clustering customers into groups, reducing dimensions, detecting anomalies. The algorithm optimises a criterion such as compact clusters, not a known answer.

Self-supervised learning creates labels from the data itself. A language model is trained to predict the next token of real text โ€“ every text is its own training signal. This is why LLMs can be pre-trained on huge unlabelled corpora.

Reinforcement learning learns by acting in an environment and receiving rewards. Reinforcement learning from human feedback (RLHF) and related methods are used to align LLM behaviour with human preferences after pre-training.

What 'learning' means internally

Every learning procedure has three parts: a model family (for example, all linear functions, or all neural networks of a given architecture), a loss function that measures how wrong a prediction is, and an optimiser that changes the parameters to reduce the loss on the training data.

For most modern models the optimiser is a variant of gradient descent: compute how the loss changes when each parameter changes slightly (the gradient), then move every parameter a small step in the direction that reduces the loss. Chapter 2 implements this by hand; chapter 3 lets PyTorch compute the gradients.

The goal is not to do well on the training data but on new data โ€“ generalisation. A model that memorises the training set (overfitting) fails on unseen examples. This is why data is split into training, validation and test sets, and why the test set is used only once at the end.

The machine-learning workflow

1. Define the problem and the metric: what decision does the model support, and how is success measured (accuracy, precision/recall, cost of errors)?

2. Collect and understand the data: sources, quality, bias, legal constraints (personal data!).

3. Prepare features and splits: clean the data, split it into train / validation / test without leakage (no information from the test set may influence training).

4. Train baselines first: a simple model or even a rule tells you whether a complex model is worth its cost.

5. Evaluate honestly on held-out data, analyse errors, iterate.

6. Deploy, monitor and retrain: data in production drifts away from the training data, so performance must be measured continuously (chapter 16).

When to use ML โ€“ and when not

ML fits when the rules are hard to write down, examples are available, some error rate is acceptable, and the pattern is stable enough to learn.

Prefer plain code when the rules are known and must be exact (tax calculation, access control), when there is no data, or when every decision must be fully explainable and deterministic.

Prefer a pretrained model (an LLM or embedding model) over training your own when the task is general (summarising, classifying text, extracting fields) and you have little labelled data. Train or fine-tune when the domain is special and quality must exceed what prompting achieves.

Key terminology

Model
A parameterised function that maps inputs to outputs; its parameters are learned from data.
Parameters (weights)
The numbers inside a model that training adjusts. A small classifier has dozens; current LLMs have billions.
Loss function
A number measuring how wrong the model's predictions are on given examples; training minimises it.
Generalisation
Performance on new, unseen data โ€“ the actual goal of training.
Overfitting
The model fits the training data, including its noise, so well that it performs worse on new data.
Inference
Using a trained model to make predictions; no parameters change.
Token
The unit an LLM reads and writes โ€“ a word, part of a word or a character, depending on the tokenizer.
Foundation model
A large model pre-trained on broad data that is adapted to many tasks by prompting or fine-tuning.

Architecture diagrams

From AI to generative AI

flowchart LR
  AI[Artificial intelligence - rules, search, learning] --> ML[Machine learning - learned from data]
  ML --> DL[Deep learning - multi-layer neural networks]
  DL --> GEN[Generative AI - produces text, images, code]
  GEN --> LLM[Large language models]
Each field is a subset of the one before; generative AI is defined by producing new content.

The ML workflow, step by step

flowchart LR
  P[1 Problem and metric] --> D[2 Data collection]
  D --> S[3 Preparation and splits]
  S --> T[4 Training - baseline first]
  T --> E[5 Evaluation on held-out data]
  E -->|not good enough| S
  E --> DEP[6 Deployment]
  DEP --> MON[Monitoring]
  MON -->|drift| D
Evaluation and monitoring loop back: models are improved iteratively and retrained when data drifts.

Practical examples

Spam filter (supervised classification). Thousands of e-mails labelled spam / not spam train a classifier. The metric is not just accuracy: a legitimate e-mail lost in the spam folder costs more than a spam e-mail that gets through, so precision on the spam class matters most.

Customer segments (unsupervised clustering). Purchase histories without labels are clustered into groups; marketing then interprets the groups. The algorithm does not know what the groups mean โ€“ humans do.

Support assistant (generative AI). An LLM drafts answers to support tickets. Because it can produce plausible but wrong statements, it is combined with retrieval of the actual product documentation (RAG) and a human approves each answer.

Working code

Supervised and unsupervised learning on a real dataset

Tested with: Python 3.13, scikit-learn 1.9

# pip install scikit-learn
# python ch1_classic_ml.py
"""Chapter 1 โ€“ supervised vs. unsupervised learning with scikit-learn."""
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.cluster import KMeans

X, y = load_iris(return_X_y=True)            # 150 flowers, 4 measurements, 3 species
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y)

# Supervised: learn a mapping from measurements to the known label.
clf = LogisticRegression(max_iter=1000)
clf.fit(X_train, y_train)
print("test accuracy:", round(accuracy_score(y_test, clf.predict(X_test)), 3))

# Unsupervised: find groups without using the labels at all.
kmeans = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
print("cluster sizes:", sorted(int((kmeans.labels_ == k).sum()) for k in range(3)))
Expected output
test accuracy: 0.947
cluster sizes: [38, 50, 62]

The classifier learns from 112 labelled flowers and is tested on 38 it has never seen. K-means finds three groups without labels; the sizes differ from the true 50/50/50 because two species overlap in their measurements โ€“ the algorithm optimises compactness, not species.

Practice Lab

Work through the exercises in order; each builds on the code above. Solutions are hidden until you open them.

Why a test set?

Beginner

Train the classifier and print the accuracy on the training data as well as on the test data. Then change test_size to 0.5 and repeat.

  • Use clf.predict(X_train).
  • Training accuracy is usually higher โ€“ why?
Show solution
print("train:", accuracy_score(y_train, clf.predict(X_train)))
print("test: ", accuracy_score(y_test, clf.predict(X_test)))
# The model has seen the training data, so its training accuracy is optimistic.
# Only the held-out test set estimates performance on new flowers.

Compare against a baseline

Intermediate

Use sklearn.dummy.DummyClassifier(strategy='most_frequent') as a baseline. How much better is logistic regression?

  • A baseline answers: is learning worth it at all?
Show solution
from sklearn.dummy import DummyClassifier
base = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print("baseline:", round(accuracy_score(y_test, base.predict(X_test)), 3))  # 0.316

Evaluate clusters without labels

Advanced

Compute the silhouette score (sklearn.metrics.silhouette_score) for k = 2โ€ฆ6 clusters. Which k does the score prefer, and does it match the three species?

  • Higher silhouette = more compact, better separated clusters.
Show solution
from sklearn.metrics import silhouette_score
for k in range(2, 7):
    labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)
    print(k, round(silhouette_score(X, labels), 3))
# k = 2 scores highest: two of the three species overlap so much that,
# without labels, two groups describe the data best.

Practise with OOHM

Reinforce the chapter's vocabulary and concepts with dictation, rapid typing and quizzes on this topic.

Please log in to use this AI feature.

Knowledge check

1. Which statement about the relationship between AI and machine learning is correct?
2. What makes deep learning 'deep'?
3. How is a large language model pre-trained on unlabelled text?
4. Which task is a typical unsupervised learning task?
5. What does a loss function measure?
6. Why is a separate test set needed?
7. What is overfitting?
8. What happens during inference?
9. When is plain code better than machine learning?
10. An LLM writes a confident but false statement. What is the most robust mitigation?

Common mistakes and troubleshooting

Excellent accuracy in development, poor results in production.
Cause: Data leakage: information from the test set (or the future) influenced training, e.g. normalising with statistics of the whole dataset.
Fix: Split first, then fit every preprocessing step on the training data only (scikit-learn Pipeline helps).
99 % accuracy, but the model is useless.
Cause: Imbalanced classes: if 99 % of transactions are legitimate, always predicting 'legitimate' scores 99 %.
Fix: Use precision, recall and a confusion matrix, and compare with a baseline.
The LLM 'knows' outdated or invented facts.
Cause: Generative models reproduce patterns from training data; they have no live knowledge.
Fix: Retrieve current sources (RAG) or call tools, and show sources to users.

Summary

  • AI is the field; machine learning learns behaviour from data; deep learning uses deep neural networks; generative AI produces new content.
  • Learning = model family + loss function + optimiser; the goal is generalisation, measured on held-out data.
  • Supervised, unsupervised, self-supervised and reinforcement learning differ in where the training signal comes from.
  • Start every project with the problem, the metric and a baseline.

Learning outcomes

  • You can explain the AI vocabulary precisely to colleagues and stakeholders.
  • You can train and evaluate a first classifier and judge its result against a baseline.

Official documentation