Unit 7

Implementation of AI Systems

8 Hours  |  4 Topics  |  Programming Paradigms · Integration · SDLC · Case Studies

AI SYSTEM

Unit Outline

7.1 Selecting Programming Paradigms

Imperative, OOP, Functional, Logic, Event-Driven, Dataflow — choosing the right approach for AI tasks

7.2 Integration of Paradigms

Hybrid architectures, polyglot systems, multi-language AI pipelines, benefits & challenges

7.3 AI System Development Lifecycle

Problem definition → data → modelling → deployment → monitoring — full SDLC for AI

7.4 Case Studies

ChatGPT, Tesla Autopilot, Netflix, AlphaGo, Healthcare AI — real-world paradigm applications

Learning Objectives

By the end of this unit, students will be able to:

  • Identify and distinguish major programming paradigms used in AI development
  • Select an appropriate paradigm based on the nature of an AI problem
  • Explain how multiple paradigms can be integrated within a single AI system
  • Describe the complete AI System Development Life Cycle (SDLC)
  • Apply SDLC phases to design and plan a real AI system
  • Analyse real-world AI case studies and identify the paradigms used
  • Evaluate trade-offs in paradigm choice, integration complexity, and deployment
  • Discuss ethical considerations in AI system implementation

What is an AI System?

Definition

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.

Perceive

Sensors, cameras, microphones, data feeds

Reason

ML models, rule engines, search algorithms

Act

Decisions, recommendations, actuators

Learn

Adapt and improve from experience/feedback

ENVIRONMENT 🌍 Data / Signals Sensors / Events AI SYSTEM Perception Reasoning Learning Action OUTPUT 🎯 Decisions Actions Predictions Feedback / Learning Loop

Components of an AI System

Data Layer

Raw data sources, databases, data lakes, real-time streams. Quality data is the foundation of every AI system.

Preprocessing

Cleaning, normalisation, feature extraction, dimensionality reduction. Transforms raw data into model-ready inputs.

AI Model

ML/DL models, rule engines, knowledge bases. The intelligence core — makes predictions, decisions, or inferences.

Inference Engine

Applies trained models to new inputs. May run locally (edge) or on cloud hardware (GPU/TPU clusters).

Integration Layer

APIs, message queues, microservices. Connects the AI core to applications, UIs, and external systems.

Monitoring

Performance metrics, drift detection, logging. Ensures the system remains accurate and reliable over time.

7.1
Selecting the Appropriate
Programming Paradigm
Imperative · OOP · Functional · Logic · Event-Driven · Dataflow
7.1 Programming Paradigms

Why Programming Paradigms Matter

What is a Programming Paradigm?

A paradigm is a fundamental style or pattern of programming — a set of principles that guide how problems are modelled and solved in code.

  • Different AI tasks have very different computational structures
  • The paradigm shapes expressiveness, maintainability & performance
  • Wrong choice → brittle, inefficient, or un-maintainable systems
  • Most real AI systems combine multiple paradigms (polyglot approach)
  • Understanding paradigms enables better architecture decisions
AI Problem Imperative / Procedural Object- Oriented Functional Logic Event- Driven Dataflow
7.1 Programming Paradigms

Imperative & Procedural Programming

Core Idea

Programs are sequences of statements that change program state. You describe how to solve the problem step-by-step.

AI Use Cases

Numerical algorithms (gradient descent, sort), data pipelines, scripting experiments, preprocessing routines in C / Python.

Limitations

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
Key Characteristics
Mutable state  ·  Explicit control flow  ·  Sequential execution  ·  Direct hardware mapping
7.1 Programming Paradigms

Object-Oriented Programming (OOP)

Core Idea

Programs are organised as objects — encapsulated bundles of state (attributes) and behaviour (methods). Relationships modelled via inheritance & composition.

AI Use Cases

Neural network layer classes (PyTorch nn.Module), agent architectures, simulation environments, game AI, robotics frameworks.

OOP Pillars in AI

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()
)
7.1 Programming Paradigms

Functional Programming

Core Idea

Computation as evaluation of pure functions — no side effects, immutable data, higher-order functions, declarative transformations.

AI Use Cases

Data transformation pipelines (map/filter/reduce), JAX auto-differentiation, Haskell probabilistic models, Spark ML pipelines.

Why FP suits AI

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))
7.1 Programming Paradigms

Logic Programming

Core Idea

Programs are expressed as facts and rules; the engine performs automated inference to answer queries. Describes what to compute, not how.

AI Use Cases

Expert systems, knowledge graphs, natural language processing (constraint solving), medical diagnosis, planning (STRIPS/PDDL).

Languages

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.
Key: Unification & backtracking make inference automatic — no explicit search algorithm needed
7.1 Programming Paradigms

Event-Driven Programming

Core Idea

Program flow driven by events — signals, user actions, sensor readings, messages. Handlers (callbacks/listeners) respond asynchronously.

AI Use Cases

Real-time AI (fraud detection, intrusion detection), chatbot interfaces, autonomous robot reactions, IoT sensor fusion, reinforcement learning environments.

Key Patterns

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())
7.1 Programming Paradigms

Dataflow Programming

Core Idea

Programs modelled as a directed graph of operations. Nodes represent computations; edges represent data flowing between them. Execution driven by data availability.

AI Use Cases

TensorFlow computation graphs, Apache Spark ML, ML pipelines (scikit-learn Pipeline), Airflow DAGs for training workflows.

Advantages for AI

Automatic parallelism  ·  GPU scheduling
Lazy evaluation  ·  Easy graph optimisation
Visual debugging of pipelines

Raw Data Normalise Augment Model Train TensorFlow / Spark DAG pattern Input Node Output Node
7.1 Programming Paradigms

Paradigm Comparison Table

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
7.1 Programming Paradigms

Choosing the Right Paradigm

Ask: What is the AI task?

Pattern recognition / prediction → Dataflow / OOP (deep learning)
Rule-based / expert → Logic
Real-time response → Event-Driven

Ask: What are the scale needs?

Single machine, prototyping → Imperative / OOP
Distributed big data → Functional / Dataflow
Edge / embedded → Imperative (C/C++)

Ask: How critical is correctness?

Mission-critical → Functional (verifiable purity)
Rapid experimentation → OOP / Imperative
Safety constraints → Logic / hybrid

7.1 Programming Paradigms

Decision Flowchart — Paradigm Selection

AI Task Selection Real-time events? Event-Driven YES Rule-based knowledge? NO Logic Prog. YES Large-scale data / DL? NO Dataflow / FP YES Complex architecture? NO OOP / Hybrid YES Imperative / Procedural NO Examples: ROS, async IO Examples: Prolog, Datalog Examples: TF, Spark, JAX
7.2
Integration of Different
Programming Paradigms
Hybrid Architectures · Polyglot Systems · Multi-language Pipelines
7.2 Integration

Why Multiple Paradigms in One AI System?

No Single Paradigm is Universal

Real AI systems have many subsystems — each may require a different computational style. A one-paradigm approach forces unnatural solutions.

Benefits of Integration

  • Use each paradigm where it excels
  • Leverage best-of-breed libraries per language
  • Separate concerns cleanly across system boundaries
  • Incremental adoption of new techniques
Example: Self-Driving Car System
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
7.2 Integration

Hybrid AI Architecture

Data Sources Layer Sensors / IoT Databases APIs / Streams Documents Images / Video User Interactions Processing Layer — Functional & Imperative Paradigms Data Cleaning(Functional — Spark/Pandas) Feature Engineering(Imperative — NumPy/SciPy) Knowledge Extraction(Logic — Prolog/SPARQL) Stream Processing(Event-Driven — Kafka/Flink) AI Core — OOP & Dataflow Paradigms ML Models(OOP — PyTorch/sklearn) Deep Learning(Dataflow — TensorFlow) Reasoning Engine(Logic — expert system) Reinforcement Learning(Functional+OOP — stable-baselines) Interface & Deployment Layer — Event-Driven REST / GraphQL API Web / Mobile UI Monitoring & Alerts Edge / Embedded Deployment
7.2 Integration

Example: Python + Prolog (OOP + Logic)

Use Case: Medical Diagnosis System

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 / NLP ML Models Prolog Logic Rules Inference pyswip bridge Symptoms → Diagnosis Patient object → Prolog query
# 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'}, ...]
7.2 Integration

Example: Python + TensorFlow + SQL (Multi-Paradigm)

Use Case: E-Commerce Recommendation

SQL retrieves historical orders (declarative)
Python cleans & engineers features (imperative/functional)
TensorFlow trains the recommendation model (dataflow)

Paradigm Roles

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()
7.2 Integration

Example: ROS + C++ + Python (Robotics AI)

Use Case: Autonomous Mobile Robot

ROS (Robot Operating System) uses event-driven pub/sub messaging to coordinate modules written in different languages and paradigms.

ROS Middleware Pub/Sub Topics C++ Node Sensor Driver LIDAR / Camera Python Node Object Detection PyTorch DL model C++ Node Path Planning A* / Dijkstra Python Node Motor Control PID Controller
# 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())
7.2 Integration

Multi-Language AI Pipelines

Integration Mechanisms

  • REST / gRPC APIs — language-agnostic service calls
  • Message Queues — Kafka, RabbitMQ for async pipelines
  • Shared memory / files — numpy memmap, Arrow IPC
  • FFI (Foreign Function Interface) — ctypes, JNI, CFFI
  • Containers (Docker) — isolate language environments
  • Orchestration (K8s, Airflow) — coordinate across services
R / SQL Data Collection Python Preprocessing Python/JAX Training C++ / TRT Optimisation Go / Node API Serving Python Monitoring gRPC / Apache Arrow REST API / Kafka Integration mechanisms across languages Docker / Kubernetes Orchestration
7.2 Integration

Benefits & Challenges of Paradigm Integration

Benefits

  • Each component uses the most suitable tool/paradigm
  • Encourages modular, loosely-coupled architecture
  • Independent scaling of subsystems
  • Easier to replace/upgrade individual components
  • Access to best-of-breed open-source libraries
  • Parallel development by specialised teams

Challenges

  • Increased operational complexity (DevOps overhead)
  • Data serialisation overhead at language boundaries
  • Debugging across languages and paradigms is harder
  • Inter-service latency in distributed pipelines
  • Consistency: different type systems and null handling
  • Team skill requirements span multiple languages
Key Principle: The right integration strategy balances engineering simplicity with optimal performance — avoid polyglot complexity unless it provides clear, measurable benefits.
7.3
AI System Development
Life Cycle
Problem → Data → Model → Deploy → Monitor
7.3 AI Development Lifecycle

AI Development Lifecycle — Overview

1
Problem
Definition
2
Data
Collection
3
Data
Preprocessing
4
Feature
Engineering
5
Model
Selection
6
Model
Training
7
Evaluation
8
Deployment
9
Monitoring &
Maintenance
 Iterative process — insights from later stages feed back into earlier ones
7.3 AI Development Lifecycle

Phase 1: Problem Definition

What to Define

  • Business / research goal in clear, measurable terms
  • Whether AI is even the right solution
  • Type of problem: classification, regression, clustering, generation?
  • Success criteria and evaluation metrics
  • Constraints: latency, cost, explainability requirements

Common Mistakes

Vague goals ("make it smarter") · Ignoring data availability · Skipping feasibility analysis · Underestimating deployment complexity

Problem Definition Checklist
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
7.3 AI Development Lifecycle

Phase 2: Data Collection

Structured Data

Relational databases (SQL), spreadsheets, CSV files, ERP systems. Well-organised, easy to query but may need joins and aggregation.

Unstructured Data

Text (web scraping, NLP corpora), images (cameras, Flickr API), audio (recordings), video. Requires specialised preprocessing pipelines.

Real-time Streams

IoT sensors, social media APIs (Twitter/X firehose), financial ticks, server logs. Needs stream processing (Kafka, Flink).

Synthetic Data

Generated data when real data is scarce or private. GANs, simulation (robotics), data augmentation, faker libraries.

Data Labelling

Manual annotation (LabelImg, CVAT, Label Studio), crowdsourcing (MTurk), weak supervision (Snorkel), semi-supervised techniques.

Data Governance

GDPR / privacy compliance, data lineage, consent management, data versioning (DVC), access controls, audit trails.

7.3 AI Development Lifecycle

Phase 3: Data Preprocessing

Why Preprocessing Matters

"Garbage in, garbage out" — real-world data is messy, incomplete, and inconsistent. Preprocessing converts raw data into clean, model-ready inputs.

  • Handling missing values: mean/median imputation, interpolation, or removal
  • Outlier detection: IQR, Z-score, isolation forests
  • Normalisation / scaling: Min-Max, Z-score, RobustScaler
  • Encoding categoricals: One-hot, label, target encoding
  • Text cleaning: tokenisation, stop-word removal, stemming, lemmatisation
  • Image preprocessing: resize, crop, histogram equalisation
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")
7.3 AI Development Lifecycle

Phase 4: Feature Engineering

What is Feature Engineering?

The process of using domain knowledge to create, transform, or select input variables that help machine learning algorithms perform better.

Creation

Combine/derive signals (e.g. rush hour from timestamp)

Reduction

PCA, t-SNE — reduce noise, compress features

Selection

SHAP, mutual info — keep relevant variables

Embeddings

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%}")
7.3 AI Development Lifecycle

Phase 5: Model Selection

Classical ML

When: Structured/tabular data, small-medium datasets, interpretability needed
Examples: Linear/Logistic Regression, SVM, Decision Trees, Random Forest, XGBoost

Deep Learning

When: Images, text, audio, video; very large datasets; raw feature input
Examples: CNNs, RNNs/LSTMs, Transformers, GANs, Diffusion models

Reinforcement Learning

When: Sequential decisions, environment simulation available, exploration needed
Examples: DQN, PPO, A3C, SAC, AlphaZero

Knowledge-Based

When: Expert knowledge encoded as rules; explainability mandatory
Examples: Expert systems, Bayesian networks, ontologies

Ensemble Methods

When: Maximum accuracy needed; diverse models available
Examples: Bagging, Boosting (XGBoost, LightGBM), Stacking

Selection Criteria

Data size & type · Latency requirements · Explainability · Available compute · Team expertise · Baseline performance

7.3 AI Development Lifecycle

Phase 6: Model Training

Training Process

  • Split data: train / validation / test (e.g. 70/15/15)
  • Define loss function (MSE, cross-entropy, custom)
  • Choose optimiser (SGD, Adam, RMSprop)
  • Set hyperparameters (learning rate, batch size, epochs)
  • Train on GPU/TPU with gradient-based optimisation
  • Monitor training curves — detect overfitting early

Hyperparameter Tuning

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)
7.3 AI Development Lifecycle

Phase 7: Evaluation

Classification Metrics

Accuracy — overall correct rate
Precision — TP / (TP+FP)
Recall — TP / (TP+FN)
F1-Score — harmonic mean of P & R
AUC-ROC — ranking quality

Regression Metrics

MAE — Mean Absolute Error
MSE / RMSE — penalises large errors
— explained variance
MAPE — percentage error

NLP Metrics

BLEU — translation quality
ROUGE — summarisation recall
Perplexity — language model quality
BERTScore — semantic similarity

Robustness Testing

Adversarial inputs · Distribution shift · Edge cases · Fairness across demographic groups

Explainability (XAI)

SHAP values · LIME · Attention maps · Grad-CAM for CNNs · Feature importance plots

Failure Analysis

Confusion matrix analysis · Error case review · Bias audits · Hold-out test set — never tune on this!

7.3 AI Development Lifecycle

Phase 8: Deployment

Deployment Patterns

  • REST API — Flask, FastAPI, TorchServe, TF Serving
  • Batch inference — scheduled jobs on stored datasets
  • Streaming inference — Kafka + real-time pipelines
  • Edge AI — TFLite, ONNX Runtime, CoreML on device
  • Cloud — AWS SageMaker, GCP Vertex AI, Azure ML

MLOps & CI/CD for ML

Model versioning (MLflow) · Container packaging (Docker) · Automated testing · Blue/green & canary deployments · Model registry

Train & Validate MLflow tracking Package Model Docker + ONNX Model Registry Version control Cloud API SageMaker Edge Device TFLite/CoreML Batch Job Spark / Airflow Monitor & Alert Prometheus / Grafana Retrain loop
7.3 AI Development Lifecycle

Phase 9: Monitoring & Maintenance

What to Monitor

  • Data drift — input distribution changes over time
  • Model drift / degradation — accuracy dropping in production
  • System performance — latency, throughput, error rates
  • Fairness metrics — bias emergence in production
  • Resource utilisation — CPU/GPU/memory/cost

Maintenance Activities

  • Periodic retraining with fresh data
  • Champion / challenger model A/B testing
  • Model documentation updates
  • Security patches and dependency updates
Monitoring Tools
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

The Feedback Loop

Monitoring insights feed back to data collection, model retraining, or even problem redefinition — making the lifecycle truly iterative.

7.3 AI Development Lifecycle

Lifecycle Summary Diagram

1. Problem Definition Goals, metrics, feasibility 2. Data Collection Sources, labelling, governance 3. Preprocessing Clean, normalise, encode 4. Feature Eng. Create, select, reduce 5. Model Selection ML type, architecture 6. Model Training Optimise & tune 7. Evaluation Metrics, XAI, bias audit 8. Deployment API, edge, MLOps 9. Monitoring Drift, retrain, updates Iterative Feedback Loop — Insights Drive Continuous Improvement ⟳ Iterative Nature Poor evaluation → revisit training Drift detected → retrain model
7.4
Case Studies of AI Systems
ChatGPT · Tesla Autopilot · Netflix · AlphaGo · Healthcare AI
7.4 Case Studies

Case Study 1 — ChatGPT / Large Language Models

OpenAI · GPT-4 Architecture · Transformer-based text generation

Programming Paradigms Used

OOP — PyTorch nn.Module Dataflow — TF/JAX graphs Functional — JAX transforms Event-Driven — streaming API

Lifecycle Phases Highlighted

  • Data: ~570 GB text from web, books, Wikipedia, code
  • Preprocessing: BPE tokenisation, deduplication, filtering
  • Model: Transformer with 175B+ parameters
  • Training: Pre-training on clusters of A100 GPUs
  • Fine-tuning: RLHF — human feedback reward model
Transformer Architecture (Simplified) "What is AI?" → tokens Token + Positional Embedding Multi-Head Self-Attention 96 attention heads (GPT-4) Feed-Forward Network Expand → GELU → Project ×N Output Projection Softmax → next token probability Generated Text "Artificial Intelligence is…"
7.4 Case Studies

Case Study 2 — Tesla Autopilot

Real-time perception, path planning & control for autonomous driving

Programming Paradigms Used

Dataflow — neural net inference Event-Driven — real-time callbacks OOP — vehicle abstraction Logic — safety rules Imperative C++ — control

System Architecture Layers

  • Perception: 8× cameras → HydraNet (multi-task CNN)
  • Prediction: Motion forecasting for vehicles & pedestrians
  • Planning: Occupancy network + cost-based path planner
  • Control: PID + MPC to actuate steering, throttle, braking
  • Shadow mode: Fleet learning from millions of cars
8× Camera 360° view 1.2 MP each FSD Chip 144 TOPS HydraNet CNN Neural Planner Actuators Steer / Brake Throttle Occupancy Grid + Path Planning Vector space representation of world Fleet Shadow Mode — Continuous Learning Millions of cars → edge case detection → model updates
7.4 Case Studies

Case Study 3 — Netflix Recommendation System

Personalised content recommendations for 270+ million subscribers

Programming Paradigms Used

Dataflow — Spark/Flink pipelines Functional — immutable transforms OOP — model hierarchy Event-Driven — real-time signals

Recommendation Pipeline

  • Candidate generation: ~1000 items from 200M+ catalogue
  • Ranking model: Deep neural net with 100+ features
  • Contextual features: Time of day, device, country, mood signal
  • A/B testing: Continuous experimentation at scale
  • Result: 80% of content watched via recommendations
Algorithm Layers
Offline Layer — Spark batch jobs: collaborative filtering, matrix factorisation (ALS), user-item embeddings
Nearline Layer — Kafka streams: incremental updates from viewing behaviour in last hours
Online Layer — Real-time: session context, A/B test assignment, final ranking neural net, <100ms response
Key insight: Multiple paradigms operate at different latency tiers simultaneously
7.4 Case Studies

Case Study 4 — AlphaGo / AlphaZero (DeepMind)

Superhuman performance at Go, Chess, and Shogi using deep RL

Programming Paradigms Used

Dataflow — CNN/ResNet OOP — game tree & nodes Event-Driven — move triggers Logic — MCTS rules Functional — self-play

How AlphaGo Works

  • Policy Network: CNN suggests likely moves from board state
  • Value Network: CNN evaluates board position strength
  • MCTS: Tree search guided by both networks
  • Self-play RL: Plays against itself to generate training data
  • AlphaZero: No human data — learns from scratch in 3 days
Board State 19×19 grid input Policy Network "Which moves to try?" Value Network "Who's winning?" Monte Carlo Tree Search Select → Expand → Simulate → Backprop Best Move Output
7.4 Case Studies

Case Study 5 — Healthcare AI: Medical Image Diagnosis

AI-assisted detection of cancer, diabetic retinopathy, and COVID-19 in medical scans

Programming Paradigms Used

Dataflow — CNN inference OOP — patient records Logic — decision rules Event-Driven — alerts

System Pipeline

  • Input: DICOM images from MRI/CT/X-Ray scanners
  • Preprocessing: Windowing, normalisation, augmentation
  • Model: U-Net (segmentation) + ResNet-50 (classification)
  • Explainability: Grad-CAM heatmaps overlaid on scan
  • Integration: HL7 FHIR API to hospital information system

Critical Requirements

FDA/CE approval · HIPAA/GDPR compliance · Explainability for doctors · Fail-safe: refer human MD

MRI / CT Scanner DICOM format DICOM Preprocess Window & Normalise U-Net Segmentation Tumour boundary mask ResNet Classification Malignant / Benign Grad-CAM Explainability Heatmap on scan regions Clinical Safety Rules Confidence < 0.9 → refer MD Report → Hospital HIS (FHIR)
7.4 Case Studies

Comparison of Case Studies

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
7.4 Case Studies

Ethical Considerations in AI Implementation

Fairness & Bias

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.

Transparency & Explainability

"Black box" AI erodes trust. Use XAI tools (SHAP, LIME, Grad-CAM). High-stakes domains (medical, legal) may legally require explanations.

Privacy & Data Protection

Personal data used to train AI must comply with GDPR, HIPAA, CCPA. Techniques: differential privacy, federated learning, data anonymisation.

Safety & Reliability

AI systems in safety-critical domains (autonomous vehicles, medical devices) must be thoroughly tested against adversarial inputs, edge cases, and distribution shifts.

Accountability

Who is responsible when an AI system makes a harmful decision? Clear accountability frameworks must accompany AI deployment. Human oversight is non-negotiable.

Sustainability

Training large models (GPT-4, Gemini) consumes enormous energy. Green AI research focuses on efficient architectures, smaller models, and renewable energy for compute.

7.4 Case Studies

Future Trends in AI System Implementation

  • Foundation Models & Fine-tuning: Pre-trained LLMs adapted to domain-specific tasks with minimal data (LoRA, QLoRA)
  • Multimodal AI: Systems that reason across text, images, audio, video simultaneously (GPT-4V, Gemini)
  • Agentic AI / AutoGPT: AI agents that autonomously plan, use tools, and execute multi-step tasks
  • Neuromorphic & Quantum AI: Brain-inspired hardware and quantum computing for exponential speedups
  • Edge AI proliferation: Efficient models on smartphones, IoT sensors, wearables — no cloud needed
  • Federated Learning: Training across distributed data without centralising sensitive records
  • AI-assisted programming: Tools like GitHub Copilot, Cursor — AI writing the AI systems of the future
  • Automated ML (AutoML): NAS, AutoFeaturization, AutoDeploy reduce human intervention in SDLC
  • Causal AI: Models that reason about cause-and-effect, not just correlations — more robust decisions
  • Regulation & Standards: EU AI Act, ISO/IEC 42001 — formal standards for AI system development
  • Hybrid Neurosymbolic AI: Combining neural networks with symbolic reasoning for interpretable, data-efficient systems
  • AI Safety research: Alignment, interpretability, robustness — making AI reliably beneficial

Unit 7 Summary

7.1 Programming Paradigms

Six major paradigms — Imperative, OOP, Functional, Logic, Event-Driven, Dataflow — each suited to different AI task types. No single paradigm fits all problems.

7.2 Integration

Real AI systems are polyglot. Hybrid architectures combine paradigms at architectural boundaries using APIs, message queues, and containers.

7.3 AI Development Lifecycle

Nine-phase iterative process: Problem → Data → Preprocessing → Features → Model Selection → Training → Evaluation → Deployment → Monitoring. Each phase feeds back into others.

7.4 Case Studies

ChatGPT, Tesla, Netflix, AlphaGo, and Healthcare AI all demonstrate different paradigm combinations driven by their unique constraints: scale, latency, safety, and explainability.

Key takeaway: Implementing an AI system requires both technical mastery (choosing the right paradigm and following the SDLC) and ethical responsibility (fairness, transparency, safety, and accountability).

References

Books & Textbooks

  • Russell, S. & Norvig, P. Artificial Intelligence: A Modern Approach, 4th ed. (2020)
  • Goodfellow, I. et al. Deep Learning, MIT Press (2016)
  • Géron, A. Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow, 3rd ed. (2022)
  • Sculley, D. et al. "Hidden Technical Debt in ML Systems" — NeurIPS 2015

Official Documentation

  • PyTorch Docs — pytorch.org/docs
  • TensorFlow Guide — tensorflow.org/guide
  • scikit-learn User Guide — scikit-learn.org
  • MLflow Documentation — mlflow.org

Research Papers & Articles

  • Vaswani et al. "Attention Is All You Need" (2017) — Transformer architecture
  • Silver et al. "Mastering Go with Deep Neural Networks" — Nature (2016)
  • Esteva et al. "Dermatologist-level classification of skin cancer" — Nature (2017)
  • OpenAI. "GPT-4 Technical Report" (2023)
  • Karpathy. "Tesla AI / Autopilot" — CVPR Workshop (2021)

Online Courses & Resources

  • fast.ai — Practical Deep Learning for Coders
  • DeepLearning.AI — Andrew Ng Specialisations (Coursera)
  • Papers With Code — paperswithcode.com
  • Andrej Karpathy "Neural Networks: Zero to Hero" — YouTube