8 Hours | 4 Topics | Programming Paradigms · Integration · SDLC · Case Studies
Imperative, OOP, Functional, Logic, Event-Driven, Dataflow — choosing the right approach for AI tasks
Hybrid architectures, polyglot systems, multi-language AI pipelines, benefits & challenges
Problem definition → data → modelling → deployment → monitoring — full SDLC for AI
ChatGPT, Tesla Autopilot, Netflix, AlphaGo, Healthcare AI — real-world paradigm applications
By the end of this unit, students will be able to:
An AI System is a software or hardware system that perceives its environment, processes information using computational intelligence, and takes actions or produces outputs that would otherwise require human intelligence.
Sensors, cameras, microphones, data feeds
ML models, rule engines, search algorithms
Decisions, recommendations, actuators
Adapt and improve from experience/feedback
Raw data sources, databases, data lakes, real-time streams. Quality data is the foundation of every AI system.
Cleaning, normalisation, feature extraction, dimensionality reduction. Transforms raw data into model-ready inputs.
ML/DL models, rule engines, knowledge bases. The intelligence core — makes predictions, decisions, or inferences.
Applies trained models to new inputs. May run locally (edge) or on cloud hardware (GPU/TPU clusters).
APIs, message queues, microservices. Connects the AI core to applications, UIs, and external systems.
Performance metrics, drift detection, logging. Ensures the system remains accurate and reliable over time.
A paradigm is a fundamental style or pattern of programming — a set of principles that guide how problems are modelled and solved in code.
Programs are sequences of statements that change program state. You describe how to solve the problem step-by-step.
Numerical algorithms (gradient descent, sort), data pipelines, scripting experiments, preprocessing routines in C / Python.
Hard to scale; state management complexity grows rapidly; difficult to parallelise large AI workloads.
# Imperative: gradient descent step
def gradient_descent(X, y, lr=0.01, epochs=1000):
m, n = X.shape
theta = np.zeros(n) # state
for epoch in range(epochs): # explicit loop
predictions = X @ theta
error = predictions - y
gradient = X.T @ error / m
theta = theta - lr * gradient # state mutation
return theta
Programs are organised as objects — encapsulated bundles of state (attributes) and behaviour (methods). Relationships modelled via inheritance & composition.
Neural network layer classes (PyTorch nn.Module), agent architectures,
simulation environments, game AI, robotics frameworks.
Encapsulation — model internals hidden
Inheritance — custom layers extend base
Polymorphism — swap optimisers/models
# OOP: custom neural network layer (PyTorch)
import torch.nn as nn
class AttentionLayer(nn.Module):
def __init__(self, embed_dim, heads):
super().__init__()
self.attn = nn.MultiheadAttention(
embed_dim, heads
)
self.norm = nn.LayerNorm(embed_dim)
def forward(self, x):
attn_out, _ = self.attn(x, x, x)
return self.norm(x + attn_out) # residual
# Polymorphism – plug in any nn.Module
model = nn.Sequential(
AttentionLayer(512, 8),
nn.Linear(512, 256),
nn.ReLU()
)
Computation as evaluation of pure functions — no side effects, immutable data, higher-order functions, declarative transformations.
Data transformation pipelines (map/filter/reduce), JAX auto-differentiation,
Haskell probabilistic models, Spark ML pipelines.
Pure functions → easy parallelisation
Immutability → reproducible experiments
Function composition → modular pipelines
# Functional: data pipeline with map/filter
from functools import reduce
raw_data = [3.2, None, -1.0, 8.7, None, 5.5]
pipeline = (
lambda data:
list(map(
lambda x: (x - 2.8) / 3.4, # normalise
filter(lambda x: x is not None, # clean
filter(lambda x: x >= 0, # remove neg
filter(None.__ne__, data)))
))
)
clean = pipeline(raw_data) # [0.118, 1.735, 0.794]
# JAX: functional auto-diff
import jax
grad_loss = jax.grad(lambda params: loss_fn(params, X, y))
Programs are expressed as facts and rules; the engine performs automated inference to answer queries. Describes what to compute, not how.
Expert systems, knowledge graphs, natural language processing (constraint solving), medical diagnosis, planning (STRIPS/PDDL).
Prolog, Datalog, Answer Set Programming (ASP), CLIPS. Python bridges:
pyswip, kanren
% Prolog — Medical Expert System
symptom(patient1, fever).
symptom(patient1, cough).
symptom(patient1, fatigue).
disease(flu) :- symptom(P, fever),
symptom(P, cough),
symptom(P, fatigue).
treatment(flu, rest).
treatment(flu, antiviral).
% Query: what disease does patient1 have?
% ?- disease(D), treatment(D, T).
% D = flu, T = rest ;
% D = flu, T = antiviral.
Program flow driven by events — signals, user actions, sensor readings, messages. Handlers (callbacks/listeners) respond asynchronously.
Real-time AI (fraud detection, intrusion detection), chatbot interfaces, autonomous robot reactions, IoT sensor fusion, reinforcement learning environments.
Publisher/Subscriber · Observer Pattern
Message Queues (Kafka, RabbitMQ)
WebSocket streams for live inference
# Event-driven: real-time fraud detection
import asyncio
class FraudDetector:
async def on_transaction(self, event):
score = await self.model.predict(event)
if score > 0.85:
await self.alert(event['id'], score)
async def alert(self, tx_id, score):
print(f"🚨 FRAUD: tx={tx_id} score={score:.2f}")
# Event loop — handles thousands concurrently
async def main():
detector = FraudDetector()
async for event in kafka_stream("transactions"):
asyncio.create_task(
detector.on_transaction(event)
)
asyncio.run(main())
Programs modelled as a directed graph of operations. Nodes represent computations; edges represent data flowing between them. Execution driven by data availability.
TensorFlow computation graphs, Apache Spark ML, ML pipelines (scikit-learn
Pipeline), Airflow DAGs for training workflows.
Automatic parallelism · GPU scheduling
Lazy evaluation · Easy graph optimisation
Visual debugging of pipelines
| Paradigm | Core Concept | State | AI Strengths | Typical Languages / Frameworks | AI Example |
|---|---|---|---|---|---|
| Imperative | Step-by-step instructions | Mutable | Algorithms, preprocessing | C, Python, NumPy | Gradient descent loop |
| OOP | Objects with state & behaviour | Mutable | Model design, agents, frameworks | Python, Java, C++, PyTorch | Neural network classes |
| Functional | Pure functions, no side effects | Immutable | Data pipelines, auto-diff | Haskell, Scala, JAX, Spark | ML transformation pipelines |
| Logic | Facts + rules → inference | Declarative | Expert systems, KGs, planning | Prolog, Datalog, ASP | Medical diagnosis engine |
| Event-Driven | Callbacks on events | Reactive | Real-time AI, robotics | Python asyncio, Node.js, ROS | Fraud detection stream |
| Dataflow | Data-driven graph execution | Implicit | DL training, big data ML | TensorFlow, Spark, Airflow | TF computation graph |
Pattern recognition / prediction → Dataflow / OOP (deep learning)
Rule-based / expert → Logic
Real-time response → Event-Driven
Single machine, prototyping → Imperative / OOP
Distributed big data → Functional / Dataflow
Edge / embedded → Imperative (C/C++)
Mission-critical → Functional (verifiable purity)
Rapid experimentation → OOP / Imperative
Safety constraints → Logic / hybrid
Real AI systems have many subsystems — each may require a different computational style. A one-paradigm approach forces unnatural solutions.
| Subsystem | Paradigm | Reason |
|---|---|---|
| Sensor fusion | Imperative / C++ | Speed, hardware control |
| Object detection | Dataflow (PyTorch) | GPU-accelerated DL |
| Path planning | Logic / constraint | Safety rules enforcement |
| Real-time control | Event-Driven (ROS) | Millisecond reaction |
| Data logging | Functional (Spark) | Parallel, immutable records |
Python handles data I/O, patient records (OOP), and ML-based symptom extraction.
Prolog encodes clinical decision rules and performs logical inference for diagnosis.
# Python (OOP) calls Prolog (Logic)
from pyswip import Prolog
class Patient:
def __init__(self, name, symptoms):
self.name = name
self.symptoms = symptoms # list of strings
class DiagnosisEngine:
def __init__(self):
self.prolog = Prolog()
self.prolog.consult("diagnosis.pl") # load rules
def diagnose(self, patient: Patient):
# Assert patient facts into Prolog
for s in patient.symptoms:
self.prolog.assertz(f"symptom({patient.name},{s})")
# Query Prolog logic engine
results = list(self.prolog.query(
f"disease({patient.name}, D), treatment(D,T)"
))
return results
# Usage
p = Patient("alice", ["fever","cough","fatigue"])
engine = DiagnosisEngine()
print(engine.diagnose(p))
# → [{'D': 'flu', 'T': 'rest'}, ...]
SQL retrieves historical orders (declarative)
Python cleans & engineers features (imperative/functional)
TensorFlow trains the recommendation model (dataflow)
SQL — Declarative Pandas — Functional TensorFlow — Dataflow FastAPI — Event-Driven
# 1. SQL (Declarative) — fetch data
query = """
SELECT user_id, product_id, rating, timestamp
FROM purchases
WHERE timestamp > '2024-01-01'
"""
df = pd.read_sql(query, engine)
# 2. Pandas (Functional transforms) — feature engineering
user_features = (df
.groupby('user_id')
.agg(avg_rating=('rating','mean'),
purchase_count=('product_id','count'))
.reset_index()
)
# 3. TensorFlow (Dataflow) — collaborative filtering
model = tf.keras.Sequential([
tf.keras.layers.Embedding(n_users, 32),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(n_products, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy')
model.fit(X_train, y_train, epochs=10)
# 4. FastAPI (Event-Driven) — serve predictions
@app.get("/recommend/{user_id}")
async def recommend(user_id: int):
return model.predict([[user_id]]).tolist()
ROS (Robot Operating System) uses event-driven pub/sub messaging to coordinate modules written in different languages and paradigms.
# ROS2 Python node — object detection subscriber
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from vision_msgs.msg import Detection2DArray
import torch
class DetectionNode(Node): # OOP: extends Node
def __init__(self):
super().__init__('detector')
# Event-Driven: subscribe to camera topic
self.sub = self.create_subscription(
Image, '/camera/image_raw',
self.on_image, 10 # callback
)
self.pub = self.create_publisher(
Detection2DArray, '/detections', 10
)
self.model = torch.hub.load( # Dataflow: DL model
'ultralytics/yolov5', 'yolov5s'
)
def on_image(self, msg): # event handler
results = self.model(msg.data)
detections = self.parse(results)
self.pub.publish(detections) # publish to ROS topic
rclpy.init()
rclpy.spin(DetectionNode())
Vague goals ("make it smarter") · Ignoring data availability · Skipping feasibility analysis · Underestimating deployment complexity
| Question | Example Answer |
|---|---|
| What is the goal? | Detect spam emails with >95% precision |
| What is the input? | Raw email text + metadata |
| What is the output? | Binary label: spam / not spam |
| What metrics matter? | Precision, Recall, F1, latency < 100ms |
| Is data available? | 10M labelled emails from archive |
| Is AI needed? | Rules alone achieve only 70% — yes |
Relational databases (SQL), spreadsheets, CSV files, ERP systems. Well-organised, easy to query but may need joins and aggregation.
Text (web scraping, NLP corpora), images (cameras, Flickr API), audio (recordings), video. Requires specialised preprocessing pipelines.
IoT sensors, social media APIs (Twitter/X firehose), financial ticks, server logs. Needs stream processing (Kafka, Flink).
Generated data when real data is scarce or private. GANs, simulation (robotics), data augmentation, faker libraries.
Manual annotation (LabelImg, CVAT, Label Studio), crowdsourcing (MTurk), weak supervision (Snorkel), semi-supervised techniques.
GDPR / privacy compliance, data lineage, consent management, data versioning (DVC), access controls, audit trails.
"Garbage in, garbage out" — real-world data is messy, incomplete, and inconsistent. Preprocessing converts raw data into clean, model-ready inputs.
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
# Load raw data
df = pd.read_csv('data.csv')
# 1. Missing value imputation
imputer = SimpleImputer(strategy='median')
df[['age','income']] = imputer.fit_transform(
df[['age','income']]
)
# 2. Remove outliers (IQR method)
Q1, Q3 = df['income'].quantile([0.25, 0.75])
IQR = Q3 - Q1
df = df[df['income'].between(Q1 - 1.5*IQR,
Q3 + 1.5*IQR)]
# 3. Encode categoricals
df = pd.get_dummies(df, columns=['city','gender'])
# 4. Scale numeric features
scaler = StandardScaler()
numeric = ['age','income','score']
df[numeric] = scaler.fit_transform(df[numeric])
print(f"Clean dataset: {df.shape} rows/cols")
The process of using domain knowledge to create, transform, or select input variables that help machine learning algorithms perform better.
Combine/derive signals (e.g. rush hour from timestamp)
PCA, t-SNE — reduce noise, compress features
SHAP, mutual info — keep relevant variables
TF-IDF, Word2Vec, CNN feature maps
import pandas as pd
from sklearn.decomposition import PCA
# Example: feature engineering for ride-share data
df['hour'] = pd.to_datetime(df['pickup']).dt.hour
df['is_rush'] = df['hour'].between(7, 9) | df['hour'].between(17, 19)
df['is_weekend'] = pd.to_datetime(df['pickup']).dt.dayofweek >= 5
df['distance_km'] = haversine(df['lat1'],df['lon1'],
df['lat2'],df['lon2'])
df['price_per_km'] = df['fare'] / (df['distance_km'] + 1e-9)
# Embeddings for categorical 'zone'
from sklearn.preprocessing import OrdinalEncoder
enc = OrdinalEncoder()
df['zone_enc'] = enc.fit_transform(df[['zone']])
# Dimensionality reduction on sensor data
pca = PCA(n_components=10)
sensor_cols = [c for c in df if c.startswith('sensor')]
df_pca = pca.fit_transform(df[sensor_cols])
print(f"Explained variance: {pca.explained_variance_ratio_.sum():.2%}")
When: Structured/tabular data, small-medium datasets, interpretability
needed
Examples: Linear/Logistic Regression, SVM, Decision Trees, Random Forest,
XGBoost
When: Images, text, audio, video; very large datasets; raw feature input
Examples: CNNs, RNNs/LSTMs, Transformers, GANs, Diffusion models
When: Sequential decisions, environment simulation available, exploration
needed
Examples: DQN, PPO, A3C, SAC, AlphaZero
When: Expert knowledge encoded as rules; explainability mandatory
Examples: Expert systems, Bayesian networks, ontologies
When: Maximum accuracy needed; diverse models available
Examples: Bagging, Boosting (XGBoost, LightGBM), Stacking
Data size & type · Latency requirements · Explainability · Available compute · Team expertise · Baseline performance
Grid search · Random search · Bayesian optimisation (Optuna) · Neural Architecture Search (NAS)
import torch, torch.nn as nn, optuna
def objective(trial):
lr = trial.suggest_float('lr', 1e-5, 1e-2, log=True)
batch = trial.suggest_categorical('batch', [16,32,64,128])
drop = trial.suggest_float('dropout', 0.1, 0.5)
model = MyModel(dropout=drop)
opt = torch.optim.Adam(model.parameters(), lr=lr)
loader = DataLoader(train_ds, batch_size=batch)
for epoch in range(20):
model.train()
for X, y in loader:
opt.zero_grad()
loss = nn.CrossEntropyLoss()(model(X), y)
loss.backward()
opt.step()
# Return validation metric
return evaluate(model, val_loader)
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=50)
print("Best:", study.best_params)
Accuracy — overall correct rate
Precision — TP / (TP+FP)
Recall — TP / (TP+FN)
F1-Score — harmonic mean of P & R
AUC-ROC — ranking quality
MAE — Mean Absolute Error
MSE / RMSE — penalises large errors
R² — explained variance
MAPE — percentage error
BLEU — translation quality
ROUGE — summarisation recall
Perplexity — language model quality
BERTScore — semantic similarity
Adversarial inputs · Distribution shift · Edge cases · Fairness across demographic groups
SHAP values · LIME · Attention maps · Grad-CAM for CNNs · Feature importance plots
Confusion matrix analysis · Error case review · Bias audits · Hold-out test set — never tune on this!
Model versioning (MLflow) · Container packaging (Docker) · Automated testing · Blue/green & canary deployments · Model registry
| Tool | Purpose |
|---|---|
| Evidently AI | Data/model drift detection |
| Prometheus + Grafana | Infrastructure & custom metrics |
| Weights & Biases | Experiment tracking, model registry |
| MLflow | Model lifecycle management |
| Great Expectations | Data quality validation |
Monitoring insights feed back to data collection, model retraining, or even problem redefinition — making the lifecycle truly iterative.
OpenAI · GPT-4 Architecture · Transformer-based text generation
OOP — PyTorch nn.Module Dataflow — TF/JAX graphs Functional — JAX transforms Event-Driven — streaming API
Real-time perception, path planning & control for autonomous driving
Dataflow — neural net inference Event-Driven — real-time callbacks OOP — vehicle abstraction Logic — safety rules Imperative C++ — control
Personalised content recommendations for 270+ million subscribers
Dataflow — Spark/Flink pipelines Functional — immutable transforms OOP — model hierarchy Event-Driven — real-time signals
Superhuman performance at Go, Chess, and Shogi using deep RL
Dataflow — CNN/ResNet OOP — game tree & nodes Event-Driven — move triggers Logic — MCTS rules Functional — self-play
AI-assisted detection of cancer, diabetic retinopathy, and COVID-19 in medical scans
Dataflow — CNN inference OOP — patient records Logic — decision rules Event-Driven — alerts
FDA/CE approval · HIPAA/GDPR compliance · Explainability for doctors · Fail-safe: refer human MD
| AI System | Primary Paradigm(s) | Data Type | Key Technique | Scale | Unique Challenge |
|---|---|---|---|---|---|
| ChatGPT / GPT-4 | Dataflow, OOP, Functional | Text (570 GB+) | Transformer + RLHF | 175B+ parameters, global | Hallucination & factual accuracy |
| Tesla Autopilot | Event-Driven, Dataflow, Imperative | Video + sensors | HydraNet + occupancy grids | Fleet of millions of vehicles | Real-time safety at ms latency |
| Netflix Recommender | Dataflow, Functional, Event-Driven | Interaction logs | Collaborative filtering + DNN | 270M+ users, 15,000+ titles | Cold start & diversity vs. accuracy |
| AlphaGo / Zero | Dataflow, OOP, Logic, Functional | Game states (self-play) | Policy/Value nets + MCTS + RL | Millions of self-play games | Sample efficiency of self-play |
| Healthcare AI | Dataflow, OOP, Logic, Event-Driven | Medical images (DICOM) | U-Net + ResNet + Grad-CAM | Hospital-scale, regulated | Regulatory compliance & explainability |
Training data biases propagate into model outputs. Biased AI in hiring, lending, or healthcare can cause real harm. Regular bias audits (Aequitas, Fairlearn) are essential.
"Black box" AI erodes trust. Use XAI tools (SHAP, LIME, Grad-CAM). High-stakes domains (medical, legal) may legally require explanations.
Personal data used to train AI must comply with GDPR, HIPAA, CCPA. Techniques: differential privacy, federated learning, data anonymisation.
AI systems in safety-critical domains (autonomous vehicles, medical devices) must be thoroughly tested against adversarial inputs, edge cases, and distribution shifts.
Who is responsible when an AI system makes a harmful decision? Clear accountability frameworks must accompany AI deployment. Human oversight is non-negotiable.
Training large models (GPT-4, Gemini) consumes enormous energy. Green AI research focuses on efficient architectures, smaller models, and renewable energy for compute.
Six major paradigms — Imperative, OOP, Functional, Logic, Event-Driven, Dataflow — each suited to different AI task types. No single paradigm fits all problems.
Real AI systems are polyglot. Hybrid architectures combine paradigms at architectural boundaries using APIs, message queues, and containers.
Nine-phase iterative process: Problem → Data → Preprocessing → Features → Model Selection → Training → Evaluation → Deployment → Monitoring. Each phase feeds back into others.
ChatGPT, Tesla, Netflix, AlphaGo, and Healthcare AI all demonstrate different paradigm combinations driven by their unique constraints: scale, latency, safety, and explainability.