← MAAI Study Hub

Two papers per lecture. The figures move; they hold still if your device asks for reduced motion.

Lecture 1 · Introduction to AI, ML, DL and AI Agents

MAAI801 Foundation of AI · study summary
Paper 1
of 2

One cycle, two kinds of machinery: a driver braking for a pedestrian, and a self-driving car doing the same.

1. What is intelligence?

Intelligence is the ability to acquire and apply knowledge: learn, understand, reason, solve problems, decide, adapt. Knowing a lot is not enough.

Human intelligence is a cycle (figure above), fed by memory and experience.

Calculator vs self-driving car: both compute, but the calculator runs fixed rules while the car perceives, decides and adapts in a changing world. A machine is intelligent when it uses data and experience to reach a goal in a changing environment.

2. What is AI?

AI is the field of computer science that builds machines able to do tasks that normally need human intelligence.

  • It need not think like a human: chess AI wins by searching millions of moves.
  • AI judges by the behavioural view (what it does), not the cognitive view (how it thinks).
  • AI ≠ consciousness or emotions. It can perceive, learn, predict, plan, decide, act.
  • Value: speed, scale, automation, prediction, personalisation, augmenting people.

3. Types of AI: two questions about one system

Capability: what can it do?Functionality: how does it operate?
now ANI narrow, one domain (radiology AI)now Reactive: current input only
idea AGI human-level in every domainnow Limited memory: current + past data
idea ASI beyond human abilityresearch Theory of mind · idea Self-aware

A self-driving car is ANI + limited memory. Narrow does not mean simple.

4. From rules to Machine Learning

Chess engines, GPS and weather apps run programmed algorithms. Rules break on fraud detection, recommendations and face recognition: too many cases to write.

Machine Learning is the subset of AI that learns patterns from data instead of being given every rule. We choose the algorithm; it learns the rules: data → patterns → model → prediction. Like a child: examples, patterns, feedback.

5. Types of learning and problems

LearningDataExample
Supervisedlabelledneeds support? yes/no
Unsupervisedno labelsgroup similar students
Reinforcementreward ±1tutor learns what helps
ProblemPredictsModels
Classificationcategorytree, forest, SVM, logistic
Regressionnumberlinear, tree, SVR
ClusteringgroupsK-means, DBSCAN

Decide HOW (learning) and WHAT (problem) first.

Remember: AI is judged by intelligent behaviour, not by human-like thought. ML gets that behaviour by learning rules from data instead of having them written.
MAAI801 · Lecture 1Intelligence → AI → types of AI → ML

Building ML, Deep Learning, Agents and the Turing Test

Case study: predicting UOWD students who need academic support (3,000 students)
Paper 2
of 2

6. The 7-step ML workflow

Excel, hand rules and manual review don't scale. Labelled history → supervised classification.

  1. Define: target = needs support (yes/no); success = catch the at-risk.
  2. Collect: grades, attendance, LMS logins, forum posts. Features in, target out.
  3. Prepare: clean (missing, duplicates, outliers); one-hot encode; min-max scale x′ = (x − min)/(max − min); engineer features (late-submission rate).
  4. Split without leakage; test set untouched while tuning.
    Train 70%Val 15Test 15
  5. Choose: decision tree, interpretable rules ("attendance < 70% and quiz < 60% → at risk").
  6. Train on train, tune (max depth) on validation.
  7. Evaluate once on test, deploy, act, monitor drift, retrain.

7. Confusion matrix and metrics

Predicted no
Predicted yes
Actual no
TN 5
FP 0
Actual yes
FN 2
TP 3
Accuracy = (TP+TN)/all80%
Precision = TP/(TP+FP)100%
Recall = TP/(TP+FN)60%
F1 = 2PR/(P+R)0.75

Recall matters most: a missed at-risk student (FN) costs more than a false alert. ML is a continuous cycle, not magic.

8. Deep Learning: the model learns its own features

Hand-made features fail on images, audio and free text. Deep Learning (subset of ML) uses neural networks with many layers, each learning more abstract features from raw data: vision, speech, NLP, generative AI. More complex is not automatically better.

Traditional MLDeep Learning
Datatables, lesstext, images, audio, more
Featureshand-designedlearned
Cost / claritylow / clearGPUs / "black box"

9. AI Agents: from prediction to action

ML and DL predict. An AI agent perceives, decides, acts toward a goal, then adapts, often using ML/DL inside. Seeing "Student X: high risk (85%)", it emails resources, alerts the advisor and books a meeting. Predictions inform action; agents make it happen.

10. The Turing Test (Alan Turing, 1950) and the workshop

A judge chats by text with a hidden human and a hidden machine; if they can't tell which is which, the machine passes. Limits: text only, no perception or action, and passing ≠ understanding. Workshop: groups of 3 (judge, human, experimenter with an AI tool), 5 shared questions, anonymised answers, reveal, discuss; one report /100.

One line: AI is the field, ML learns from data, DL learns the features too, agents act on predictions.
MAAI801 · Lecture 1Workflow → metrics → DL → agents → Turing Test

Lecture 2 · Supervised Learning: Classification

Single methods: logistic regression, decision trees, decision stumps
Paper 1
of 2

1. Supervised learning and classification

Learn a mapping from features X to a known target y from labelled examples, then predict y for unseen ones. Classification predicts a category (at risk, spam); regression a number. Binary = 2 classes, multiclass = 3+.

Single methodsEnsemble methods
Logistic regression: class probabilityBagging: independent models vote (Random Forest)
Decision tree: tree of rulesBoosting: each model fixes earlier errors (AdaBoost)
Decision stump: one split, weak learnerStacking: a meta-learner combines models

2. Logistic regression: a classifier in 4 steps

  1. Features as numbers: encode categories, e.g. LMS Medium → one-hot, so x = [60, 64, 0, 1, 0]; label y = 1 (at risk).
  2. Linear score z = β₀ + β₁x₁ + … + βₙxₙ. Each β is learned; a positive β raises z, a negative one lowers it.
  3. Sigmoid p = σ(z) = 1/(1 + e⁻ᶻ) turns any z into a probability: z < 0 → p < 0.5, z = 0 → 0.5, z > 0 → p > 0.5.
  4. Threshold: p ≥ 0.5 → at risk (1), else not at risk (0).

Learning: compute p, measure log loss, update β by gradient descent, repeat.

1.89 0.50
0.87p ≥ threshold → At risk

Starts at student S9 (z = 1.89). Move the threshold.

3. Decision trees

A tree asks a sequence of questions. Root node = first question, internal nodes = more questions, branches = answers, leaf nodes = final class. It picks the question that splits the classes into the purest groups.

Node (at risk : not)Gini 1 − Σp²Entropy −Σp log₂p
4 : 0 pure00
3 : 1 partly mixed0.3750.811
2 : 2 evenly mixed0.5 (max)1 (max)

Information gain = entropy(parent) − weighted entropy(children). Pick the lowest weighted Gini (CART) or highest gain (ID3, C4.5).

Game: pick the first split for 8 students (4 at risk, 4 not).

Tap a question to see the groups it makes.

Recursive: split each mixed child until a stop rule: pure node, no features, too few samples, no gain, max depth.

4. Overfitting and pruning

A tree grown too deep memorises noise: great on training data, poor on new data. Too shallow underfits. Pruning keeps it simple:

  • Pre-pruning (stop early): max_depth, min_samples_split, min_samples_leaf, min_impurity_decrease.
  • Post-pruning: grow fully, then cut branches with little predictive power.

Trees: easy to explain, fast, nonlinear; but they overfit and shift with small data changes.

5. Decision stump

A tree of depth 1: one feature, one split, two leaves (e.g. "attendance < 70%?"). Fast and easy to read, but alone it underfits: a weak learner.

Many weak stumps combined make a strong model: the idea behind AdaBoost.

Remember: logistic regression scores, squashes and thresholds; a tree asks the question that leaves the purest groups, and pruning stops it from memorising.
MAAI801 · Lecture 2Logistic regression → trees → impurity → pruning → stumps

Ensemble Methods: Bagging, Boosting, Stacking

Many models together usually predict better than one
Paper 2
of 2

6. Ensembles: base learners combined into one prediction

BaggingBoostingStacking
Trainingparallel, bootstrap samplessequential, fixes earlier errorsdifferent models + meta-learner
Combinevote or averageweighted votemeta-learner decides
Goalless varianceless biascomplementary strengths
ExamplesRandom ForestAdaBoost, Gradient Boosting, XGBoostDT + RF + AdaBoost → meta

7. Bagging and Random Forest

Bootstrap sample: draw rows with replacement to the original size. Some repeat, some are left out, so each model sees different data. That diversity stabilises the vote.

Random Forest = bagging of decision trees + a random subset of features at each split. Classification takes the majority vote; regression averages.

Pros: robust, accurate, overfits less than one tree. Cons: less interpretable, more compute; cuts variance, not bias.

Try it: draw a bootstrap sample from students S1–S8

Student S6: 3 trees vote at risk, 2 not → forest says at risk.

8. Boosting and AdaBoost

Weak learners (often stumps) train in sequence; each round up-weights the examples the last got wrong.

  1. wᵢ = 1/N; train stump hₜ; εₜ = Σ w of mistakes.
  2. Vote αₜ = ½ ln((1 − εₜ)/εₜ); reweight w·e−αyh/Z.
  3. F(x) = Σ αₜhₜ(x), H = sign(F): > 0 → at risk.

Stop: T rounds, zero training error, ε ≥ 0.5, or validation stalls. Pros: accurate, cuts bias. Cons: sequential, noise and outliers get huge weight, needs tuning.

0.25
0.549Strong vote.

9. Stacking

Base models (DT, RF, AdaBoost) predict on out-of-fold data; their predictions become the features of a meta-learner. S9 → [+1, −1, +1] → meta-tree → at risk. Costs: complexity, an extra training stage.

Workshop code (scikit-learn)
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
models = [LogisticRegression(max_iter=1000), DecisionTreeClassifier(max_depth=3),
          RandomForestClassifier(n_estimators=100), AdaBoostClassifier(n_estimators=50)]
for m in models:
    print(type(m).__name__, m.fit(X_train, y_train).score(X_test, y_test))
One line: bagging votes in parallel, boosting corrects in sequence, stacking learns how to combine.
MAAI801 · Lecture 2Ensembles → Random Forest → AdaBoost → stacking

Lecture 3 · Supervised Learning: Regression

Data preparation, linear regression, cost and gradient descent
Paper 1
of 2

1. What is regression?

Supervised learning that predicts a continuous number from features. Same student, two tasks: classification says at risk; regression says final score 64.5%. The target decides the task.

Uses: house prices, sales forecasts, length of hospital stay, financial returns. Cycle: training data → model form → learning → prediction.

Inputs x are features or predictors; the target y is the output or response. "Independent" does not mean causal.

2. Prepare the data first

  1. Clean: missing (attendance blank), invalid (125%), impossible (−2 hours), duplicates. Verify before imputing.
  2. Encode categories with one-hot: Campus / Online / Hybrid → [1,0,0], [0,1,0], [0,0,1].
  3. Scale: z = (x − mean)/SD; attendance 70 with mean 75, SD 10 → −0.5. Helps gradient descent.
  4. Split 80% train / 20% test.
  5. No leakage: split first, fit scaling on training data only, never use the final score as a feature. Leakage makes results look better than they are.

3. Linear regression

Simple (one input): ŷ = β₀ + β₁x. β₀ = intercept (score at x = 0); β₁ = slope (change per extra hour). Example ŷ = 42.5 + 4.92x: 6 hours → 72%.

Multiple (several inputs): ŷ = β₀ + β₁x₁ + … + βₚxₚ. Each β is the change in ŷ per unit of its feature, others held constant. In ŷ = 5 + 2.5x₁ + 0.3x₂ + 0.4x₃, one extra study hour adds 2.5 points.

Residual eᵢ = yᵢ − ŷᵢ: positive = point above the line (under-predicted). We square residuals so +4 and −4 don't cancel (16 + 16 = 32) and big errors weigh more.

Try it: train the line with gradient descent (the lecture's 5 students: 2–10 hours → 50–90)

0.010

4. How the model learns: cost and gradient descent

Cost J(β) = (1/n) Σ(yᵢ − ŷᵢ)² (MSE). Least squares picks the line with the smallest sum of squared residuals (SSE).

Gradient descent: start with β = 0 → predict → measure cost → compute gradient → update β ← β − α ∂J/∂β → repeat until the cost barely changes.

Learning rate α: too small = slow; too large = overshoots and can diverge; suitable = steady fall. Try α = 0.025 above.

Linear models can also use Ordinary Least Squares (direct solution). Neural networks use backpropagation + gradient descent. Cost is minimised during training; metrics judge the model afterwards.

Remember: prepare without leakage, fit ŷ = β₀ + β₁x by shrinking the squared residuals, and let α set the step size.
MAAI801 · Lecture 3Regression → preparation → linear model → gradient descent

Metrics, Polynomial Regression, Neural Nets

Which model fits the pattern and still works on unseen students?
Paper 2
of 2

5. Evaluation metrics

MetricFormulaBetter
MSE(1/n) Σ(y − ŷ)²lower
RMSE√MSE, in target unitslower
R²1 − Σ(y − ŷ)² / Σ(y − ȳ)²higher

Example: actual 80, 70, 90; predicted 78, 73, 88 → MSE = (4 + 9 + 4)/3 = 5.67. MSE 16 → RMSE 4 points. R² = 0.85: explains 85% of the variation; R² = 1 perfect, ≈ 0 weak, < 0 worse than the mean.

Train vs test: low + low = generalises; very low train + high test = overfitting; high + high = underfitting.

6. Assumptions and problems

  • Linearity, independent errors, constant error variance (homoscedasticity), normal residuals.
  • Multicollinearity: features carry the same information (study hours and LMS activity). Predictions can be fine but coefficients become unstable. Check the correlation matrix (|r| > 0.8) or VIF = 1/(1 − R²ⱼ): ≈1 none, 5–10 investigate, >10 serious.
  • Outliers pull the line; curved data breaks the straight-line model.

Poor test results? Check overfitting, leakage, preprocessing and features, then simplify or change the model and retrain.

7. Polynomial regression: when the pattern curves

Study hours help a lot at first, then less (diminishing returns). Add powers of the same input: ŷ = β₀ + β₁x + β₂x² + β₃x³. If x = 3 hours, x² = 9 and x³ = 27; they are not new variables, they let the line bend. Still trained like linear regression (OLS or gradient descent).

Choose the degree on validation data: start low, increase only while test error improves. Lecture table: degree 1 test MSE 510 (underfit), degree 2: 130, R² 0.85 (good), degree 8: train 5 but test 300 (overfit).

2
Train MSE 0Test MSE 0

8. Neural networks for regression

Layers of neurons learn complex nonlinear patterns. A neuron: z = w₁x₁ + w₂x₂ + w₃x₃ + b, then an activation a = f(z). Weights = importance of an input; bias shifts the output.

ReLU max(0, z) in hidden layers adds nonlinearity (z = −3 → 0, z = 2.5 → 2.5). The output layer for regression is linear (ŷ = z).

Training: forward pass → prediction → loss (MSE: actual 80, predicted 74, squared error 36) → backpropagation sends the error back → gradient descent updates w and b → repeat.

ModelPatternComplexity
Simple linearstraight, 1 featurelow
Multiple linearstraight, manylow
Polynomialcurvedmedium
Neural networkcomplex nonlinearhigher

NN pros: complex patterns, many inputs, flexible. Cons: needs more data and compute, hard to interpret, many settings (layers, neurons, α, epochs). Poor results come from too few neurons (underfit), training too long (overfit), little data or unscaled inputs.

One line: pick the simplest model that captures the pattern, train by minimising MSE, and trust only the test-set RMSE and R².
MAAI801 · Lecture 3Metrics → assumptions → polynomial → neural networks

Lecture 4 · Unsupervised Learning: Clustering

Similarity, K-Means, hierarchical clustering, DBSCAN
Paper 1
of 2

1. Learning without labels

Supervised learning predicts known outcomes from labelled data. Unsupervised learning gets no labels and discovers structure: groups, relationships, unusual points, simpler representations. Humans interpret what it finds.

FamilyGoalAlgorithms
Clusteringgroup similar pointsK-Means, hierarchical, DBSCAN
Associationitems that occur togetherApriori, FP-Growth, Eclat
Dim. reductionfewer features, keep infoPCA, NMF, LLE

2. Similarity and distance

Clustering groups points so members are similar and groups differ. Hard: each point in exactly one cluster. Soft: degrees (70% cluster 1, 30% cluster 2).

Small distance = more similar. Euclidean: d = √((x₂ − x₁)² + (y₂ − y₁)²). Others: Manhattan, cosine.

Scale first: LMS logins (0–1000) would swamp attendance (0–100). Use standardisation or min-max so each feature counts fairly.

Lecture data: students S1–S8 by attendance and assignment (plotted below).

3. K-Means (partition-based)

Choose K → place K centroids → assign each point to the nearest centroid → update each centroid to the mean of its points → repeat until stable.

Choose K with the elbow: run several K, plot WCSS / inertia Σ‖x − μ‖². WCSS always falls as K grows; pick K at the bend where gains get small.

Lecture result, K = 3: {S1, S2, S3, S8}, {S4, S5}, {S6, S7}.

Pros: simple, fast, scales. Cons: K chosen in advance, sensitive to starting centroids and outliers, prefers round compact clusters.

3

4. Hierarchical clustering

Agglomerative (bottom-up): every point is a cluster; merge the two closest; repeat until one. Divisive (top-down) splits instead.

Linkage defines cluster distance: single (closest pair), complete (farthest pair), average (mean of all pairs), Ward (smallest rise in variance).

A dendrogram shows the merges: leaves = points, merge height = dissimilarity. Cut it at a height to get clusters, so no K is needed upfront.

DBSCAN slider: at the lecture's ε = 6 (MinPts 2) S4 and S5 become noise; raise ε to merge everything.

5. DBSCAN (density-based)

Dense regions become clusters; isolated points are noise. ε = radius, MinPts ≈ features + 1. Core: ≥ MinPts within ε; border: near a core; noise: neither.

6
K-MeansHierarchicalDBSCAN
Pick K first?yesno (cut later)no
Odd shapes / noiselimited / poorsometimes / limitedyes / yes
Best forcompact, separated groupssmall data with a hierarchynoisy, irregular data (sensitive to ε)
Remember: scale, measure distance, then choose: K-Means for round groups, a dendrogram for hierarchy, DBSCAN when noise matters.
MAAI801 · Lecture 4Unsupervised → distance → K-Means → hierarchy → DBSCAN

Evaluating Clusters, Association Rules and PCA

Same eight students, three different questions
Paper 2
of 2

6. Evaluating clusters

Internal metrics need no labels:

Inertia / WCSScompactness onlylower
Silhouette s = (b − a)/max(a, b)a = own cluster, b = nearest other≈ +1
Davies–Bouldin (1/K) Σ max (Sᵢ + Sⱼ)/Mᵢⱼspread vs centroid gaplower
Calinski–Harabasz [B/(k−1)] / [W/(n−k)]between vs withinhigher

Silhouette ≈ 0.8 good, ≈ 0.1 overlapping, < 0 wrong cluster likely.

External metrics need reference labels, used only afterwards. Plain accuracy fails because cluster IDs are arbitrary names. ARI compares pairs, adjusted for chance (1 perfect, ≈ 0 random, < 0 worse). Mutual information: higher = more shared information.

7. Association rules and Apriori

Turn each student into a transaction of items: low attendance < 70, low assignment < 60, low quiz < 60, low LMS < 50, high late ≥ 4. S5 = {low attendance}; S6 and S7 have all five; others are empty.

  • Support = count(X ∪ Y)/N: how common.
  • Confidence = support(X ∪ Y)/support(X): when X, how often Y.
  • Lift = confidence/support(Y): > 1 positive, = 1 independent, < 1 negative.

Try a rule on the 8 students

→

Apriori: if an itemset is frequent, all its subsets are, so skip any superset of an infrequent set. Find frequent 1-itemsets → build bigger candidates → keep those above min support (25%) → generate rules → keep by confidence and lift. Associations ≠ causation.

8. Dimensionality reduction and PCA

Fewer features, most information kept: simpler data, less redundancy, faster models, easier plots.

Feature selection keeps original features (meaning preserved): filter (statistics, e.g. remove variance below τ = 0.01), wrapper (test subsets), embedded (chosen during training).

Feature extraction builds new features: PCA, factor analysis, ICA.

PCA steps: standardise z = (x − μ)/σ → covariance matrix → eigenvectors (directions) and eigenvalues (variance) → keep enough PCs for ~90–95% variance → project the data. PC1 = direction of most spread; PC2 = next, perpendicular to PC1.

Real run on S1–S8 (5 features): PC1 = 99.5% of variance. Scores run from S8 2.74 to S7 −3.51: strong students on one side.

PCA pros: compact, less redundancy, easy plots. Cons: PCs are hard to interpret, needs scaling, loses some information, linear only.

Workshop code (scikit-learn)
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
Xs = StandardScaler().fit_transform(X)
km = KMeans(n_clusters=3, n_init=10).fit(Xs); print(silhouette_score(Xs, km.labels_))
db = DBSCAN(eps=0.5, min_samples=3).fit(Xs); print(db.labels_)        # -1 = noise
pca = PCA(n_components=2).fit(Xs); print(pca.explained_variance_ratio_)
One line: judge clusters by compactness and separation, find co-occurring traits with support, confidence and lift, and compress features with PCA.
MAAI801 · Lecture 4Cluster metrics → Apriori → feature selection → PCA

Lecture 5 · Reinforcement Learning: Fundamentals

Agent, rewards, return, policy, exploration
Paper 1
of 2

1. What is reinforcement learning?

An agent learns by trial and error: it acts in an environment, receives rewards or penalties, and learns a policy that maximises cumulative reward over time. No labelled answers; built for sequential decisions.

SupervisedUnsupervisedReinforcement
Datalabelledunlabelledinteraction
Feedbackcorrect answernonereward after action
Outputlabel / numbergroups, patternspolicy

Uses: robotics, games (chess, Go, Atari), self-driving, energy grids. Course example: an AI academic advisor choosing interventions for students.

2. The building blocks

  • State s: the situation (attendance 55%, assignment 45%, LMS low).
  • Action a: tutoring, reminder, resources, study group, no action.
  • Reward r: feedback after an action (+ good, − bad, 0 no change).
  • Policy π: rule from states to actions.
  • Return G: total reward over time; discount γ weights the future.

The cycle: observe sₜ → choose aₜ → environment gives rₜ₊₁ and sₜ₊₁ → update the policy → repeat. A time step is one interaction; an episode runs from start to a terminal state (e.g. semester end).

Online RL learns by live interaction (adapts, but exploring can be costly). Offline RL learns from logged data only (safe, limited to what's recorded).

3. Rewards and reinforcement

Reward function r = w₁ΔA + w₂ΔS + w₃ΔL (weights sum to 1). S1 after tutoring: attendance 55→70, assignment 45→60, LMS Low→Medium: 0.4(15) + 0.4(15) + 0.2(1) = +12.2.

Positive reinforcement adds something good; negative reinforcement removes something unpleasant (reminders stop once she logs in). Both strengthen a behaviour. A penalty (negative reward, e.g. −3) is different: it discourages it.

4. Return and discounting

One good week isn't enough: tutoring +12.2, reminder −3, study group +8.

Undiscounted G = 12.2 − 3 + 8 = 17.2. Discounted G = r₁ + γr₂ + γ²r₃; with γ = 0.9: 15.98.

0.90
G = 15.98

γ = 0: only now matters; γ → 1: the future counts fully.

5. Policy and exploration

Deterministic a = π(s): attendance < 60% → tutoring. Stochastic π(a|s): tutoring 0.60, reminder 0.25, resources 0.10, none 0.05.

Exploration tries new actions; exploitation uses the best known. Too much of either hurts long-term reward.

ε-greedy: draw r ∈ [0, 1]; if r < ε explore (random action), else exploit. ε = 0.2 → 20% explore. Example r = 0.63 > 0.2 → exploit tutoring. Start high (0.3) when inexperienced, lower (0.1) later; keep ε small when exploring is risky.

6. Families of RL methods

AlgorithmTypeKey idea
Q-Learningvalue, off-policyupdate with best next action
SARSAvalue, on-policyupdate with action taken
DQNvalue + networkNN approximates Q, big states
REINFORCEpolicy-basedoptimise π(a|s) directly

Model-based plans with a model of the environment; model-free learns from trial and error. Actor-critic mixes policy and value.

Remember: the agent acts, collects rewards, and judges actions by their discounted long-term return, balancing exploration with exploitation.
MAAI801 · Lecture 5Agent → rewards → return → policy → ε-greedy

Value Functions, Bellman Equation, Q-Learning

From "how good is this?" to a learned policy
Paper 2
of 2

7. Value functions

State value Vπ(s) = Eπ[Gₜ | Sₜ = s]: how good a situation is if we follow π.

Action value Qπ(s,a) = Eπ[Gₜ | Sₜ = s, Aₜ = a]: how good one action is, then follow π.

S1: Q(s₁, tutoring) = 12.2 + 0.9 × 2.0 = 14.0. With Q = 14.0, 4.0, 6.5, 8.0 and π = 0.6, 0.2, 0.2, 0:

V(s₁) = Σ π(a|s)Q(s,a) = 8.4 + 0.8 + 1.3 = 10.5.

8. The Bellman equation

Value = immediate reward + γ × value of the next state:

Qπ(s,a) = E[rₜ₊₁ + γVπ(sₜ₊₁) | s, a]

S1, tutoring: 12.2 + 0.9 × 8.0 ≈ 19.4. It breaks a long-term value into simpler, recursive parts, so we don't need every future reward listed. Discounted return adds a known sequence; Bellman expresses value recursively.

9. Q-Learning: learn values from experience

Model-free: transition probabilities and rewards are unknown upfront. Goal: the optimal Q*(s,a) = maxπ Qπ(s,a).

Update rule after each experience (s, a, r, s′):

Q(s,a) ← Q(s,a) + α[r + γ maxa′Q(s′,a′) − Q(s,a)]

α = learning rate, γ = discount, the bracket = the error between the new target and the old estimate.

Worked (α = 0.1, γ = 0.9, max Q(s′) = 8): 0 + 0.1(12.2 + 7.2 − 0) = 1.94; next reward +4: 1.94 + 0.1(4 + 7.2 − 1.94) ≈ 2.87.

The Q-table has a row per state, a column per action, all starting at 0, and fills in with experience.

Game: train a robot with Q-learning. Goal ★ +10, obstacle −5, each step −1.

0.20

10. The learned policy

Pick the action with the highest learned value: π̂(s) = argmaxa Q̂(s,a).

Recommend tutoring14.0 ✓
Form study group8.0
Provide resources6.5
Send reminder4.0

So π̂(S1) = recommend tutoring. Bellman gives the theory; Q-learning applies it to learn from experience.

11. Challenges

  • Sample inefficiency: many interactions needed; simulation helps.
  • Reward design: bad rewards cause "reward hacking".
  • Exploration vs exploitation is hard to balance.
  • Scale: huge or continuous states need deep RL.

Overall: observe → act (ε-greedy) → reward → estimate values → update Q → better policy.

One line: V and Q measure long-term value, Bellman splits it into now + γ·next, Q-learning learns it from experience, and the policy takes the argmax.
MAAI801 · Lecture 5V and Q → Bellman → Q-learning → learned policy

Lecture 6 · Neural Networks: Foundations

Neurons, activation functions, forward pass and loss
Paper 1
of 2

1. Why neural networks?

Single-feature rules disagree: "attendance < 70%" and "assignment < 60%" classify students C, D and F differently. Student C has 85% attendance but 40% assignment. We need a model that combines several features, gives each a learned importance (weight) and learns from data.

Inspired by the brain: dendrites → inputs, synaptic strength → weights, soma → weighted sum, firing → activation, axon → output. The bias shifts the activation; it is not a biological threshold.

Types: feedforward (FNN, this lecture), CNN (images), RNN (sequences), GAN (generator vs discriminator), Transformers (attention).

2. The artificial neuron

Linear transformation z = w₁x₁ + w₂x₂ + w₃x₃ + b = w·x + b, then activation ŷ = f(z).

Student example: x = [0.85, 0.40, 1.00], w = [0.5, 0.3, 0.2], b = −0.4.

z = 0.425 + 0.12 + 0.20 − 0.4 = 0.345; σ(0.345) = 0.585 > 0.5 → needs support.

Network: input layer (features) → hidden layers (intermediate patterns) → output layer (prediction). Each neuron has one weight per input plus one bias: 3 inputs, 5 neurons → (3 + 1) × 5 = 20 parameters.

3. Activation functions

Without them, stacked layers are still one linear model. They add nonlinearity.

FunctionRangef(−3)Typical use
Sigmoid 1/(1+e⁻ᶻ)(0, 1)0.047binary output
ReLU max(0, z)[0, ∞)0hidden layers
Tanh(−1, 1)−0.995hidden, zero-centred

Choose by layer role, task (binary, multi-class, regression) and how well it trains.

−3.00

4. Try it: does this network flag spam?

Text becomes features: is the word present (1) or absent (0)? "Get free gift cards… limited-time offer" → X = [free 1, win 0, offer 1].

Hidden ReLU neurons, biases 0:
H1: z = 0.5·free − 0.2·win + 0.3·offer
H2: z = 0.4·free + 0.1·win − 0.5·offer
Output: ŷ = σ(0.7·H1 + 0.2·H2).

Lecture result: H1 = 0.8, H2 = ReLU(−0.1) = 0, z = 0.56, ŷ = 0.636 → spam. Loss −ln(0.636) = 0.452. A correct label isn't enough: probability and loss matter too.

True label:
Remember: a neuron is weighted sum + bias + activation; ReLU in hidden layers, sigmoid at a binary output; inputs must be numbers.
MAAI801 · Lecture 6Why NNs → neuron → activations → forward pass

Training: Loss, Backpropagation, Gradient Descent

Then building, evaluating and using the network in Keras
Paper 2
of 2

5. Loss: how wrong was it?

Binary cross-entropy L = −[y log ŷ + (1 − y) log(1 − ŷ)].

True yPredicted ŷLossMeaning
10.102.30very poor
10.301.20poor
10.700.36better
10.900.11good

The further the probability is from the true label, the higher the loss.

6. Gradient descent

wnew = wold − η ∂L/∂w: move each weight against its gradient. Example: 0.50 − 0.1 × 0.8 = 0.42.

0.10

Small η: slow but stable. Suitable η (0.10): fast, steady. Large η (1.00): overshoots, oscillates, may diverge.

7. Backpropagation and the training loop

  1. Forward pass layer by layer → ŷ (lecture: ŷ = 0.55, y = 1, loss 0.60).
  2. Loss compares ŷ with y.
  3. Backpropagation sends error signals backward with the chain rule to get ∂L/∂w and ∂L/∂b for every layer (output error δ = ŷ − y = −0.45).
  4. Gradient descent updates all weights and biases.

Backprop computes gradients; gradient descent uses them.

Iteration = one batch through the loop. Epoch = the whole dataset once. 1,000 students, batch 200 → 5 iterations per epoch.

8. Underfitting, overfitting and size

Underfit: training and validation loss both high (too few neurons, too few epochs). Good fit: both low and close. Overfit: training loss low, validation rising (too big, too little data, too many epochs; fix with regularisation, dropout, early stopping).

Neurons per layer (same data): 3→2→1 = 11 params, 78% val (underfit); 3→8→4→1 = 101, 88% (good); 3→64→32→1 = 2,369, 83% (overfit).

Pros: learns nonlinear patterns and features, parallel on GPUs. Cons: compute, black box, overfitting, needs lots of good data.

9. Workshop in Python (Keras): predict at-risk students

1. Prepare: 80/20 test split, then 20% of training for validation; scale attendance and assignment; one-hot LMS (drop "High") → 4 inputs. Fit preprocessing on training data only.

2. Build: 4 → Dense 8 ReLU → Dense 4 ReLU → Dense 1 sigmoid; Adam optimiser, binary cross-entropy.

3. Train 100 epochs, batch 16; watch training and validation curves (≈0.97 vs 0.89 accuracy: a small gap).

4. Evaluate on test (illustrative): TN 42, FP 8, FN 6, TP 44 → accuracy 0.86, precision 0.85, recall 0.88.

5. Predict a new student (68%, 55%, Low) → P(at risk) 0.782 → at risk. Lower the threshold (0.4) to catch more.

Keras code
from tensorflow.keras import Sequential, Input
from tensorflow.keras.layers import Dense
model = Sequential([Input(shape=(4,)),
    Dense(8, activation="relu"),
    Dense(4, activation="relu"),
    Dense(1, activation="sigmoid")])
model.compile(optimizer="adam",
    loss="binary_crossentropy",
    metrics=["accuracy"])
history = model.fit(X_train, y_train,
    epochs=100, batch_size=16,
    validation_data=(X_val, y_val))
p = model.predict(X_new)[0][0]
print("At Risk" if p > 0.5 else "Not At Risk")
One line: predict, measure the loss, backpropagate the gradients, step the weights, repeat for many epochs, then judge it on unseen data.
MAAI801 · Lecture 6Loss → gradient descent → backprop → fitting → Keras

Lecture 7 · Deep Learning: CNNs and RNNs

Architectures, applications and challenges
Paper 1
of 2

1. What is deep learning?

A subfield of ML using neural networks with multiple hidden layers that learn complex patterns and representations automatically from raw data. AI ⊃ ML ⊃ DL.

Shallow network (1–2 hidden layers): fine for simple, structured data. Deep: hierarchical features from images, text, audio; needs more data and compute.

Traditional ML uses hand-engineered features (edges, textures → SVM, random forest). DL learns them: automatic feature learning, multiple layers, complex/unstructured data, end-to-end learning.

Hierarchy: edges → textures → parts → objects. Loop: predict (Cat 0.92) → loss (0.08) → backprop + gradient descent, over many epochs.

2. The main architectures

ModelMain ideaExample
DNN / MLPmany fully connected layersstudent performance
CNNlocal visual patternscats vs dogs
RNNsequence, hidden statenext word
LSTMRNN with gates and memorysales forecast
Transformerattention between elementsChatGPT, translation
Autoencodercompress, reconstructdenoising images
GANgenerator vs discriminatorrealistic images

3. Convolutional Neural Networks (CNNs)

Why: images have spatial structure. A fully connected net flattens a 28 × 28 digit into 784 inputs, ignores which pixels are neighbours, and needs many parameters. A CNN uses local shared filters: fewer parameters, built for images.

Pipeline: input → convolution (small filters/kernels detect edges, curves) → ReLU (negatives → 0) → pooling (shrink, keep strongest) → flatten (3D maps → 1D vector) → fully connected + softmax (class probabilities summing to 1, e.g. bottle 0.90, mug 0.05, book 0.05).

Digit example: 28 × 28 → conv 26 × 26 × 32 → ReLU (same) → pool 13 × 13 × 32 → flatten 13 × 13 × 32 = 5,408 values → FC → digit 4. Pooling and flatten have no trainable parameters.

Models: LeNet-5 (1998, digits), ResNet (2015, residual shortcuts), MobileNet (2017, phones). Limits: labelled data, GPUs, grid data only.

Try it: convolution. Tap pixels of the 3 × 3 patch; filter = vertical edge [1 0 −1].

×
10−110−110−1
→
sum −3ReLU 0

Starts at the lecture's patch: sum = −3, ReLU → 0. Make the left column bright to detect an edge.

Max pooling 2 × 2 on the lecture's 4 × 4 map → [3 4; 2 3]:

4. Recurrent Neural Networks (RNNs)

Order matters: "The cat chased the mouse" ≠ "The mouse chased the cat". An RNN reads a sequence one step at a time and keeps a hidden state (memory): hₜ = tanh(Wₓxₜ + Whhₜ₋₁ + b). The same weights are reused at every step.

Next word: "The cat chased the …" → h₁…h₄ (each a vector, e.g. [0.56, −0.12, 0.80, …]) → FC + softmax → mouse 0.65, dog 0.12, car 0.08.

Uses: language modelling, speech, time series, sentiment. Types: simple, bidirectional (past and future context), stacked (several layers). Trained with backpropagation through time.

Vanishing gradients: in "The cat, which was hungry, chased the …" "cat" fades: mouse 0.25, house 0.30. Long-term dependencies are hard.

Remember: deep nets learn features layer by layer; CNNs exploit space with filters and pooling, RNNs exploit order with a hidden state.
MAAI801 · Lecture 7Deep learning → architectures → CNN → RNN

LSTMs, Transformers, Autoencoders and GANs

Plus how to choose an architecture, and the Teachable Machine workshop
Paper 2
of 2

5. LSTM: long short-term memory

An RNN with a memory cell and three gates:

  • Forget gate fₜ: what to remove from memory.
  • Input gate iₜ: what new information C̃ₜ to add.
  • Output gate oₜ: what to output as the hidden state.

Cₜ = fₜ ⊙ Cₜ₋₁ + iₜ ⊙ C̃ₜ, hₜ = oₜ ⊙ tanh(Cₜ). ⊙ = element-wise (Hadamard) product: [0.8, 0.3] ⊙ [10, 20] = [8, 6].

The cell learns to keep "cat" across the sentence → mouse 65%. It mitigates vanishing gradients. Uses: translation, speech, forecasting, video activity. Variants: standard, BiLSTM, stacked.

6. Transformers and attention

Replace recurrence with attention: every word looks directly at every other word, all words in parallel. Better long-range relations, faster training, scales.

Pipeline: tokenise → embeddings (animal → [0.2, 0.7, −0.4, …]) → add positional information (order) → self-attention + feed-forward layers → contextual representations → output.

Q, K, V: Query = what I look for; Key = what each word offers; Value = information used. Q·K → attention weights → weighted sum of V.

"The animal was tired because it ran all day." Who does it attend to?

BERT (encoder: understanding), GPT (decoder: generation), ViT (image patches). Costly in compute and data.

7. Autoencoders and GANs

Autoencoder (unsupervised): encoder compresses to a latent representation (e.g. 2 or 10 values), decoder reconstructs. Uses: compression, denoising, anomaly detection.

GAN: a generator turns random noise into fake data; a discriminator judges real vs fake. They train adversarially until fakes look real. Uses: image generation, style transfer, audio, data augmentation. Training can be unstable.

All of them learn the same way: forward pass → loss → backpropagation → gradient update (SGD/Adam), with task-specific losses.

8. Challenges

  • Data: thousands of labelled examples.
  • Overfitting: training loss falls, validation rises.
  • Compute: GPUs, days for large Transformers.
  • Interpretability: "black box" decisions (e.g. a refused loan).
  • Model selection and tuning: learning rate, layers, batch size, dropout.

Game: which architecture would you choose?

9. Workshop: image classifier

  1. Teachable Machine → Image Project → classes Mug, Book, Bottle; upload varied photos; train; test with new images.
  2. Export as TensorFlow / Keras (model file + labels).
  3. Google Colab: upload model, labels and test images; run cells in order.
  4. Evaluate: predicted label, confidence, accuracy, confusion matrix; which class is best/worst and how to improve.
One line: MLP for tables, CNN for images, RNN/LSTM for sequences, Transformers for long text, autoencoders to compress, GANs to generate.
MAAI801 · Lecture 7LSTM → Transformer → autoencoder, GAN → choosing

Lecture 8 · Problem Solving and Search

Problem formulation, uninformed and informed search
Paper 1
of 2

1. What is a problem in AI?

An agent moves from a current state to a goal state by choosing actions (Dubai → Abu Dhabi by different routes). Where am I? → what can I do? → where do I want to go?

Formulation = initial state + actions + transition model + goal test + path cost.

State space = all states reachable from the start. A solution = a sequence of actions to the goal (Dubai → E11 → Al Dhaid → E311 → Abu Dhabi).

2. Search

Systematically explore the state space to find actions from start to goal. Trying everything randomly or exhaustively is infeasible: the tree explodes.

Process: start → successors → select (strategy) → goal test → repeat.

Uninformed (blind): knows only start, actions, goal test, path cost: BFS, DFS, UCS. Informed (heuristic): uses an estimate of closeness to the goal: Greedy, A*.

3. Search on the warehouse robot (S = storage → G = packing station)

BFS (queue, FIFO): level by level. Finds the fewest steps, here S→A→D→G (cost 8, depth 3); ignores costs. Complete; optimal if all step costs are equal. Time and space O(bd): memory-hungry.

DFS (stack, LIFO): deepest first, backtrack at dead ends. Little memory O(bm), time O(bm). Not complete (infinite branches) and not optimal.

UCS (priority queue by g(n) = cost so far): cheapest first; stops when the goal is removed, not generated. Lecture: S→C→H→G, cost 1 + 2 + 3 = 6. Complete and optimal for positive costs; can be slow.

Heuristic h(n) = estimated remaining cost (e.g. straight-line km: A 80, B 35, C 60 → B looks best). A guide, not a guarantee.

Greedy best-first: smallest h(n) only. Fast but not optimal (lecture: S→C→D→G costs 8). A*: smallest f(n) = g(n) + h(n). Complete; optimal if h is admissible (never overestimates); worst case O(bm) memory.

Picks next byCompleteOptimalStrength / weakness
BFSshallowestyesfewest stepsfew steps / lots of memory
DFSdeepestnot alwaysnolow memory / deep or infinite paths
UCSlowest g(n)yesyesleast cost / slow, memory
Greedylowest h(n)not alwaysnooften fast / misleading h
A*lowest g + hyesyes (admissible h)balanced / memory

4. Optimisation

Search asks "can I reach the goal?"; optimisation asks "which feasible solution is best?" (route A 12 min, B 8 min, C 15 min).

Elements: decision variables, objective (min or max f(x)), constraints, feasible and optimal solutions. Min time → route B; max packages → C (10).

Why hard: 10 stops → 10! = 3,628,800 orders; 20 → 2.4 × 10¹⁸; plus constraints and uncertainty.

Formulations: CSP/COP, SAT/Max-SAT, LP, ILP/MILP. Problem → model → algorithm → solution.

Remember: formulate first, then search: BFS for fewest steps, UCS for least cost, A* for least cost guided by a good admissible heuristic.
MAAI801 · Lecture 8Formulation → BFS, DFS, UCS → Greedy, A* → optimisation

Constraint Satisfaction and Metaheuristics

CSP, COP, backtracking, local search, simulated annealing, genetic algorithms
Paper 2
of 2

5. Constraint satisfaction problems

CSP = (X, D, C): variables X = {A, B, C, D}, domains D = {Red, Green, Blue}, constraints A ≠ B, A ≠ C, B ≠ D, C ≠ D. A solution is a complete assignment satisfying every constraint. CSPs are NP-hard (O(dᴺ) assignments).

COP = (X, D, C, f) adds an objective: of all feasible colourings, minimise f(X) = Σ 1(Xᵢ = Red). Hard constraints must hold (feasibility); the objective ranks solutions.

Complete methods guarantee a solution if one exists (backtracking, FC, AC-3); incomplete ones scale but don't (local search, metaheuristics).

Game: colour the map. Tap a region to change its colour. Adjacent: A–B, A–C, B–D, C–D.

6. Making backtracking smarter

Backtracking: DFS that assigns one variable at a time and undoes a value that breaks a constraint → A = Red, B = Green, C = Green, D = Red.

Forward checking: after each assignment, delete now-impossible values from neighbours' domains (A = Red removes Red from B and C). An empty domain → backtrack at once.

AC-3: repeat until every arc X → Y is consistent (each value of X has support in Y): D(B) = {Red} removes Red from D(A).

MRV (which variable): fewest legal values left, e.g. C with 1. LCV (which value): the one that removes the fewest options from neighbours.

7. Local search and metaheuristics

Local search repairs a complete assignment (conflicts 2 → 1 → 0); min-conflicts gives a conflicted variable its least-conflict value. Risks: local optimum, plateau, cycling.

Metaheuristics balance exploration and exploitation. Single-solution: hill climbing (best neighbour, fitness 3 → 4, stops at a local optimum), simulated annealing, tabu search. Population: GA, particle swarm, ant colony.

8. Simulated annealing

Sometimes accept a worse move to escape a local optimum. ΔE = cost(new) − cost(current); better → accept; worse → accept with P = e−ΔE/T. Temperature falls: T ← αT, 0 < α < 1 (explore early, exploit late).

1 10
P = 0.90

9. Genetic algorithms

Chromosome [R, G, B, R] (gene = region, allele = colour) in a population. Fitness = satisfied constraints (3/4) → roulette selection (3, 4, 3, 3 → 23%, 31%, 23%, 23%) → crossover at a cut point → mutation (G → B) → repeat until 4/4 or no gain.

10. Choosing a method and the workshop

Shortest route → UCS / A*; timetable → backtracking + FC/MRV/LCV; huge map → min-conflicts; huge schedule → GA; stuck → simulated annealing.

Workshop: 6 courses, 3 rooms, 6 slots; no clashes, labs, AI before ML. Backtracking + FC + MRV/LCV finds a feasible timetable; as a COP, hill climbing moves ML R102 → R101: room changes f(X) 1 → 0.

One line: CSP finds a feasible answer, COP the best one; complete methods guarantee, incomplete ones scale; there is no universally best algorithm.
MAAI801 · Lecture 8CSP, COP → backtracking → local search → SA, GA

Lecture 9 · Knowledge Representation & Reasoning

Symbolic AI: facts, rules, representations, inference
Paper 1
of 2

1. Symbolic AI

Machine learning learns patterns from data. Symbolic AI represents knowledge explicitly with symbols, facts and rules and uses reasoning to derive conclusions: fact Attendance(Sara, 65) + rule IF Attendance(x) < 70 THEN LowAttendance(x) → LowAttendance(Sara).

Use symbolic when knowledge can be stated clearly and conclusions must be traced to rules (eligibility checks). Use ML when patterns are too complex to write (fraud detection). They can be combined.

2. Knowledge representation (KR)

KR organises facts, concepts, relationships and rules so an AI can process them; reasoning derives new conclusions. Knowledge alone is not intelligence.

A knowledge-based system (KBS) = knowledge base (facts and rules) + inference engine (applies rules to facts) + user interface.

TypeMeaningExample
Declarativeknowing whatattendance is 65%
Proceduralknowing howcompute weighted grade
Heuristicrule of thumblow attendance → may need help
Structuralrelationshipscourse belongs to a school
Metaabout knowledgewhich rules are reliable

3. Four ways to represent knowledge

TechniqueHowBest forLibrary example (Ali, 3 books, limit 3)
Logicpropositions, predicates, implicationprecise facts and logical relationsStudent(Ali), BorrowedBooks(Ali, 3)
Semantic networknodes + labelled links (instance-of, is-a)connections between conceptsAli —is a→ Student, —has borrowed→ 3 books
Framesobject with slots, values, defaultsattributes of objectsStudent frame: Name Ali, Borrowed 3, Limit 3
Production rulesIF condition THEN conclusion/actioncondition-based decisionsIF Student(x) ∧ Borrowed(x) ≥ 3 THEN NoMoreBorrowing(x)

Network inference: Sara instance-of Student, Student is-a Person → Sara is a person. Frames can hold defaults (Status = Active). Systems often mix techniques.

4. Types of reasoning

  • Deductive: general rule → certain specific conclusion (rule + Attendance(Sara, 65) → LowAttendance(Sara)).
  • Inductive: examples (60%, 65%, 68% all low) → probable general rule.
  • Abductive: observation (grade dropped) → most plausible explanation (low LMS activity).
  • Analogical: tutoring helped Adam → suggest it for similar Lina. Common-sense: everyday knowledge.
  • Monotonic: new facts never undo conclusions; nonmonotonic: they can (approved absence). Fuzzy: degrees of truth.

5. Inference: forward vs backward chaining

Rules: R1 attendance < 70% → low attendance. R2 low attendance ∧ low LMS → needs review. R3 needs review → advisor appointment.

Forward (data-driven): facts → apply rules → new facts → conclusion. 65%, LMS Low → R1 → R2 → R3 → RecommendAdvisorAppointment(Sara).

Backward (goal-driven): start from the goal, prove its subgoals from facts. Best for "Does Sara qualify?" (unknown LMS → cannot prove).

Remember: KR stores what the system knows, reasoning decides what follows; forward chaining asks "what follows?", backward chaining asks "can I prove this?".
MAAI801 · Lecture 9Symbolic AI → KR → 4 representations → reasoning → chaining

Fuzzy Logic and Fuzzy Inference

From 70% attendance and low LMS activity to a support priority score
Paper 2
of 2

6. Why fuzzy logic?

Crisp logic uses 0 or 1 with a sharp boundary: 69% = Low, 70% = Not low. One point flips the class. Fuzzy logic uses degrees of membership μ in [0, 1], so nearby values get similar degrees. It mimics "shades of grey" reasoning under vagueness.

Room at 32 °C: Cool μ = 0.0, Warm 0.8, Hot 0.2: partly warm and partly hot. Rule "IF warm THEN fan medium" → medium–high speed. Membership is not a probability.

Membership functions map each input in the universe of discourse to μ: triangular, trapezoidal, Gaussian, singleton. μ = 0 none, 0 < μ < 1 partial, 1 full.

7. Fuzzy operators

OperatorRuleSara
AND (intersection)min(μA, μB)min(0.33, 0.50) = 0.33
OR (union)max(μA, μB)max(0.33, 0.50) = 0.50
NOT (complement)1 − μA1 − 0.33 = 0.67

Fuzzy control adjusts behaviour gradually (fan slow / medium / fast) instead of on/off.

Quick check (from paper 1): which knowledge type?

8. The fuzzy inference system, step by step (Sara)

Architecture: crisp input → fuzzifier → inference engine (rules from the knowledge base) → aggregation → defuzzifier → crisp output. The input is a crisp value; fuzzy sets are created inside.

1. Fuzzification. Attendance sets: Low trapezoid (0, 0, 50, 80), Medium triangle (30, 60, 90), High (60, 90, 100, 100). LMS: Low (0, 0, 20, 40), Medium (20, 60, 100), High (60, 80, 100, 100). Attendance 70 → 0.33 / 0.67 / 0.33; LMS 30 → 0.50 / 0.25 / 0.00.

2. Rule evaluation (AND = min). R1: attendance Low AND LMS Low → support High: min(0.33, 0.50) = 0.33. R2: attendance Medium → support Medium: 0.67.

3. Aggregation. Clip each output set at its strength (Medium (20, 50, 80) at 0.67, High (60, 80, 100) at 0.33), then combine with MAX.

4. Defuzzification by centroid z* = ∫z·μ(z)dz / ∫μ(z)dz ≈ 57.6 / 100: moderate support priority. A score, not a probability of risk.

Try it: run the fuzzy system.

70 30
57.6

R1 and R2 are the lecture's. R3 (attendance High AND LMS High → support Low (0, 20, 40)) is added so the demo works for strong students.

One line: fuzzify crisp inputs into degrees, fire rules with min, combine with max, and defuzzify by centroid into one practical decision.
MAAI801 · Lecture 9Fuzzy sets → operators → fuzzification → rules → centroid

Lecture 10 · Ethical and Responsible AI

Dilemmas, values and the principles of trustworthy AI
Paper 1
of 2

1. Ethics and why AI needs it

Ethics = what we ought to do, what we owe others, and how we justify choices. Values guide choices (fairness, safety, privacy). An ethical dilemma arises when values or duties conflict.

AI already shapes hiring, lending and transport. The challenge: what should it prioritise, and who is responsible when it goes wrong?

2. Moral dilemmas

Trolley problem: do nothing and five die, or pull the lever and one dies. Footbridge: push one person to save five. Same outcome, but most say yes to the lever and no to pushing: the death is a side effect in one case and a means in the other. Intention and how directly we cause harm matter.

Moral Machine (Awad et al., Nature 2018): 40 million choices, 233 countries; the young were generally favoured, with varying strength. People weigh choices differently.

3. How an AI "decides": luxury car (AED 45,000) vs old truck (AED 8,000)

Model learns fromPredictsDecision rule → choice
insurance claims with repair billscar AED 45,000, truck AED 8,000minimise repair cost → hit the old truck
crash records with ages and injuriescar: 1 child; truck: 2 adults injuredminimise people injured → hit the luxury car
crash records with injury severitycar: 1 serious; truck: 2 minoravoid serious injuries → hit the old truck

Training data shapes the prediction; the decision rule sets the priority. AI can learn biases from human choices, and a numerical goal can still give an unfair choice. AI optimises for numbers; humans define the values.

4. Ethical vs responsible AI

Ethical AI applies principles to decide how AI should be designed and used (similarly qualified loan applicants should be treated alike). Responsible AI puts them into practice across design, testing, deployment and oversight (check whether some groups are wrongly rejected more often; assign a team to investigate).

Game: name the principle (section 5).

5. Six principles, one hiring case (timed online test, a candidate using a screen reader)

Principle: questionIn the case
Fairness: could it disadvantage some people?offer an accessible test that measures the skills the job actually needs.
Accountability: who can correct a mistake?the employer owns the use of the score; a manager offers an accessible retest; the team fixes the test and checks other affected candidates. Someone needs both the responsibility and the authority to fix mistakes.
Transparency: do people know AI is used, and its limits?tell applicants beforehand that AI scores the test and how to report a problem and request human review.
Explainability: what influenced this output?"one point per correct answer, unanswered = 0" lets a reviewer see the low score reflected an accessibility barrier.
Reliability: consistent over time?identical answers score the same in every supported browser and after updates; test with known-score cases.
Interpretability: can we follow input → output?6 correct, 4 blank → follow the rule → 6/10.
Remember: the same outcome can feel right or wrong depending on how harm is caused; AI follows the numbers we give it, so humans must choose the values and stay accountable.
MAAI801 · Lecture 10Ethics → dilemmas → decision rules → six principles

Vulnerability, Bias and the Noor Loan Case

Where bias comes from, how to test for it, and what to do next
Paper 2
of 2

7. Vulnerability

Changes in inputs or conditions expose weaknesses: conditions (fog), inputs (partly blocked camera), object appearance (a scratched stop sign may not be recognised). Test with imperfect inputs and plan for uncertainty.

In lending: conditions change (more freelancers apply), input data is wrong (a missing payment record lowers income), inputs are manipulated (a falsified income document accepted unverified). Check inputs and retest as conditions change.

8. AI bias and where it comes from

AI bias = a pattern that unfairly disadvantages some people or groups (e.g. by race, gender, age).

  • Data collection: underrepresented groups.
  • Feature selection: a proxy, e.g. postcode reveals a sensitive trait.
  • Model objective: overall accuracy hides higher error for small groups.
  • Human judgement: assumptions in labels and design.
  • Feedback loops: decisions shape future training data.

9. Two bias examples

Loan model: two applicants each earn AED 144,000 a year with the same debts. Salaried (AED 12,000 monthly) → approve; freelancer (same income, varying months) → deny. The model trained mostly on salaried applicants and learned to favour steady pay.

Gender Shades (Buolamwini and Gebru, MIT Media Lab, 2018): three commercial gender classifiers; error up to 34.7% for darker-skinned women vs 0.8% for lighter-skinned men. Test datasets were mostly lighter-skinned faces. Buolamwini's face went undetected until she wore a white mask.

10. Reducing and testing bias

  • Collect diverse data across genders, groups, cultures, regions.
  • Review and balance labels and coverage.
  • Test in real-world conditions where it will be used.
  • Separate prediction from auditing: drop unneeded sensitive inputs; use group data only to check unequal errors.
  • Involve diverse teams and users.

Tools: IBM AI Fairness 360 (measure and reduce disparities), ALM-Bench (vision-language models across languages and cultures). Tools flag gaps; people decide what to measure and why gaps exist.

11. Practice case: Noor's loan

Noor, a freelancer with varying monthly income who can afford the repayments, is recommended for denial. A loan officer finds she meets the lending criteria.

Trustworthiness checks: reliability (right on recent applications?), fairness (more wrongful denials for freelancers?), explainability (which factors?), accountability (who reviews and corrects?).

Audit: 100 qualified applicants per group. Wrongful denials: salaried 5/100 (5%), freelancers 20/100 (20%) → gap 15 percentage points.

What Noor should know: income variation was a major factor (explainability); a reviewer can trace the rules applied (interpretability); AI made the recommendation and an officer can review it (transparency).

Try it: audit the model. Wrongful denials per 100 qualified applicants.

5 20

Conclusion: require human review of denial recommendations while the bank investigates whether it penalises variable income or saw too few freelancers. Test on more recent applications (including approvals of unqualified applicants) and repeat the audit after any fix.

One line: one case raises the question, an audit shows the pattern, and the bank needs stronger evidence and human oversight before relying on the model.
MAAI801 · Lecture 10Vulnerability → bias sources → reduce and test → Noor audit

Guest Lecture · Machine Learning for Personalized Skin Health

Genetics, lifestyle and six skin concerns
Paper 1
of 2

1. The problem and the data

Two adults with similar sleep and sun habits can have different dryness and redness. Genetics may explain part of it; unmeasured exposures, skincare routines and reporting differences also matter. Would you use genetics, lifestyle or both? (Answered by the ablation later.)

Data: Nomige (Belgian skincare company, saliva DNA test + lifestyle survey). 5,254 records, 2018–2024; Belgium 81.9%, skin types II–III 77.0%. Inputs: 6 genetic profiles + 22 lifestyle variables (environment, skincare, psychological, smoking). Public on Mendeley Data.

Genes: FLG (barrier, hydration), AQP3 (water transport), GPX1 and SOD2 (antioxidant), MMP1 (collagen turnover), MMP3 (matrix, inflammation). A small targeted panel, not the whole genome.

Targets: six concerns (redness, dryness, acne, sensitivity, pigmentation, scarring), each graded 0–5 (ordered). "No concern" ranges from 37.8% (pigmentation) to 76.1% (scarring). Labels are self-reported, not clinical diagnoses. Encodings vary (Pregnant uses 0 = Yes).

2. Three papers, three tasks

StudyTargetQuestion
[1] IEEE JTEHM 2026derived skin profilecan genetics + lifestyle predict profile membership? (clustering + classification)
[2] IEEE Access 20256 severity gradesindependent models or coupled outputs?
[3] Scientific Reports 20266 severity gradesshared layers and explicit interactions?

Different targets and protocols, so the headline numbers cannot be ranked directly.

3. Pipeline and leakage

Intake + encoding → partition → fit transforms + model → evaluate + explain. Every learned step (imputation, scaling, cluster prototypes) must sit inside the training boundary.

Which estimate would you trust?

4. Metrics for ordered outcomes

MAE = (1/n) Σ|yᵢ − ŷᵢ|: average grade distance. QWK (quadratic weighted kappa) = 1 − Σwᵢⱼ Oᵢⱼ / Σwᵢⱼ Eᵢⱼ: ordinal agreement, distant errors penalised more, compared with chance. Predicting 4 when the truth is 5 is better than predicting 0. Also check macro-F1 and per-class recall: averages hide rare-class errors.

Try it: truth 0, 2, 5 (lecture example). Set the predictions:

MAE 1.00Accuracy 1/3QWK

Prediction 0, 3, 3 gives MAE 1.00 and accuracy 1/3, as in the lecture. Neither metric replaces the other.

5. Paper [1]: profiles from genetics + lifestyle

k-modes (clustering for categorical data) learns skin profiles inside each outer training fold; held-out records get labels from training prototypes. XGBoost then predicts the profile from genetics and lifestyle (phenotype columns excluded). Full-data refit: 4 profiles, including a lower-severity reference group, an acne-dominant group and a reactive sensitivity/redness group.

Result: integrated inputs reach accuracy 0.979 ± 0.008, macro-F1 0.971 ± 0.013 (5 outer folds); single-source models scored 0.82–0.88. This is agreement with derived labels, partly defined by the same variables, not diagnostic accuracy.

Remember: fit every learned step inside the training split, use ordinal metrics (MAE, QWK) for graded targets, and read a score against the target it measures.
Guest lecture · related to Lecture 8Data → three papers → leakage → MAE, QWK → profiles

Multi-Output Models, Neural Interactions and Limits

Chains vs independent models, multi-task networks, explanations vs causes
Paper 2
of 2

6. Paper [2]: how to connect six outputs

  • Independent models: one tuned model per concern.
  • MultiOutputRegressor: one wrapper, separate regressors, outputs not connected.
  • RegressorChain: later models use earlier predictions as inputs; order matters (6! = 720 orders).

Setup: LightGBM, 80/20 split, 3-fold grid search inside training. QWK selects the classifiers; MAE selects the wrappers. Chain order should also be chosen inside training; repeatedly checking the test set turns it into development data.

Result: independent LightGBM classifiers reach QWK 0.87–0.92, MAE 0.07–0.23. Best chain: mean QWK 0.687, MAE 0.736. A strong per-target baseline, but objectives and tuning also differ, so the gap is not only about independence.

7. Paper [3]: shared neural representations

Related concerns may share input patterns (hydration info could help both dryness and sensitivity: an intuition, not a proven mechanism). Sharing can also hurt: negative transfer.

MT-DNN: 28 standardised inputs → Dense 256 → Dense 128 (norm + dropout, residual projection) → shared 128-dim representation → 6 task heads.

Two output formulations: bounded regression ŷ = 5σ(z) with Huber loss + snap regulariser (β = 0.10), versus six-class softmax with sparse cross-entropy (argmax). Training: 70/15/15 split, AdamW, early stopping (patience 12), 5 random seeds.

Mean QWK: regression 0.787 ± 0.015, softmax 0.813 ± 0.017. Scarring gains, dryness prefers regression. A 0.026 trend, not proof of superiority.

8. Explicit pairwise interactions and ablation

Add all feature products before the dense layers: 28 + (28 × 27)/2 = 406 inputs; 132 strict gene × lifestyle pairs per concern.

Ablation: mean QWK by input set

Lifestyle carries most of the signal; genetics adds 0.028, interactions another 0.031. Predictive gains, not proof of biological interaction.

9. Explanations are not causes

MethodAnswersLimit
Permutation importancedoes shuffling hurt the score?correlated features
Saliencylocal output sensitivityscale, gradient noise
SHAPhow a prediction is allocateddepends on model, background

18 SHAP-selected interaction terms tested; 14 survive FDR correction (e.g. GPX1 × outdoor exposure → acne, p = 1.2 × 10⁻⁹; AQP3 × stress → redness). Same-cohort, data-driven: exploratory, non-causal.

Prediction vs causation: someone may avoid the sun because their skin is already sensitive. Importance ≠ the effect of changing behaviour.

10. Limits, next steps and lessons

LimitationConsequenceStronger evidence
narrow consumer cohortuncertain transferindependent, diverse recruitment
self-reported labelsmeasurement / reporting biasclinician or instrument endpoints, images
rare severity gradesaverages hide errorsper-class recall and uncertainty
cross-sectional datadirection unresolvedrepeated outcomes or interventions

Next: ordinal losses (cumulative-link), single-task vs shared networks on the same splits and tuning budgets, independent and longitudinal cohorts, images linked properly (not row by row).

Lessons: (1) the target defines the claim; (2) the protocol defines the comparison; (3) explanations generate hypotheses; (4) predicting a concern ≠ knowing what to change.

One line: combining genetics and lifestyle helps prediction, but fair comparisons need one protocol, and causal claims need causal evidence.
Guest lecture · related to Lecture 8Chains → MT-DNN → interactions → explanations → limits