Docsity

High Performance Data Analytics (HPDA) — Complete Module Revision Guide, Study notes of Computer Science

Partial preview of the text

Download High Performance Data Analytics (HPDA) — Complete Module Revision Guide and more Study notes Computer Science in PDF only on Docsity!

High Performance Data Analytics

Complete Revision & Study Guide

A topic-by-topic guide covering big data foundations, statistics, data cleaning, high performance computing, and the core machine learning methods used in data analytics at scale. Original study notes — independently written summary and explanation

Contents

    1. Foundations: Big Data & Data Analytics
    1. Analytics Process Frameworks
    1. Statistics Refresher
    1. Data Cleaning & Preparation
    1. Tidy Data
    1. High Performance Computing Fundamentals
    1. Tools for Scalable Analytics: Spark, Dask & PyTorch
    1. Supervised Learning: Linear & Logistic Regression
    1. K-Nearest Neighbours Classification
    1. Naive Bayes Classification
    1. Tree-Based Models & Random Forests
    1. Neural Networks
    1. Clustering: K-Means, Gaussian Mixtures & DBSCAN

Solutions: general data cleaning; for unstructured data specifically, transforming it into structured form where possible, storing it using newer technologies such as NoSQL databases, and processing it with analytical techniques built for unstructured content.

Veracity

Veracity is essentially a measure of data quality: the degree to which data are accurate, unbiased, and trustworthy. Challenges: data are often collected for one purpose but later reused for a different one it wasn't designed for, and quality can vary unevenly across a dataset. Solutions: domain expertise is essential for spotting quality issues, alongside systematic data cleaning and data governance policies that standardise how data is collected and processed.

Value

Challenge: understanding how a business can actually extract value from its Big Data, rather than simply accumulating it. Solutions: a cost/benefit analysis can help establish whether processing the data is worthwhile — this becomes more favourable as the cost of storage continues to fall.

1.4 High Performance Computing (HPC): a first look

HPC is the use of specialised computing systems to solve complex problems at scale. The same factors that define Big Data — volume, velocity, and variety — are what typically force analysts beyond the limits of a standard desktop machine. When more CPU power, memory, or storage is required than a conventional setup can provide, the task needs "scaling" — expanding the computational resources available to it. There are two broad approaches:

  • Vertical scaling ("scaling up"): increasing the resources available on a single machine — more CPUs, more memory, or a higher-spec virtual machine. This is usually the easier route, since it typically requires few or no code changes.
  • Horizontal scaling ("scaling out"): increasing the number of machines (nodes) working on the problem, for example by adding more workers to a Spark cluster. This is generally harder, since computation now has to be coordinated across multiple machines. Frameworks such as Spark and Dask exist specifically to make this more manageable.

2. Analytics Process Frameworks

A number of established frameworks describe how a data analytics project should proceed from start to finish. They share a broadly similar shape but differ in emphasis.

2.1 A generic process for a data analytics project

  1. Determine the project goal.
  2. Identify possible data sources and resources.
  3. Obtain the relevant data.
  4. Clean and prepare the data.
  5. Analyse and model the data.
  6. Analyse the results.
  7. Exploit the knowledge obtained.
  8. Return to any earlier step and repeat as necessary.

2.2 CRISP-DM (Cross-Industry Standard Process for Data Mining)

CRISP-DM is the most widely referenced framework, describing commonly used approaches to data analytics problems. It is cyclical rather than strictly linear, and consists of six phases:

  1. Business understanding — clarifying the goals of the project from a business perspective.
  2. Data understanding — getting familiar with the available data and its quality.
  3. Data preparation — cleaning and structuring data ready for modelling.
  4. Modelling — applying analytical or machine learning techniques.
  5. Evaluation — assessing whether the model actually meets the business objective.
  6. Deployment — putting the resulting knowledge or model into practical use. Business understanding and data understanding feed into one another, and the whole cycle typically loops back to business understanding after deployment, reflecting the iterative nature of real analytics projects.

2.3 Other frameworks, briefly

  • KDD (Knowledge Discovery in Databases): centres on finding patterns and knowledge within large volumes of data held in a database.
  • SEMMA (Sample, Explore, Modify, Model, Assess): focuses heavily on modelling and evaluation, generally assuming that clean data is already available, and paying comparatively little attention to data preprocessing.
  • EMC's Data Analytics Lifecycle: takes an iterative approach and, notably, separates model planning from model building as distinct stages.
  • The Data Science Process (O'Neil & Schutt): emphasises the end-to-end process from raw data through to a finished data product.

2.4 Data sources

Data used in a project can come from several types of source:

  • Published data — data already made available by a third party.
  • Experimental data — data generated by running a controlled experiment.

3. Statistics Refresher

3.1 Populations, samples, and data types

A population is the entire collection of people, animals, or things that share a common characteristic of interest. A sample is a subset of units drawn from that population. If the sample size is n, the data can be written as x = (x₁, x₂, ..., x ).ₙ The general goal of a statistical analysis is to find a model that plausibly describes how the characteristic of interest behaves. A sensible strategy is to: (1) consider the type of data; (2) explore it through summary measures and graphs to identify its key features; and (3) choose a model that could reasonably have generated the observed data.

Types of data

  • Quantitative — numerical measurements. These can be discrete (e.g. 5) or continuous (e.g. 12.8).
  • Qualitative — attributes or labels. These can be ordinal (e.g. "good", "fair", "poor", where order matters) or nominal (e.g. colours, where it doesn't).

3.2 Exploratory Data Analysis (EDA)

A handful of summary statistics are used repeatedly throughout data analytics:

  • Sample mean ( ) — the average value:x̄ x̄ = (1/n) · Σxᵢ.
  • Sample mode — the most frequently occurring value.
  • Sample median — the value below which 50% of the data lie.
  • Quantile (Qp) — the value below which p×100% of the data lie.
  • Range — the difference between the maximum and minimum observations.
  • Interquartile range (IQR) — the difference between the 75th and 25th percentiles: IQR = Q0. − Q0.25.
  • Sample variance (s²) — quantifies the spread of the data: s² = 1/(n−1) · Σ(xᵢ − x̄ )².
  • Sample standard deviation (s) — the square root of the variance, used to express the amount of variation in the same units as the original data: s = √s².
  • Sample correlation (ρ) — describes whether the values of one variable move together with those of another (association, not causation). ρ ranges from −1 (perfect negative correlation) through 0 (no correlation) to +1 (perfect positive correlation).

Graphical tools

For quantitative data: boxplots, histograms, scatterplots, and time-series plots. For qualitative data: frequency tables and bar charts.

3.3 Random variables and probability distributions

A random variable (RV) is a variable whose possible values are the numerical outcomes of a random event. A discrete RV only takes distinct values (e.g. 0, 1, 2, ...); its probability mass function f(x) = P(X = x) gives the probability of each possible value, and these probabilities must sum to 1. The cumulative distribution function is F(x) = P(X ≤ x) = Σ f(y) for y ≤ x, from which P(X > x) = 1 − F(x). The expected value E(X) represents the long-run average outcome of repeating the experiment: E(X) = Σ x·f(x). The variance is Var(X) = E[X − E(X)]² = E[X²] − E[X]².

Bernoulli distribution

Describes a single trial with two outcomes — success (1) or failure (0) — such as one coin toss. If p is the probability of success, then E(X) = p and Var(X) = p(1 − p).

Binomial distribution

Describes the total number of successes across n independent Bernoulli trials, each with success probability p — essentially, "many Bernoulli trials at once". Its mean and variance are E(X) = np and Var(X) = np(1 − p).

Poisson distribution

Used to model rare events — effectively the limiting case of a Binomial distribution with a large n and a small p. Both its mean and variance equal the rate parameter λ: E(X) = Var(X) = λ. A classic example is modelling the number of goals scored in a football match.

Continuous random variables

A continuous RV can take an uncountable number of possible values, so the probability of it taking any single exact value is zero. Instead, probability is described by a probability density function f(x), where the probability of the RV falling in an infinitesimally small interval dx is f(x)dx, and the total area under f(x) integrates to 1.

Normal distribution

The most important continuous distribution, characterised by its mean μ and variance σ². Its density is bell-shaped and symmetric around μ.

Central Limit Theorem (CLT)

Large sums of random variables with finite variance approximately follow a Normal distribution — one of the reasons the Normal distribution appears so often in statistics.

3.4 Maximum Likelihood Estimation (MLE)

MLE is a method for working out which parameter values were most likely to have generated an observed dataset. The likelihood function L(θ, x) is the joint probability (or density) of the observed data, viewed as a function of the unknown parameter θ, given by the product of the individual densities: L(θ, x) = ∏ f(xᵢ, θ). The value θ̂ that maximises this likelihood is the maximum likelihood estimate — the most plausible model for the observed data. In practice it is usually easier to work with the log-likelihood, l(θ, x) = log L(θ, x), since the logarithm turns the product into a sum.

Recipe for computing the MLE

  1. Write down the likelihood: L(θ, x) = ∏ f(xᵢ, θ).
  2. Take the log-likelihood: l(θ, x) = Σ log f(xᵢ, θ).
  3. Differentiate with respect to θ and set the result to zero.
  4. The variance of the estimate is given by the (negative) inverse of the expected second derivative of the log-likelihood.

Properties of the MLE

  • Consistent: θ̂ → θ as the sample size n → ∞.
  • Asymptotically unbiased: E( θ̂ ) → θ as n → ∞.
  • Efficient: Var( θ̂ ) → 0 as n → ∞.

4. Data Cleaning & Preparation

Data cleaning and preparation form a large part of any data project's lifecycle. The guiding principle is simple: garbage in, garbage out — the veracity of the data is crucial to achieving any meaningful analytical goal. For results to be valid, datasets need to be:

  • Valid in the context of the business domain.
  • Accurate when compared against the true values.
  • Complete, with no missing records.
  • Consistent, within the dataset and across multiple datasets.
  • Recorded in a uniform unit of measure for each feature.

4.1 Data provenance

Before cleaning begins, it is important to understand a dataset's history: how was it created? Have any transformations already been applied? Are there known problems, such as miscalibration of a measuring instrument? What assumptions can reasonably be made, and could the data contain hidden biases? Metadata often provides useful clues here.

4.2 The data cleaning workflow

Cleaning is best thought of as a cyclical, iterative process with four stages: inspection, cleaning, verification, and reporting. Each stage feeds back into the others as issues are discovered.

Inspection

Goal: understand the dataset's qualities, verify assumptions, and detect errors — in short, "trust but verify". This is closely tied to EDA, and typically covers data types, profiling (min/max/mean/standard deviation), and visualisation (distributions, histograms, correlations).

Cleaning

Goal: fix the issues found during inspection, or remove invalid data. This happens in two broad steps: first, converting raw data into a technically correct form; second, converting technically correct data into a consistent form suitable for analysis.

Verification

Goal: confirm that the cleaned data meets expectations, and that any specified constraints or business rules have actually been satisfied.

Reporting

Cleaning steps and modifications should be documented, both to demonstrate that the data is ready for analysis and to preserve provenance for future users. Continuous improvement matters too — reviewing how errors arose can feed back into how data is generated or collected in future. Reproducibility is also important: scripts and documentation should be kept in a version control system such as Git, since the cleaning process may need to be repeated or verified later.

4.3 From raw to technically correct data

Technically correct data means that each value can be directly recognised as belonging to a specific variable, and is stored using a data type that matches the real-world variable it represents. Concretely: numeric values are stored as numbers rather than text; dates and times use appropriate formats rather than free text; and formatting is consistent throughout the dataset.

Common techniques include parsing numeric and date values out of strings, ensuring consistent character encoding, normalising strings (e.g. removing stray whitespace), and re-coding categorical variables into a consistent scheme (e.g. standardising "f" and "female" to a single category).

4.4 From technically correct to consistent data

Consistent data is technically correct data that is genuinely fit for statistical analysis. This requires:

  • In-record consistency — no contradictory information within a single record.
  • Cross-record consistency — no contradictions between records for the same variable.
  • Cross-dataset consistency — the dataset agrees with other datasets covering the same subject matter.

Missing values

Missing data must be understood and handled before analysis. Software typically represents missingness with a special value (e.g. None in Python) — and it's important not to confuse a genuinely missing value with a valid default or category ("unknown" can itself be a meaningful category). Ideally, the reason data are missing should be understood before deciding how to handle it. Options include removing the affected record (reasonable when only a small number of records are affected), imputing a replacement value such as the mean, or removing the feature entirely if it is too sparse to be useful.

Outliers

An outlier is an observation that lies abnormally far from the main body of the distribution. Outliers are not automatically errors — they should be detected, but not automatically removed. Whether to include them in an analysis is a statistical judgement, not an automatic rule. They are typically found through distribution visualisations such as boxplots, density plots, and histograms.

Inconsistencies

These occur when a record contains a value, or combination of values, that cannot correspond to a real-world situation — for example, an under-age person appearing in a dataset of driving licences. Automated checks (e.g. specifying a valid age range) can catch many of these.

Duplicate records

Duplicates may need to be removed to keep an analysis valid, though this depends on data provenance — some duplicates are perfectly valid (e.g. multiple prescriptions dispensed at a pharmacy on the same day). In such cases, appending an auto-incrementing identifier to each record can help distinguish genuine repeats from duplication errors.

Deleting features

It can be sensible to remove features that are unrelated to the analytics goal — for example, a customer's email address in a study of spending habits. More importantly, "cheating" features — proxies for the outcome you are trying to predict — should be removed. For example, if a dataset contains a code that identifies early redeemers of an offer, and the goal is to predict who will redeem early, that code needs to be dropped, since it would let the model "cheat" by looking at the answer.

Confounding and proxy variables

A confounding variable creates an apparent relationship between two variables that is really driven by both variables' relationship with a third variable (the classic example being shoe size and reading ability in children, both really driven by age). This is why correlation does not imply causation.

5. Tidy Data

Data tidying means structuring datasets to make manipulation, visualisation, and modelling straightforward.

5.1 Principles of tidy data

A dataset is considered tidy when:

  1. Each variable forms a column.
  2. Each observation forms a row.
  3. Each type of observational unit forms its own table (an observational unit being the entity that information is collected on). In relational database theory, this effectively corresponds to Third Normal Form (3NF): a relation R is in 3NF if and only if its non-key attributes are mutually independent, and fully dependent on the primary key of R.

5.2 Common problems in messy datasets

  1. Column headers are values, rather than variable names.
  2. Multiple variables are stored in a single column.
  3. Variables are stored in both rows and columns.
  4. Multiple types of observational unit are stored in the same table.
  5. A single observational unit is spread across multiple tables.

5.3 Normalisation and denormalisation

Normalisation is useful for tidying data and removing inconsistencies. However, many machine learning and modelling libraries expect a single flat table or file as input. Depending on the tool being used, it may therefore be necessary to denormalise data — merging several related tables (relations) back into one large flat table.

6. High Performance Computing Fundamentals

By default, software runs on a single system using a single thread of execution. When writing complex programs, or processing large-scale data, parallel execution becomes necessary. This need arises from three main constraints:

  • CPU — runtime is largely determined by processor speed.
  • Memory — the available memory limits how much can be processed at once.
  • I/O — runtime is affected by reading/writing to disk or waiting on network communication.

6.1 Assessing serial performance first

Before parallelising anything, it's important to understand a program's performance characteristics. Common approaches include measuring runtime at different problem scales and plotting the results, monitoring system resources during execution, and instrumenting the program with logging or profiling. Profiling in particular calculates the total running time of each function or statement, and how many times each was called — this is essential for finding out where the real bottlenecks are before spending effort optimising the wrong part of the code.

6.2 Processes and threads

A process represents the executing state of a program. A process contains one main thread of execution and can spawn additional threads; all threads within a process share the same memory space. A thread executes program instructions on a CPU, and threads are scheduled onto CPUs by the operating system. A process may also spawn child processes — unlike threads, child processes do not share their parent's memory space.

6.3 Concurrency vs. parallelism

Concurrency means decomposing a problem into multiple independent tasks. Parallelism means actually executing multiple tasks at the same time. Multiple threads can run concurrently on a single CPU core, but not truly in parallel — the operating system rapidly switches which thread occupies the core, creating the illusion of parallelism, even though only one thread is genuinely executing at any instant. True parallelism requires multiple cores, each genuinely running a task simultaneously.

6.4 Data parallelism and task parallelism

Data parallelism (domain decomposition)

The dataset is partitioned across several worker tasks, each of which processes its own subset in parallel. The general pattern is: split the dataset by some heuristic or function, apply a common operation across every partition, then combine (gather) the intermediate results back together. Properties: parallel efficiency scales with problem size, and this approach is straightforward for "embarrassingly parallel" problems — those with no dependencies between tasks. It can be implemented using shared memory on a single node, or message passing across a cluster. Limitations: splitting and combining introduce communication overhead, reducing the theoretical performance gain, and overall performance is limited by the speed of the slowest worker.

Parallel efficiency = t₁ / (N × t_N) This is sometimes referred to as "weak scaling" — how much work can be completed in a fixed time, as opposed to "strong scaling", which asks how much faster a fixed amount of work can be completed.

6.7 GPUs and hardware acceleration

CPUs are general-purpose computation devices. "Hardware acceleration" refers to using specialised hardware to boost the efficiency of common data processing patterns. Accelerators can be roughly classified into GPUs (Graphics Processing Units), FPGAs (Field Programmable Gate Arrays), and ASICs (Application Specific Integrated Circuits). GPUs were originally designed for graphics rendering in games and 3D modelling, but were later discovered to be excellent for training deep learning models, and are now ubiquitous for that purpose. GPUs are built for high degrees of data parallelism — able to execute the same instruction across many thousands of data points in parallel — though they typically support a smaller instruction set than a CPU. Because GPUs act as co-processors, specialised software libraries (such as PyTorch or TensorFlow) are required to make use of them.

Summary

  • Profile your application first, to understand where the actual bottlenecks are.
  • Scale up first, since it is generally the simpler option.
  • Scale out only once the resources on a single node are no longer sufficient.
  • Hardware accelerators such as GPUs can significantly improve throughput for suitable workloads.

7. Tools for Scalable Analytics: Spark, Dask & PyTorch

High Performance Data Analytics (HPDA) is the term used for the intersection of big data analytics and high performance computing: Big Data Analytics + HPC = HPDA. In practice, this means using the parallel processing capability of HPC to run large-scale, powerful analytics software.

7.1 Parallelism in Python

Python provides built-in high-level libraries for both multi-threading and multi-processing. Libraries such as NumExpr and NumPy can speed up Python code through vectorisation and multi-threading, and some libraries — such as scikit-learn's njobs option — use multi-processing to parallelise tasks like ML training, though in practice the scaling achieved this way is limited. A key constraint is the Python Global Interpreter Lock (GIL), which prevents true multi-threaded parallelism within a single Python process. Each separate Python process, however, has its own GIL. Libraries like NumExpr and NumPy compile down to native code, allowing them to sidestep the GIL restriction.

7.2 Apache Spark

Apache Spark is an engine for running data engineering, data science, and machine learning workloads, either on a single machine or across a cluster. Key features include support for streaming data, general analytics, data science at scale, and machine learning.

How Spark runs on a cluster

A Spark cluster has three main components: the driver program (which contains the SparkContext), the cluster manager, and the worker nodes (each running executors that carry out tasks and hold cached data). Spark supports several cluster managers, including its own built-in Standalone manager (which makes setting up a cluster straightforward), Hadoop YARN, and Kubernetes.

Why Apache Spark?

Spark's core strength is its focus on in-memory computation — intermediate results are held in memory rather than repeatedly written to disk. It offers APIs across multiple languages (Scala, Java, Python via PySpark, SQL, and R), and includes purpose-built libraries for different workflows: Spark ML (machine learning), Structured Streaming, Spark SQL, and GraphX.

Spark operators: transformations and actions

Transformations create a new Spark DataFrame without altering the original. They are lazily evaluated, and split further into:

  • Narrow transformations — take a single input partition and return a single output partition (e.g. a filter operation).
  • Wide transformations — draw on multiple partitions and require the data to be re-shuffled (e.g. a groupBy operation). Actions, by contrast, are eagerly executed and produce a concrete result — for example the outcome of a chain of transformations. Common actions include count, collect, and saveAsTextFile.

Spark's data APIs

  • RDD (Resilient Distributed Dataset) — the original, low-level distributed collection API.
  • DataFrame — a higher-level, tabular API, broadly similar in spirit to a Pandas DataFrame.

7.4 PyTorch and AI frameworks

Demand for machine learning and AI has grown enormously, and the surrounding community and tooling has grown along with it. PyTorch, first released in 2016, is primarily used through Python (its underlying engine, Torch, also supports C and Lua). It applies the computational power of Torch to build a modern machine learning library suited to computer vision and natural language processing. It underlies large-scale AI workloads at major technology companies and is used across sectors from customer service to social media. PyTorch supports rapid deployment of new models, flexible computational graphs that can be modified on the fly, and implementation of a wide range of network architectures, including Convolutional Neural Networks (CNNs), Long Short-Term Memory networks (LSTMs), and Recurrent Neural Networks (RNNs). Its design follows three guiding principles: usability over raw performance, simplicity over cleverness, and a Python-first approach.

8. Supervised Learning: Linear & Logistic Regression

8.1 What is Machine Learning?

Usually, solving a problem on a computer requires an algorithm that transforms an input into an output. For some tasks, however, no such algorithm is readily available — machine learning instead extracts a model, or algorithm, directly from data (a spam filter is a classic example: nobody writes an explicit rule for "spam", the system learns one from labelled examples).

Types of machine learning

  • Supervised learning — data consists of inputs X and known outputs Y; the task is to learn the mapping X → Y. This is classification if Y is a categorical variable, or regression if Y is a continuous number.
  • Unsupervised learning — data consists only of inputs X; the task is to find structure within it (e.g. grouping similar customers or images).
  • Reinforcement learning — an interactive scenario in which an agent interacts with an environment; the task is to learn a policy that maximises reward (common in robotics). A typical ML workflow moves through: problem definition, data preprocessing, learning, evaluation, and prediction. The choice of model depends on data quality, data volume, and data coverage on the input side, and on accuracy requirements and output format on the output side — a medical application, for example, generally demands much higher accuracy than something like a CAPTCHA. Since ML is fundamentally data-driven, a model is only ever as good as the data it was trained on, which is why the data analytics steps covered earlier — understanding sources and biases, identifying relevant data, cleaning, and structuring — matter just as much for ML as for any other kind of analysis. In supervised learning, data is split into a training set and a test set, and test data should never be allowed to leak into training. "MLOps" refers to the practical implementation and ongoing management of ML systems in production. Note also that, in an HPC context, simpler models often generalise better than very complex ones.

8.2 Linear regression

Consider predicting a continuous outcome — for example, the weight of a cat's heart from its body weight — using a linear model: y = θ₀ + θ₁x This assumes there is a dependency between X and Y, and that the dependency is linear. Here θ₀ is the intercept (also called the bias), and θ₁ is the slope of the line. Given a training set {(x⁽¹⁾, y⁽¹⁾), (x⁽²⁾, y⁽²⁾), ..., (x⁽ᵐ⁾, y⁽ᵐ⁾)}, the model's predictions are h(x) = θ₀ + θ₁x, and the cost (mean squared error) is: Cost = (1/m) × Σ (y⁽ⁱ⁾ − hθ(x⁽ⁱ⁾))² The goal is to find the values of θ₀ and θ₁ that minimise this cost, giving the best linear prediction.

Gradient descent

Gradient descent finds these optimal parameters iteratively: start with arbitrary initial values, then repeatedly adjust the parameters to reduce the cost, using the gradient to determine the direction that reduces cost, until the minimum is reached.