Skip to main content
Data Management for Machine Learning

Data Integration and Data Transformation

Published: 2026-08-07
Level: postgraduate
Audience: Postgraduate students in Machine Learning, Data Science, and Data Engineering

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • Data Profiling and Data Quality Dimensions — covered in Lecture 8 (Data Profiling; Data Quality Dimensions) and Lecture 1 (Data Quality).
  • Outlier Detection — covered in Lecture 6 (Are Outliers Good or Bad?) and Lecture 8 (Outliers).
  • Bias and Fairness — covered in Lecture 8 (The Many Kinds of Bias).
  • Data Leakage — covered in Lecture 8 (Data Leakage) and Lecture 7 (Train, Validate, Test Partitioning and Data Leakage).
  • Data Drift, Model Drift, and Concept Drift — covered in Lecture 8 (Model Drift and Training-Serving Skew).
  • Data Drift Detection Metrics — covered in Lecture 8 (Drift Detection: PSI, KL Divergence, and Entropy).
  • Data Integration — covered in Lecture 5 (Data Ingestion and Integration).
  • Data Transformation — covered in Lecture 5 (Data Transformation) and Lecture 8 (ETL versus ELT and Ingestion Tools).

Data Integration and Data Transformation

This lecture closes out the data profiling work from earlier sessions, then moves into the two big themes of the day: data integration (bringing data from many sources into one place) and data transformation (reshaping raw data so models and reports can actually use it). Along the way the material covers data engineering, the patterns people use to organize transformation work, drift detection metrics, and a leadership story about honesty that ties back to data leakage.

Roadmap for this lecture:

  • 9.1–9.4 — Data quality first. Profiling, the data quality dimensions, outlier detection, bias and fairness, and data leakage. This part answers the question: how do you know the data is worth feeding to a model?
  • 9.5–9.6 — Why models decay. Data drift, model drift, concept drift, and the metrics used to detect them (the Population Stability Index and KL divergence).
  • 9.7–9.8 — Profiling's role and the honesty story. Where data profiling sits in ML data readiness, plus the king's final test — a story that maps directly onto data quality and leakage.
  • 9.9–9.12 — The engineering core. Data integration, data engineering, data transformation, and the layered patterns (medallion architecture and the DBT pattern) used to organize transformation work.
  • Appendices — Exam guidance summary and key industry applications.

One theme runs through the entire lecture: in machine learning, most of the effort goes into the data, not the model. The same data set can be sliced many ways, and the quality of those slices — how complete, how consistent, how unbiased, how leak-free — decides whether the model built on top can be trusted at all.

9.1 Data Profiling and Data Quality Dimensions

9.1.1 Profiling: The CV of Your Data

Hook: How would you judge a data set you have never seen before — and would you trust a model trained on it? Before any data enters a pipeline, you need its "profile," and that profile is built the same way a person builds a CV.

Data profiling means systematically examining a data set — a customer table, a product list, a transaction log, or any kind of data — before it goes into a pipeline. The core analogy from the session is your CV. When you apply to a company, your profile talks about everything about you: leadership, team spread, technical skills, project management skills, process. The same holds for data. A person has multiple dimensions — a singer, a trust runner, a professor, a consultant, a trainer, an SME, a father, a son — and depending on what we are trying to do, we need to bring in more about the specific dimension that matters. Data is exactly the same: different situations need different slices of the same data set.

Why does profiling matter so much? The one mantra: garbage in, garbage out. People spend roughly 80% of their effort only on data — collecting it, cleaning it, validating it, understanding it — so data profiling and data validation are very, very important. This applies whether you build a data pipeline, a data warehouse, or a lakehouse: every layer downstream inherits whatever quality (or garbage) entered upstream.

Scope — what profiling is not: Profiling is a pre-pipeline examination. It does not fix the data, does not transform it, and does not build the model. It tells you what the data is, where it came from, what it contains, and how healthy it is — the fixing and transforming come later in the pipeline (Sections 9.11 and 9.12). If you skip profiling, every downstream problem — missing values, duplicate rows, broken references — is discovered late, when the cost of fixing it is highest.

Real-world context: organizations everywhere are adopting generative AI tools for data pipelines and for many other tools; everything is being automated with Gen AI. Banking teams were being trained on Gen AI adoption for data pipelines while the session was running — a sign that profiling and pipeline-building are being actively automated across the industry.

9.1.2 The Data Quality Dimensions

Before you profile any data, you check it across several quality dimensions — a quality dimension is nothing but a measurement of an attribute, a variable, or a feature; we assess it, interpret it, and improve it. The dimensions read out in the session were:

Timeliness, uniqueness, traceability, reliability, validity, completeness, accessibility, integrity, accuracy, and consistency.

Each dimension answers a specific question about the data:

Dimension Question it answers
Timeliness Is the data current enough for the decision we are making?
Uniqueness Are there duplicate records, or is every entity represented once?
Traceability Can we trace the data back to its source?
Reliability Is the data coming from a dependable source?
Validity Does the data fit its declared format, range, and rules?
Completeness Is everything there, or are fields and records missing?
Accessibility Can the right people actually reach the data? (Not all data is accessible to all.)
Integrity Do references hold together — does every foreign key point to a real row?
Accuracy Does the data reflect the true real-world value?
Consistency Does the same value mean the same thing everywhere in the data set?

Earlier in the course, this same checklist was applied to healthcare data — checking for duplicates, completeness, and issues — which shows the dimensions are a reusable checklist, not a one-off exercise.

Worked example — an integrity failure (from the session): A prescription record points to a doctor ID that does not exist in the doctor table.

  • The prescription row says "prescribed by doctor 734," but no doctor with ID 734 exists.
  • Integrity check: the reference is broken — the foreign key points nowhere.
  • Consequence: this is a compliance issue. Can we be sure about the correct prescription? Somebody is being prescribed some medicine, and the prescribing doctor cannot be verified. In a healthcare setting, that failure is exactly what profiling must catch before the data enters a pipeline.

Final answer: broken references = integrity failure = compliance risk. Sense-check: if you cannot name the prescriber, you cannot audit the prescription — the record is untrustworthy even though every other column looks fine.

Q: Could you read out the data quality dimensions shown on the right-hand side?

A: Timeliness, uniqueness, traceability, reliability, validity, completeness, accessibility, integrity, accuracy, and consistency.

Pitfalls to watch when applying the dimensions:

  • Treating the list as a formality. Reading out the ten names is not profiling. Each dimension must be checked with actual data: count nulls, count duplicates, validate foreign keys, compare timestamps.
  • Testing only one dimension. A data set can be complete yet inaccurate (every row present, values all wrong), or accurate yet inaccessible. Missing one dimension hides a real problem.
  • Ignoring traceability. If you cannot say where a value came from, you cannot reproduce an audit trail — and you cannot detect contamination either.

9.1.3 Extended Dimensions: Informative, Covering, Real, Unbiased

Beyond the core list there are extended dimensions. Data should be informative — it should carry the correct information. It should have coverage — covering everything, all the details; does it cover the world as the model needs it? It should be real inputs — really reflecting the real inputs or real customer data, not a synthetic substitute. It should be accurate. And one of the very, very important quality dimensions, especially when dealing with AI, is unbiased — the data should be unbiased.

A subtle rule — good data is not a result of the model itself. If the model's own output feeds back into the data, you have a feedback loop problem.

  • You cannot train a model that predicts the gender of a person from their name, then use that prediction to label a new training example. The label now comes from the model, so the model learns its own guesses — a self-confirming spiral.
  • Likewise, a model can be used to decide which e-mail messages are important and highlight them. If the model's own decisions feed back into the labels, the data becomes contaminated.

The rule to remember: good data is not a result of the model itself; if it is, the data is contaminated. This is the seed of the data leakage problem covered in Section 9.4.

Labels also matter. Good data has consistent labels; inconsistency in labeling is very important when you talk about ETL process extraction — that is why we do proper labeling. The same idea applies to a person's profile: you give your profile under the right category, the right label. Suppose you have a certification — the certification goes into the certification category. You do not want to mix that certification somewhere into the experience section. If you talk about your leadership, leadership goes into leadership traits.

Q: When I present my profile, why must each item go into its own labeled section?

A: Good data has consistent labels. A certification goes under certifications, not under experience; leadership goes under leadership traits. You do not mix them up — in ETL we do proper labeling for the same reason. A row labeled "certification" that contains experience text, or a field labeled "date" that holds a string, breaks every downstream process that reads that label.

9.1.4 Enough Data and Generalization

Is the data big enough? Because we talk about big data and volume, good data must be big enough to allow generalization — the ability of a model learned from this data to behave correctly on data it has never seen. Generalization is a sampling question: the data set is a sample of the real world, and we need a good sample.

Recall from earlier in the course the model-fit picture: too little data, or data with weak signal, leads to underfitting — the model is too simple to capture the pattern, so it does poorly even on the training data. The important warning from the session: sometimes nothing can be done to increase the accuracy of the model. No matter how much data you throw at the learning algorithm, if the information contained in the data has low predictive power, accuracy will not improve — that is where the underfitting problem comes into the picture. More data cannot manufacture signal that is not there.

Visual intuition: picture a scatter plot with "amount of training data" on the horizontal axis and "model accuracy" on the vertical axis. The curve rises quickly at first, then flattens into a plateau. The plateau is the key landmark: it says the data has run out of predictive power, and adding more rows moves the curve no further. That flat part of the curve is the region where underfitting rules and no volume of data fixes it — the fix has to come from better features or a better model, not more rows.

9.1.5 The Common Problems With Data

Q: What are the common problems with the data?

A: The noise, the low predictive power, outliers, bias, leakage, and outdated data.

Each of these is something to watch when building a pipeline. The session framed them as a checklist of questions you ask about the data: what is the cost of generating the data, do we have any quality problems, is there any noise, is the data capable of only low predictive power, does it contain outliers, are there any leakages, is the data outdated?

  • Noise — random fluctuations that hide the true signal.
  • Low predictive power — the features simply do not carry enough information about the target (Section 9.1.4).
  • Outliers — points that do not belong to the big bucket where most data sits (Section 9.2).
  • Bias — systematic distortions in how the data was collected or labeled (Section 9.3).
  • Leakage — information that should not have been available leaked into the data (Section 9.4).
  • Outdated data — the world moved on; the data describes a population that no longer matches production (Section 9.5).

Recap + bridge: Data profiling is the CV of your data — examine it against the ten quality dimensions (plus informative, covering, real, unbiased), keep labels consistent, avoid feedback loops, and confirm there is enough data with real predictive power. The common problems list — noise, low predictive power, outliers, bias, leakage, outdated data — is the agenda for the next four sections: we look at outliers (9.2), bias and fairness (9.3), leakage (9.4), and drift — the "outdated data" problem — (9.5–9.6) one at a time.

9.2 Outlier Detection

9.2.1 Outliers Can Be Good or Bad

Hook: Is every strange-looking data point a mistake? Sometimes the strangest transaction in your data is your best customer — and sometimes it is fraud. That is why outlier detection is not about "removing bad data" but about finding the points that do not belong, and then deciding what they mean.

An outlier — also called an anomaly — is data that does not belong to the big bucket where most of the data belongs. Most points cluster in one region; outliers sit far outside that region. The key message from the session: outliers are good as well as bad.

The professor's example: imagine you normally make transactions in one city. All of a sudden there is a transaction in London, then one in Amsterdam. Relative to your usual pattern, those transactions are outliers. But that outlier may produce a different revenue stream and a different marketing strategy for companies: the bank spots the travel pattern, gives you offers, and you start using that card more often. Use an international card and an Amazon card in Amsterdam, Belgium, and Germany — everywhere it is being used — and the next time, the company can increase your credit score, increase your credit card limit, and give you a better offer. The "outlier" behavior becomes a growth signal.

So the same unusual point can be a good outlier (a new revenue stream, a new behavior worth rewarding) or a bad outlier (fraud, a sensor failure, a data-entry error). Detection is the same; interpretation is not.

9.2.2 Box-plot Based Detection

A simple detection technique: box plot based outlier detection. The idea: find where most of the data lives, then treat whatever lives far outside as an outlier candidate. That is why analysts build a lot of charts — the five-point summary, histograms, distributions. We find out where most of the data belongs; if there is some data that does not belong to the one big bucket, we may put that under the outlier category.

The five-point summary names five landmarks of a data set: the minimum, the first quartile \(Q_1\) (the 25th percentile), the median \(Q_2\) (the 50th percentile), the third quartile \(Q_3\) (the 75th percentile), and the maximum. The box plot draws a box from \(Q_1\) to \(Q_3\), a line at the median, and whiskers toward the extremes.

The standard rule for flagging outliers with a box plot uses the interquartile range (IQR), the distance between the quartiles:

\[ \mathrm{IQR} = Q_3 - Q_1 \]

Any value below the lower fence or above the upper fence is an outlier candidate:

\[ \text{lower fence} = Q_1 - 1.5 \times \mathrm{IQR}, \qquad \text{upper fence} = Q_3 + 1.5 \times \mathrm{IQR} \]

Worked example — box plot spotting: Consider the data set \(10, 12, 14, 15, 18, 19, 21, 100\) (e.g., response times in milliseconds from eight requests).

  • Step 1 — sort: already sorted: 10, 12, 14, 15, 18, 19, 21, 100.
  • Step 2 — quartiles: the lower half is 10, 12, 14, 15, so \(Q_1 = (12 + 14)/2 = 13\). The upper half is 18, 19, 21, 100, so \(Q_3 = (19 + 21)/2 = 20\). Median \(Q_2 = (15 + 18)/2 = 16.5\).
  • Step 3 — IQR: \(\mathrm{IQR} = 20 - 13 = 7\).
  • Step 4 — fences: lower fence \(= 13 - 1.5 \times 7 = 13 - 10.5 = 2.5\). Upper fence \(= 20 + 1.5 \times 7 = 20 + 10.5 = 30.5\).
  • Step 5 — verdict: values 10–21 all sit inside the fences; 100 is far above the upper fence of 30.5, so 100 is the flagged outlier.

Final answer: 100 is the outlier. Sense-check: the eight values cluster between 10 and 21 — a response of 100 is five times the typical range, which is exactly the "does not belong to the big bucket" situation the box plot is built to expose.

9.2.3 Proximity-Based Outlier Detection

Proximity-based outlier detection is a very famous technique, and it is very simple in spirit: we try to find the distance between the data points. Points that sit close to many other points are normal; points that sit far from everything are outliers.

Step 1 — build the distance matrix. A distance matrix holds the distance between every data point and every other point. For \(m\) points, the matrix is \(m \times m\): entry \((i, j)\) holds the distance between point \(i\) and point \(j\). There are many methods to find the distance — Euclidean distance, Manhattan distance, and lots and lots of other techniques. Simple math: find the distance.

The Euclidean distance between two points \(\mathbf{x} \in \mathbb{R}^n\) and \(\mathbf{y} \in \mathbb{R}^n\), where \(x_i\) and \(y_i\) are the \(i\)-th coordinates and \(n\) is the number of dimensions, is the length of the straight line joining them:

\[ d(\mathbf{x}, \mathbf{y}) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2} \]

This is the standard definition of Euclidean distance — the session named the technique, and the formula is the textbook one. It is a direct generalization of Pythagoras: in two dimensions it is exactly \(\sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2}\).

The Manhattan distance uses absolute differences instead of squared ones, so it measures distance along a grid — like walking city blocks instead of flying:

\[ d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^{n} |x_i - y_i| \]

Again, this is the standard definition. The name "Manhattan" comes from the street grid of Manhattan: you can only move north-south or east-west, never diagonally. For two-dimensional points, Euclidean distance is the "as the crow flies" length; Manhattan distance is the "taxi cab" length.

Step 2 — find the nearest neighbors (KNN). Once you have the distances, find which points are closer in proximity — that is where you apply KNN, the k-nearest neighbors method. Suppose KNN of two, or KNN of three: you find the two or three nearest neighbors of each point. Then you rank the points by how close their neighbors are, and you group the close ones. If anything does not fall under that group, you define it as an outlier. A point whose k nearest neighbors are all far away is an outlier candidate; a point whose k nearest neighbors are close is part of the crowd.

Worked example — spotting the outlier by distance (from the session): The numbers are 50, 67, 90, 80, 55, and 167. We find the distance between every data point and every other point. For one-dimensional data, Euclidean and Manhattan distance are the same: the absolute difference.

  • Step 1 — the distance matrix. Distances from each value to each other value (only half shown, the matrix is symmetric):
50 67 90 80 55 167
50 0 17 40 30 5 117
67 17 0 23 13 12 100
90 40 23 0 10 35 77
80 30 13 10 0 25 87
55 5 12 35 25 0 112
167 117 100 77 87 112 0
  • Step 2 — how far apart is the crowd? Look at the five values 50, 67, 90, 80, 55. Their pairwise distances run from 5 (50 to 55) up to 40 (50 to 90). The average pairwise distance inside the cluster is 21.
  • Step 3 — how far is 167 from the crowd? Its distances to the others are 117, 100, 77, 87, 112 — every one of them larger than the largest distance inside the cluster (40). Its nearest neighbor (67) is 100 away.
  • Step 4 — KNN reasoning: with \(k = 1\), 167's nearest neighbor is 100 units away, while every other point has a nearest neighbor within 5 units. 167's neighborhood is empty compared to everyone else's.
  • Step 5 — verdict: 167 is the outlier. It does not belong to the big bucket.

Final answer: 167. Sense-check: the cluster spans 50 to 90 (a 40-unit spread), and 167 sits more than two-and-a-half times that entire spread away from its nearest neighbor — exactly the "far from the cluster" profile the professor described.

Q: Among 50, 67, 90, 80, 55, and 167, which one is the outlier?

A: 167 seems to be. We find the distance between every data point and the other points — using a distance matrix and a method like Euclidean distance — and 167 is far away from the cluster.

A second mini-example shows the same idea in two dimensions: point A = (1, 2) and point B = (4, 6). The coordinate differences are \(4 - 1 = 3\) and \(6 - 2 = 4\). Euclidean: \(\sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5\). Manhattan: \(|3| + |4| = 7\). The two distances differ (5 vs 7) because the crow flies straight while the taxi must travel along the grid. In high-dimensional data, the choice of distance changes which points count as "neighbors," so the metric is part of the outlier definition.

9.2.4 Density-Based Outlier Detection

Density-based outlier detection is another very famous technique. We use a set of data points, and there is a formula available for calculating the density of the data points — some points live in a high-density region (many points around them), some in a low-density region (few points around them). Based on that density, we detect the outlier: a point sitting in a sparse region while its neighbors sit in dense regions is an outlier.

The session did not state the formula, so here is the standard density-based construction (the basis of the Local Outlier Factor, LOF, method):

For a point \(p\), let \(N_k(p)\) be the set of its \(k\) nearest neighbors, and let \(\text{reach-dist}_k(p, o)\) be the "reachability distance" from \(p\) to a neighbor \(o\) — at least the \(k\)-distance of \(o\), so that points in dense regions do not get unreasonably small distances:

\[ \text{reach-dist}_k(p, o) = \max\left( k\text{-distance}(o), \; d(p, o) \right) \]

The local reachability density of \(p\) is the inverse of the average reachability distance to its neighbors:

\[ \text{lrd}_k(p) = \left( \frac{1}{|N_k(p)|} \sum_{o \in N_k(p)} \text{reach-dist}_k(p, o) \right)^{-1} \]

A high lrd means the point's neighborhood is tight (dense region); a low lrd means the point is isolated. The Local Outlier Factor compares a point's density with its neighbors' densities:

\[ \text{LOF}_k(p) = \frac{\frac{1}{|N_k(p)|} \sum_{o \in N_k(p)} \text{lrd}_k(o)}{\text{lrd}_k(p)} \]

  • \(\text{LOF}_k(p) \approx 1\) — the point's density matches its neighbors: normal.
  • \(\text{LOF}_k(p) > 1\) — the point is sparser than its neighbors: outlier candidate.

Why does density matter when proximity already works? Because proximity alone misreads clusters of different tightness. Imagine a dense village cluster and a loose countryside cluster. A point at the edge of the village is close to its village neighbors in absolute distance, but its neighborhood is still much sparser than the village core — density-based scoring catches that; a plain nearest-neighbor distance can miss it.

9.2.5 What to Do With Outliers

Outliers are good as well as bad, so we cannot blindly delete them. The session gave the two standard options:

  1. Exclude the outliers from the training data — for the bad outliers: measurement errors, data-entry mistakes, broken sensors, fraud noise. Removing them keeps the model from learning garbage.
  2. Use machine learning algorithms and models that are robust to outliers — instead of removing data, choose methods that are not dragged around by extreme points. Median-based statistics and robust models resist the pull of a few wild values, which matters when you cannot safely delete the points (for example, when the outlier might be the fraud you are trying to detect).

Pitfalls in outlier handling:

  • Deleting good outliers. The London/Amsterdam traveler's transactions are outliers — deleting them would delete the signal that drives new offers and revenue.
  • Removing outliers before checking them. An outlier can be the most important row in the data set (fraud, a crash event, a medical alert). Investigate before you delete.
  • Forgetting that "outlier" depends on the metric. With Euclidean distance, (1,2) to (4,6) is 5; with Manhattan it is 7. Different metrics flag different points, so state the metric you used.
  • Using the mean when outliers are present. The mean is dragged by extreme values; the median survives. That is why the box plot (median-based) is preferred over mean-based checks for flagging extremes.

Recap + bridge: An outlier is a point that does not belong to the big bucket — sometimes a gift (new behavior, new revenue), sometimes garbage (fraud, sensor error). Three detection families: box plots (five-point summary + IQR fences), proximity (distance matrix + KNN), and density (local density / LOF). Handle them by exclusion or by robust models — never by blind deletion. Outliers were item two on the common-problems list from Section 9.1.5; the next item on that list is bias, the topic of Section 9.3.

9.3 Bias and Fairness

9.3.1 Bias and Fairness Matter

Hook: A model is only as fair as the data it learned from. If the data collection process favors one region, one group, or one way of measuring, the model quietly inherits that favoritism — and the loss metric on the test set will not tell you it happened.

Bias and fairness are very, very important: your data should be unbiased. There can be many reasons for bias — sampling bias (the sample does not represent the population), instrument bias (the measuring device skews the readings) — a number of reasons; many biases are available. The lesson is not to memorize a list, but to understand that bias enters data at every stage: at collection, at selection, at labeling, and at reporting.

Bias here means a systematic distortion — not random noise. Random noise averages out across many examples; bias pushes the data consistently in one direction, so the model learns the distortion as if it were truth. A model trained on only one region's data does not just have "some error" — it has learned that the world looks like that one region.

9.3.2 The Types of Bias

The types of bias read out in the session:

Omitted variable bias, sponsorship or funding bias, prejudice or stereotype bias, systematic value distortion, experimenter bias, labeling bias, reporting bias, automation bias, selection bias, group attribution bias, implicit bias, and confirmation bias.

Not all biases may be applicable to every data set — the list is a checklist, and the skill is recognizing which ones threaten your particular data. Here is one compact picture of what each one does:

Bias One-line meaning
Omitted variable bias A factor that matters is left out of the model, so the included factors absorb its influence.
Sponsorship / funding bias Whoever funds the work shapes what gets measured and reported.
Prejudice / stereotype bias Pre-existing stereotypes leak into data or labels.
Systematic value distortion The recorded values are shifted in a consistent way (a mis-calibrated scale).
Experimenter bias The person running the study influences the outcome, often without meaning to.
Labeling bias Labelers label in a certain way, damaging the credibility of the data.
Reporting bias The data does not report what it should — the wrong unit, the wrong measure.
Automation bias Automated systems create errors (or humans over-trust them), so error rates matter.
Selection bias Only some of the data is selected — for example, only one region.
Group attribution bias Judgment is assigned by group membership rather than by the individual case.
Implicit bias A preference you hold without noticing.
Confirmation bias We believe something, then look for evidence that confirms it.

9.3.3 What Each Bias Looks Like

  • Labeling bias: people like to label data in a certain way; because of that they may lose the credibility of the data. If the labeling guidelines nudge workers toward one label, the whole label distribution shifts.
  • Selection bias: when people select some data, they may select only the data from one particular region — for example, only data from Mumbai — and then the data is biased. The model learns Mumbai's patterns and calls them universal.
  • Group attribution bias: when people do attribution by group, there could be a bias — judging a person by their group's average instead of their own record.
  • Reporting bias: the data does not report what it should — instead of megahertz it gives gigahertz; instead of a kilometer it gives miles. While reporting, automation could also lead to calculation problems — automated systems may create errors, so the error rates matter.
  • Selection from the population: how you select the data in terms of a population — what is important, what is not important — based on your experience. Sometimes that may lead to a problem; your personal sense of importance silently shapes the data set.
  • Implicit bias: a preference you hold without noticing. One person likes a technique and always uses it; another calls only a few people. If someone always calls the people who immediately respond and starts talking to them, that is a default behavior depending on the situation — the quick responders get over-represented and the slow responders disappear from the picture.
  • Confirmation bias: some biases are based on facts and evidences — we believe in something and then we confirm it. The belief came first; the evidence hunt follows.

Worked example — confirmation bias sneaking into a model (from the session): An ML practitioner builds a model that predicts aggressiveness in dogs based on a variety of features — height, weight, breed, and environment.

  • The practitioner's history: as a child, the practitioner had a hyper-reactive toy poodle. That small, energetic poodle colored the practitioner's mental model: "small dogs are aggressive."
  • The bias in action: when reviewing the samples, the practitioner confirms the pattern on some samples — the small, yappy dogs that fit the story — but cannot relate it to the other samples, the many small dogs that are calm and the large dogs that are aggressive.
  • The result: the model over-weights size and breed, because the human checking the labels and the features kept looking for the pattern they already believed.

Final answer: confirmation bias enters the model through the human loop — the practitioner's childhood poodle shapes which patterns get confirmed and which get ignored. Sense-check: the model's predictions on new data will systematically over-flag small breeds as aggressive, because the bias never appears in the loss metric — it hides inside the way the data was selected, labeled, and reviewed.

Q: How can confirmation bias sneak into a machine learning model?

A: An ML practitioner building a model that predicts aggressiveness in dogs from height, weight, breed, and environment may have had a hyper-reactive toy poodle as a child; he confirms that pattern on some samples but cannot relate it to other samples.

Q: Could you read those six important parameters for responsible AI?

A: Validate outputs, verify facts, avoid blind trust, check citations, detect hallucinations, maintain academic integrity.

9.3.4 Fairness and Responsible AI

Data should be fair, and AI and ML — deep learning — tools should work with fairness. When we talk about any data, any data pipeline, machine learning, or deep learning, we are talking about responsible AI: AI should be responsible. Decisions should be fair — suppose a parent has two children, a son and a daughter: the parent should be unbiased and treat them as a pair, making fair decisions. Data should have fairness. AI should be human design; data should be secure, reliable, and compliant.

Q: Why should decisions and data be fair?

A: Imagine two children, a son and a daughter — you need a fair decision and a fair pair. Data should have fairness, human design, and be secure, reliable, and compliant. Fairness is not a feature added at the end; it is a property of the whole chain — the data, the design, the deployment.

Responsible AI also means antagonistic thinking: challenge the assumption. Why was somebody biased with something? Why are you using a particular tool, or a particular cloud, or something else? People may go with some assumptions — you have to challenge the assumption, identify the weakness. That is where the human in the loop gets involved. Fairness is very, very important — every AI and ML solution should be fair enough, and this is especially important for critical AI — the systems where a wrong or unfair decision has real consequences for people's lives, health, or money.

Scope — fairness is a systems property, not a single check: Checking one metric (say, equal accuracy for two groups) is not enough. Bias can enter at data collection, at labeling, at feature choice, and at deployment — the session's list of twelve bias types maps to different stages. A fairness audit therefore has to trace the whole chain: where did the data come from, who labeled it, what was left out, and what does the model do with it. And because the world changes, fairness is checked continuously — which is why this section links forward to drift detection (Section 9.5) and monitoring.

9.3.5 Explainable AI and Responsible Evaluation

AI should be explainable — you should be able to say why a decision was made. You can use explainable AI packages like SHAP and LIME, or a few other packages, to make sure the AI gives fairness. SHAP (SHapley Additive exPlanations) and LIME (Local Interpretable Model-agnostic Explanations) both explain individual predictions: they show which features pushed the prediction up and which pushed it down. When the output should be fair, then the data profile feeding it should be fair too — an explainable model over biased data just makes the bias visible; it does not remove it.

Evaluating a machine learning model responsibly requires doing more than just calculating a loss metric. It is not enough to find the predicted value and the actual value and say: "90 minus 50 — oh my God, I have this much of loss." Fairness must be checked too — maybe the loss comes from the data collection, maybe from the data itself. So we need to identify the bias. The loss number says how wrong the model is; it never says why — and if the why is a biased sample or a biased label, the loss hides it.

9.3.6 Handling Problematic Feature Values

For missing feature values we use the binning technique — we normalize and put the values into a proper bucket. We also ask: what are the unexpected feature values — when an unexpected feature value comes, how are we going to deal with it? And when the data is skewed — lower tile or higher tile — how do we deal with it? We need to ensure the data is not under-representing or over-representing relative to the real population.

Binning (also called discretization) is grouping continuous values into a small number of buckets, so that missing values and extremes can be handled at the bucket level and the model sees stable categories instead of raw, noisy numbers.

Worked example — binning missing and skewed ages: A customer table holds ages, but 12% of rows have a missing age, and a handful of rows say "age = 999" (a dummy value entered when the clerk did not know).

  • Step 1 — decide the bins: define five age buckets: 0–17, 18–35, 36–55, 56–75, 76+.
  • Step 2 — normalize values into buckets: every row's age becomes its bucket label. The missing values and the "999" placeholders are assigned to a dedicated "unknown" bucket instead of being deleted.
  • Step 3 — check the skew: suppose the real population has about 20% of people above 56, but the data set shows only 4% in the 56–75 bucket and 1% in 76+. The lower tiles (younger ages) are over-represented; the higher tiles are under-represented.
  • Step 4 — deal with it: before modeling, re-weight the buckets or re-collect data so the training set matches the real population proportions.

Final answer: bins give a stable, auditable way to handle missing values, unexpected values (999), and skewed tiles. Sense-check: without bins, a raw 999 would drag the mean age far upward; with bins, it lands in a labeled "unknown" bucket that the model can treat explicitly — the data set no longer silently over- or under-represents any part of the population.

Recap + bridge: Bias is a systematic distortion that enters data at collection, selection, labeling, or reporting; the twelve bias types are the checklist. Fairness means treating the data like a fair pair — no group under-represented — and responsible AI adds antagonistic thinking (challenge the assumptions) and explainability (SHAP, LIME) on top of the loss metric. Binning handles missing, unexpected, and skewed feature values. Bias was item four on the common-problems list from Section 9.1.5; the next item, leakage, is the most dangerous of all — a model can look excellent while quietly cheating (Section 9.4).

9.4 Data Leakage

9.4.1 What Data Leakage Is

Hook: The most dangerous model failure is invisible: the model looks brilliant in training, passes validation, gets deployed — and then quietly collapses in production. Usually the reason is that the model was cheating all along, because the answer leaked into the question.

Data leakage — also called target leakage — is often due to the data pipeline. In supervised learning, data leakage is the unintentional introduction of information: something is introduced that should not have been made available, but it was available. Because of that, the data is contaminated. This question came from a student in an earlier session — "what is this data leakage?" — because some data could cause contamination and create different results.

Q: What is data leakage?

A: In supervised learning, data leakage is the unintentional introduction of information — something that should not have been made available was available, so the data is contaminated and the results change. The leak does not have to be deliberate: it is almost always accidental — a copy-paste, a mis-joined table, a feature computed from the future.

The key phrase is unintentional introduction. In supervised learning the model learns to map features \(x\) to a target \(y\). Leakage happens when information that would only be known at prediction time — or information derived from \(y\) itself — is present in the features during training. The model then memorizes the answer instead of learning the pattern.

9.4.2 Why Leakage Is Dangerous

Training on contaminated data leads to overly optimistic expectations about the model performance. The model looks better in training and validation than it will ever be in production — and nobody discovers the leak until it is too late.

Why "too late"? Because every reported accuracy number was measured on data the model had secretly seen. The inflated numbers look like success, so the model ships; the production traffic arrives without the leaked information; and performance falls to the level the honest features actually support. The model cannot replicate its validation performance on genuinely new data — the information it was using is simply not there anymore.

Visual intuition: picture two curves on a chart whose horizontal axis is time and whose vertical axis is accuracy. The training/validation curve sits high and flat — 90% and above, looking perfect. The production curve starts high too, then drops steeply the day after launch and settles far below. The gap between the two curves is the leakage: the higher the validation curve, the more the model was cheating. If the production curve were drawn during development, the gap would be visible immediately — but production data is not available during development, which is why the leak survives until deployment.

Worked example — the inflated accuracy trap (numbers constructed to make the mechanism concrete): A bank builds a fraud-detection model. The target \(y\) says whether a transaction was later confirmed as fraud. By mistake, the pipeline also includes the feature "chargeback_processed," a flag that is only created after the bank decides the transaction was fraudulent.

  • Step 1 — the leak: the feature "chargeback_processed" equals 1 for 92% of the fraud rows and 0 for nearly all non-fraud rows. It is derived from the target, so it is the answer wearing a disguise.
  • Step 2 — the training result: the model learns one rule — "if chargeback_processed = 1, predict fraud." On the validation set it scores 96% accuracy. The team celebrates.
  • Step 3 — the honest check: a hold-out evaluation with the leaked feature removed scores 62% accuracy — the model must now use real signals like amount and location, which are much weaker.
  • Step 4 — the deception: because every validation number reported was the 96%, nobody notices anything wrong before launch. In production the "chargeback_processed" column is empty (the chargeback has not happened yet), the model's one rule fires on nothing, and the fraud rate stays exactly where it was.

Final answer: the leak inflated every reported number (96% vs the honest 62%), and no one discovered it until production. Sense-check: the model was not predicting fraud — it was reading the fraud verdict off the target itself. The gap between 96% and 62% is the size of the lie.

9.4.3 The Causes of Leakage

The typical causes named in the session:

  • The target being a function of a feature — you send some data to some mathematical function, some algorithm, and the function is not properly done, so you have leakage. The feature contains the target's value because some computation that should not have touched the target did.
  • Feature hiding the target — a feature that silently encodes the answer (like "chargeback_processed" above, or a "total_amount_refunded" column in a churn model).
  • Feature coming from the feature — downstream or derived values creeping back upstream, so the feature is built from information that only exists after the event the model is trying to predict.

Classic real-world leak paths that follow these causes:

Leak path Which cause Example
Scaling or imputing before the train/test split Feature coming from the feature Mean/standard deviation computed on the whole data set, so test rows secretly influence training features.
Joining tables with future rows Target a function of a feature Sales data joined with a "cancellation" table that records events after the sale.
Target-derived flags left in features Feature hiding the target A label column accidentally left in the feature table.
Temporal leaks in time series Feature coming from the feature A rolling average computed with values from later time steps.

This is exactly where the conversation moves into data skew and data drift (Section 9.5): a model that quietly saw forbidden information, or that was trained on a world that has since changed, both produce the same symptom — the production world no longer matches what the model learned.

Recap + bridge: Leakage is the unintentional introduction of information that should not have been available; it inflates every validation number, ships a cheating model, and is discovered only in production. The three causes are the target being a function of a feature, a feature hiding the target, and a feature coming from the feature. Even with zero leakage, though, a deployed model still decays — because the world itself changes. That is drift, and it is the next section's topic.

9.5 Data Drift, Model Drift, and Concept Drift

9.5.1 What Does Drift Mean

Hook: Your model was perfect last quarter. Nothing in the code changed — the data changed, and the world it learned about quietly moved on. That slow, silent decay is drift, and every production model eventually meets it.

The session opened this topic with a direct question-and-answer on what drift means:

Q: What do you mean by model drift and data drift — what is a drift in general?

A: A drift happens when something goes from a benchmark number — for example, the way the distribution of the data was there has changed with the course of time. Model drift is similar: I collect the weights and I have been computing the weights for some time, but suddenly I see that the weight computation is completely off. The model drift could be because of data drift as well.

A drift happens when something moves away from its benchmark. For data, the benchmark is the distribution the model was trained on: the way the data was distributed then has changed with the course of time. For a model, the benchmark is the weight computation that worked: the weights are computed for some time, and suddenly the weight computation is completely off. And the two are connected — model drift is often caused by data drift, because the model's weights were learned from a distribution that no longer exists.

9.5.2 Drift After Deployment

Once you build a model and deploy it into production, the model usually performs well for some time — a certain model quality, everything looks fine. Often the cause of an error is explainable by the fairness or fitness of the training data: traditional training samples probably solidify the model. However, in many practical scenarios, the model starts to make errors. The training data is a frozen snapshot; the production world keeps moving.

Real-world example from the session: Amazon uses a model for its recommendation system to predict whether a user will like things on the website. Over time, the preferences may start to change — perhaps due to aging: one user liked one actor's films for some time, now likes different actors; preferences change. If the model keeps returning the same type of results, the results may mislead — the user has moved on, the recommendations have not.

One of the biggest differences in the data set: no Kaggle dataset is static — but in reality, production data is changing; that is data dynamics. Kaggle competitions give you a fixed snapshot to train on, but production data streams in continuously. Drift happens because of the dynamics of people and the dynamics of data generation.

Speed of decay: data can decay. Past performance is no guarantee of future results — model decay is a natural occurrence in ML models. The speed of decay can vary greatly: sometimes it takes years to get adjusted, sometimes a few days. Some models drift over decades (demographic models), others over days (ad-click models reacting to a viral trend).

Scope — drift is expected, not exceptional: Drift is not a bug you should have prevented. It is the normal consequence of deploying a static model into a dynamic world. What is a mistake is ignoring it — not monitoring the distribution, not retraining, not alerting. The design question is not "will my model drift?" but "how fast, and how will I notice?" That is exactly what the drift detection metrics in Section 9.6 exist for.

9.5.3 Schema Skew and Distribution Skew

Data drift means a skew grows between the training data and the serving data: the production data that the model receives for scoring has diverged from the data set that was used earlier for training, tuning, and evaluating the model — so it may not replicate the data pattern. The discrepancy between the training data and the serving data can be classified as:

  • Schema skew — very important. The production product schema or customer schema, and whatever related tables, may have inconsistent labels and inconsistent feature types. The column that held "customer_id" as an integer now holds strings; a feature that was a date became a timestamp with a different time zone; a column was renamed and the pipeline did not catch it. The structure itself no longer matches what the model expects.
  • Distribution skew — the data distribution may not be correctly sampled; there are new trends and patterns. The columns look the same, but the values have shifted: the age distribution tilted younger, the product mix changed, a new segment appeared that was never in training.

Visual intuition: picture two histograms drawn on the same axes, the horizontal axis being the feature value and the vertical axis the share of records. The training histogram (solid line) is the benchmark. The serving histogram (dashed line) is drawn from production. Distribution skew is the dashed curve visibly sliding sideways or spreading out — same shape language, different location. Schema skew cannot be drawn on this chart at all, because the chart itself fails to render: the data type changed, the column broke, the join returned nothing. Distribution skew is a question of "how different are the values?" — schema skew is a question of "does the data even fit the expected structure?"

9.5.4 Concept Drift

Concept drift is about the interpretation of the relationship changing. In data drift, the inputs change; in concept drift, the meaning of the relationship between inputs and outputs changes — the same input value now deserves a different answer.

Think of a movie-watching pattern: you normally go and search movies, and you like horror movies or some fiction movie — you select it. All of a sudden you may change your mind: you don't like science anymore, you don't like fiction anymore, you want some humor, some comedy, some fun — then the pattern has changed. If the service keeps giving you a list of fiction movies, you get irritated. The features (movies watched) did not change structure, and the user did not change how the service works — the concept "what this user wants" changed.

Worked example — the cholesterol concept (contributed by a student in the session): Earlier, whenever there used to be a prediction based on cholesterol, they used to weight it very high — if cholesterol is beyond 250, the chances of having a heart attack or cardiac arrest are high. But as the research progressed, the weightage has been given a little more lower now. The concept has changed because people are thinking: this can be from inheritance as well — there are other parameters which are high, like blood pressure.

  • Step 1 — the old concept (training era): risk model gives cholesterol one big weight. A patient with cholesterol above 250 is flagged as high cardiac risk, and the flag drives the model's output.
  • Step 2 — the world changes: medical research finds that cholesterol interacts with inheritance and blood pressure — high cholesterol in a person with normal blood pressure and no family history carries less risk than the old weight implied.
  • Step 3 — the new concept (serving era): the weight on cholesterol is lowered; blood pressure and family history carry more of the risk explanation.
  • Step 4 — the drift: the model still weights cholesterol heavily (it learned the old concept), so it keeps over-flagging patients whose risk profile changed. The same input, cholesterol = 260, deserves a different risk answer than it did in training.

Final answer: the relationship "cholesterol → heart-attack risk" changed, so a model holding the old relationship is drifting even though the data distribution barely moved. Sense-check: the cholesterol values flowing in are the same as ever; what changed is what they mean — and only retraining on the new concept restores the model.

Q: Earlier, medical guidance said that cholesterol beyond 250 meant a high risk of cardiac arrest. Does that concept still hold?

A: As research progressed, the weightage given to cholesterol has been lowered. The concept changed because inheritance matters too, and other parameters such as blood pressure carry more weight now. Even people who are thin and lean can have high cholesterol — the old idea that a big belly or tummy means cholesterol while lean people are safe is not true.

Worked example — the streaming service keeps recommending fiction (from the session): A user's watch history was fiction: horror, science fiction, drama — and the recommendation model learned it. Then the user's taste changed: no more science, no more fiction — now it is humor, comedy, fun. The pattern has changed.

  • Step 1: the model serves its learned pattern — a list of fiction movies.
  • Step 2: the user gets irritated — every recommendation misses the new taste.
  • Step 3: the model's behavior is unchanged and "correct" relative to its training; the user's concept of what they want has drifted.

Final answer: recommendation quality collapses not because the model broke, but because the concept it learned is stale. Sense-check: keep serving fiction and the user churns — which is precisely why services like Netflix continuously retrain on recent interactions: drift is fought with fresh data, not with a better static model.

So the interpretation may change; people tend to change things. You need to take care of the data skewing between training and actual production data — the model may behave differently, the concepts may change. That is why we cannot depend on a static data pipeline or static machine learning code: we need some dynamism — that is why we talk about agility.

Comparison — the three drifts at a glance:

Drift type What changes Example Detection focus
Data drift (feature drift) The input distribution changes Age distribution of customers shifts; schema columns change type Compare training vs serving distributions (PSI, KL)
Model drift (prediction drift) Model outputs deviate from their baseline The weights computation goes off; prediction volume shifts Monitor model outputs over time
Concept drift The input→output relationship changes Cholesterol now interacts with blood pressure; user taste changed Compare predictions against actuals when available

One-line rule for choosing what to watch: when the inputs look wrong, suspect data drift; when the outputs look wrong, suspect model drift; when the inputs look fine but the answers are wrong, suspect concept drift — and remember model drift is often data drift wearing a different name.

9.5.5 Agility

Agile practices: Scrum meetings, sprints, and backlogs — the instructor attended all the Scrum calls while working at Cisco for seven years. Agility is the practical answer to drift: if the world changes continuously, the pipeline and the model must be changeable continuously.

Q: What do you mean by agility?

A: Agility means moving around faster, making decisions faster, not taking a lot of time — simple, simple to make changes. It is the ability to move quickly and easily — being nimble.

There is a YouTube talk on agile software project management that discusses the power of agile — a recommended watch, mentioned in the session as an extra resource shared with the class.

Recap + bridge: Drift is movement away from a benchmark: data drift (inputs move), model drift (outputs move — often caused by data drift), and concept drift (the meaning of the relationship moves, as with cholesterol). Production data changes because people and data generation change; decay speed varies from years to days; the answer is agility — fast, nimble pipelines and quick changes. Drift is a measurable problem, and the next section gives the two metrics the session named as the important ones: the Population Stability Index and KL divergence.

9.6 Data Drift Detection Metrics

9.6.1 Population Stability Index (PSI)

Hook: How do you measure "the distribution changed"? You cannot just look at the data and feel it — you need a number you can alert on. The session named one index as very, very important: the Population Stability Index (PSI), a metric the instructor was also teaching to banking professionals in Malaysia.

There are a lot of algorithms for drift monitoring: supervised monitoring (when you can compare predictions against actual labels) and unsupervised monitoring (when actuals are not available, so you compare distributions instead). When we have population samples, we ask: between the times and dates, do we have stability in the data? That is what PSI measures.

Q: Could you read what the Population Stability Index is?

A: PSI is a statistical tool used to measure how much the distribution of data changes between two datasets, usually between a training dataset and a new dataset.

Interpretation: with a training data set we did everything; then we come into a new data set for production, real-time, or testing. What kind of distribution changes? A high PSI score indicates a significant change in the population distribution; a low PSI score indicates stability — the model is stable when detecting data drift, ensuring consistency.

How PSI works, step by step: take the feature (or score) you want to monitor, cut its range into \(n\) bins (e.g., deciles of the training distribution), and compute the share of records that fall into each bin in the training data (the expected share) and the share that falls into the same bin in the production data (the observed share). For each bin, compare the two shares; then sum the comparisons across all bins.

The PSI formula, with \(\mathrm{observed}_i\) being the observed share (fraction) of the population in bin \(i\) of the new data, \(\mathrm{expected}_i\) the expected share in bin \(i\) of the training data, summed over \(n\) bins, and \(\ln\) the natural logarithm:

\[ \mathrm{PSI} = \sum_{i=1}^{n} \left( \mathrm{observed}_i - \mathrm{expected}_i \right) \times \ln\left( \frac{\mathrm{observed}_i}{\mathrm{expected}_i} \right) \]

Why does this formula make sense? Each bin contributes two factors:

  • The difference \((\mathrm{observed}_i - \mathrm{expected}_i)\) measures how much the share moved.
  • The log ratio \(\ln(\mathrm{observed}_i / \mathrm{expected}_i)\) measures how surprising the move is in relative terms: a shift from 2% to 4% (ratio 2) is a bigger deal than a shift from 40% to 42% (ratio 1.05), and the log captures that.

A bin where observed equals expected contributes \(0 \times \ln(1) = 0\). Only bins where the shares actually moved contribute — so the sum is zero exactly when the two distributions are identical, and it grows as they separate. You can use a Python program to calculate this — find the score, low or high, and interpret the drift from it.

Standard reading of the PSI score (the thresholds used in banking practice):

PSI value Meaning Action
PSI < 0.1 No significant change — population stable Keep monitoring
0.1 ≤ PSI < 0.25 Moderate change Investigate which bins moved
PSI ≥ 0.25 Significant change — population drifted Take action (retrain, re-validate)

Worked example — a credit score distribution across three bins: A bank monitors its credit score model. The training data has 30% of applicants in bin 1 (low scores), 50% in bin 2, and 20% in bin 3 (high scores). Three months later, the production population has 25% in bin 1, 55% in bin 2, and 20% in bin 3.

  • Step 1 — per-bin terms:
  • Bin 1: \((0.25 - 0.30) \times \ln(0.25 / 0.30) = (-0.05) \times \ln(0.8333) = (-0.05) \times (-0.1823) = 0.0091\).
  • Bin 2: \((0.55 - 0.50) \times \ln(0.55 / 0.50) = (0.05) \times \ln(1.1) = (0.05) \times (0.0953) = 0.0048\).
  • Bin 3: \((0.20 - 0.20) \times \ln(1) = 0\).
  • Step 2 — sum: \(\mathrm{PSI} = 0.0091 + 0.0048 + 0 = 0.0139\).

Final answer: PSI ≈ 0.014 — well below 0.1, so the population is stable. Sense-check: the biggest shift was 5 percentage points in one bin, and the metric correctly reports a small, non-alarming change.

A second scenario with a real shift: suppose production becomes 10% in bin 1, 50% in bin 2, 40% in bin 3.

  • Bin 1: \((0.10 - 0.40) \times \ln(0.10/0.40) = (-0.30) \times \ln(0.25) = (-0.30) \times (-1.3863) = 0.4159\).
  • Bin 2: \((0.50 - 0.50) \times \ln(1) = 0\).
  • Bin 3: \((0.40 - 0.20) \times \ln(0.40/0.20) = (0.20) \times \ln(2) = (0.20) \times (0.6931) = 0.1386\).

\(\mathrm{PSI} = 0.4159 + 0 + 0.1386 = 0.5545\), far above 0.25 — significant drift, the bank must act. The applicant population changed shape: fewer low-score applicants, many more high-score ones.

Real-world: banks use PSI to monitor the stability of their credit and risk populations between training and production windows — the same index the instructor was teaching to banking professionals in Malaysia.

Pitfalls when using PSI:

  • Empty or near-zero bins. If \(\mathrm{expected}_i = 0\), the log ratio explodes. Standard practice: merge rare bins before computing, and add a small floor to both shares.
  • Bin count and bin boundaries. The same data set can give different PSI values with 5 bins versus 20 bins. Fix the binning scheme when the model ships, and keep it fixed.
  • Reading PSI in isolation. A stable distribution does not prove the model is healthy — concept drift (Section 9.5.4) can proceed with a perfectly stable input distribution. PSI is a necessary watch, not a complete one.

9.6.2 KL Divergence

The other metric is KL divergence — the Kullback–Leibler divergence, also called relative entropy.

Q: What is the KL divergence?

A: The Kullback–Leibler divergence, a relative entropy, is a statistical measurement from information theory commonly used to quantify the difference between a probability distribution and a reference probability distribution.

Entropy means the degree of disorder — uncertainty in the data. So we look at it like: I use a normal distribution, now I am using a binomial distribution — was there any relevance, and is there a divergence, what sort of divergence between the distributions? We can use that as a drift metric as well. KL divergence asks: how many extra bits of information do you need to describe the data if you use the reference distribution instead of the true one? The larger that extra cost, the more the two distributions differ.

The KL divergence between a distribution \(P\) (the observed distribution) and a reference distribution \(Q\) (the expected/training distribution), over all values \(x\) that the variable can take, with \(P(x)\) and \(Q(x)\) the probabilities each distribution assigns to \(x\):

\[ D_{\mathrm{KL}}(P \parallel Q) = \sum_{x} P(x) \ln\left( \frac{P(x)}{Q(x)} \right) \]

This is the standard definition of KL divergence — the session gave the definition in words, and the formula is the textbook one. Notice the structure: every term \(P(x) \ln(P(x)/Q(x))\) is the probability under the observed distribution times the log ratio of the two probabilities. When \(P(x) = Q(x)\) for all \(x\), every log ratio is 0 and the divergence is 0. When the distributions differ, each mismatched value adds a positive amount.

Worked example — two tiny distributions: Let \(P = [0.6, 0.4]\) (observed) and \(Q = [0.5, 0.5]\) (reference) over two values \(x_1, x_2\).

  • Step 1 — terms:
  • \(x_1\): \(0.6 \times \ln(0.6 / 0.5) = 0.6 \times \ln(1.2) = 0.6 \times 0.1823 = 0.1094\).
  • \(x_2\): \(0.4 \times \ln(0.4 / 0.5) = 0.4 \times \ln(0.8) = 0.4 \times (-0.2231) = -0.0893\).
  • Step 2 — sum: \(D_{\mathrm{KL}}(P \parallel Q) = 0.1094 - 0.0893 = 0.0201\).

Final answer: the KL divergence is ≈ 0.020. Sense-check: the distributions are close, so the divergence is small and non-negative — as every KL divergence must be.

Asymmetry check — flip the roles: \(D_{\mathrm{KL}}(Q \parallel P) = 0.5 \times \ln(0.5/0.6) + 0.5 \times \ln(0.5/0.4) = 0.5 \times (-0.1823) + 0.5 \times (0.2231) = -0.0912 + 0.1116 = 0.0204\). The value is slightly different (0.0201 vs 0.0204) — KL divergence is not symmetric: \(D_{\mathrm{KL}}(P \parallel Q) \neq D_{\mathrm{KL}}(Q \parallel P)\). That is a feature, not a bug: it tells you the direction of the change, which matters when you want to know whether production drifted away from training or the reverse.

PSI and KL divergence, side by side: both compare two distributions bin by bin with the log of the ratio. PSI weights each log ratio by the share difference \((\mathrm{observed}_i - \mathrm{expected}_i)\) and is the form banking practice standardized on; KL divergence weights each log ratio by the observed probability \(P(x)\) and is the information-theory form. Both are zero only when the distributions are identical, both grow as the distributions separate, and either can be used as the drift metric — the session flagged both as the important ones to know.

Recap + bridge: PSI sums \((\mathrm{observed}_i - \mathrm{expected}_i) \times \ln(\mathrm{observed}_i / \mathrm{expected}_i)\) over bins — under 0.1 is stable, over 0.25 is significant drift; KL divergence \(\sum_x P(x) \ln(P(x)/Q(x))\) measures the same separation from information theory and is asymmetric. Together they answer "has the population moved?" — the measurable half of the drift story. The other half is what to do about it: profiling the data (Section 9.7), monitoring continuously, and reacting with agile pipelines (Section 9.5.5).

9.7 ML Data Readiness and the Role of Data Profiling

9.7.1 Data Profiling as a Process

Hook: Everything in this lecture so far — quality dimensions, outliers, bias, leakage, drift — lands in one place: ML data readiness. A model is only ready for production if the data feeding it is understood, and understanding the data is the job of profiling.

ML data readiness is where data profiling comes in: data profiling is the process of analyzing the data set systematically to evaluate its quality. That is where all the data quality dimensions come into the picture — completeness, reliability, accuracy, integrity, and so on — plus the structure of the data and the content: what type of content it is carrying.

The process does three jobs:

  1. Provides insights into the metadata — the data about the data: column names, types, ranges, formats, lineage (where each value came from). Metadata is what makes a data set discoverable and auditable.
  2. Evaluates the data integrity — the references hold together, the keys are unique, the values obey their rules.
  3. Supports data governance — profiling produces the evidence base that governance policies (who can see what, what quality is guaranteed, how data is documented) are built on.

Most organizations are focusing on data profiling — it is the cheapest place to catch problems before they become pipeline failures, model errors, or compliance incidents.

9.7.2 Single-Field vs Multi-Field Profiling

Data profiling is single-field or multi-field. The two modes answer different questions:

  • Single-field profiling examines one column at a time. For a single field — like age or sale — we look at the summary statistics of the data (mean, median, min, max, percentiles), the data type, the data value, and the distribution (histogram shape, skew, cardinality, missing-value rate).
  • Multi-field profiling examines how columns relate. For multiple fields, we look at the dependencies and keys: how a score or sale value is related to other values — we can visualize the relationship (scatter plots, correlation, foreign-key checks between tables).

Worked example — profiling a sales table (from the session):

Single-field profiling of the "sale" column:

Check What you look at What a profile would report
Summary statistics mean, median, min, max e.g., mean 142.50, median 95.00, min 0.00, max 9,999.00
Data type and values declared type vs actual values "sale" declared decimal, but 12% of rows hold text "N/A"
Distribution histogram shape heavily right-skewed; most sales under 200, a few huge ones

Multi-field profiling of "sale" against "region":

Check What you look at What a profile would report
Dependencies does sale depend on region? average sale in Region A is 3× Region B
Keys and joins does every sale row link to a customer? 7% of sale rows reference missing customer IDs (integrity failure)

Final answer: single-field profiling describes each column alone; multi-field profiling finds relationships and broken keys between columns and tables. Sense-check: the single-field pass caught the skewed distribution and the type mismatch; the multi-field pass caught the missing customers — neither pass alone would have found all three problems.

9.7.3 Data Profiling on the Comprehensive Exam

Exam note: the instructor stated explicitly that a question related to data profiling will be asked in the comprehensive exam — making some decisions in drift, model drift, and data drift, and then the role of data profiling. Prepare the full chain: what profiling is, the quality dimensions, the role profiling plays in data readiness, and how drift (data, model, concept) decisions connect back to it.

Q: Will data profiling appear on the comprehensive exam?

A: Expect a question related to data profiling — making some decisions in drift, model drift, and data drift, and then the role of data profiling.

Recap + bridge: Profiling is the systematic evaluation of data quality — it feeds metadata, integrity checks, and governance, and it is the foundation of ML data readiness. Single-field profiling describes columns; multi-field profiling finds dependencies and keys. And it is examinable: expect a comprehensive-exam question linking profiling with drift decisions and model readiness. Profiling tells you whether the data is fit — but producing fit data is the work of the engineering half of the lecture: integration (9.9), transformation (9.11), and the patterns that organize them (9.12). Before that, the session pauses for a story about why honesty beats shortcuts in exactly the way it beats shortcuts in data (9.8).

9.8 The Leadership Story: Honesty and Continuous Effort

9.8.1 The King and His Final Test

Hook: What does a story about choosing a king have to do with data quality? Everything — the session's story of three contestants maps point-for-point onto data leakage, decorated-but-empty data, and honest, consistent effort.

A king — a very nice guy, friendly, and as a leader of the kingdom he needed to be a good person for everyone: no bias, fairness, integrity for the country. He wanted to decide who would be the next king for the kingdom. He announced to the entire kingdom a set of competitions — muscle wrestling, bow and arrow, elephant riding, and more — to select the power of the young man or young girl who would be the next king or queen.

With all the tests, only three people got selected. The three stood the best: they were good in astronomy, good in the Veda, good in martial arts, good in the history of the country, good in the geography of the country, everything. After three months of struggle, the three came to the palace. The king was confused — he thought only one person would come, but three came. How do I select the next king? The first two guys said: "Maharaj, no worries — I can rule for one year, he can rule for the second year, we alternate." The third person was very quiet: "I am okay with whatever you are saying."

The king discussed with the minister and got an idea. This is the last — but not least — final test. He ordered big jute sacks — the kind used to carry rice and wheat. Three big sacks, one for each candidate. "Take this, collect as much as possible food items. I promise that I won't check what is inside. The country has a problem — scarcity, no rain. Collect as much as possible; whoever collects more, I may decide and give the role as king. Go — but don't mix yourselves." The three were sent into different, different directions, and the king said: "I don't monitor you also."

9.8.2 The Three Contestants

Contestant one — the decorator. "What the hell — I have been doing this three months, six months of competition, and now the King is giving this work?" For a couple of days he did good work — collecting some peanuts, some bananas, trying to find something — then he became so tired. The bag was almost 25% filled. He thought: "We have time — one week he gave. The last day is there, we will find out something; next Sunday we will do it." So he took rest and enjoyed his time off. On the last day he went and looked at dead grass and dead leaves, and filled all of it in the bottom — up to 100%. On top of it he put the vegetables and fruits he had collected — bananas, peanuts — so the bag looked full: uneatable dead grass below, and 25% of genuine vegetables and a little bit of fruits on top.

Contestant two — the fixer. "Oh my god, this is the ridiculous thing. Let me try something later at the end." He was a wealthy fellow — a big, big guy with a chain. "Worst case, I can use the money to buy — because the King said he is not going to check, no monitoring, no sensors, nothing." For the first five days he collected nothing and took rest. In the last two days he gave his chain to a shop and bought rice — he filled the bag 50%, and all his money was gone. "Oh my god, what should I do? Only 50% of the bag is full." Then his crooked mind started thinking: he went around all the villages and streets where people throw damaged fruits, damaged vegetables, contaminated fruits; he took them, cleaned them, and dumped them into the bag. Now good items and bad items got mixed up.

Contestant three — the steady collector. He started collecting every day something — some peanuts, some bananas, some grapes, whatever he was able to find out. He went around, took rest, collected; took rest, collected. He could not fill the bag — it was about 30% — but he did his best.

9.8.3 The Jail Test

Now the three went to the palace, each carrying a heavy bag, each saying "mine is bigger." The king welcomed them: "Very good, you have done your final job." Then he ordered the soldiers — the security guard — to put the three people in separate jail chambers. No water, no food — that's it.

The first guy, who collected 25% plus decoration, survived for some days — three, four days. He ate all the vegetables, then he started taking the leaves; he started feeling thirsty; he was finding it hard to find food — and he died.

The second guy — the good food and bad food got mixed up. He got diarrhea, bacterial infections from all the food items, because it was all mixed up. He washed it, but damage being damaged — data leakage already created — so he started giving him leakages. He died in seven days.

Only the third person survived: he collected only a little items, he was able to manage, eat slowly — he got some banana — and he survived on the eighth day. Next week they opened the chamber and announced the third person — the one who collected the little — was finally the king.

9.8.4 The Data Lesson Inside the Story

Success is not doing one thing, one time, great. Success is doing it continuously. Honesty is the best policy, especially for good leaders. There is no shortcut to get success.

Q: Can a shortcut ever work?

A: Sometimes the cricket thing will work, but it does not stay all the time. Success is not doing something great one time — it is continuous effort. Good works get rewarded.

Worked example — the three sacks, by the numbers: the final test came down to three bags of food and three outcomes.

  • Contestant one — the decorator: about 25% genuine food (peanuts, bananas, vegetables) with dead grass and dead leaves filling the bag to 100% on top. In the jail test, he ate the vegetables first, then the leaves, ran out of food and water, and died in about four days. The bag looked full; the usable content was a quarter of it.
  • Contestant two — the fixer: 50% bought rice, topped up with contaminated, damaged fruits and vegetables collected from the streets. In the jail test, the good and bad food were mixed — he got diarrhea and bacterial infections, and died in seven days. The bag was half full, but half of the half was poison.
  • Contestant three — the steady collector: about 30% honest food, collected a little every day. In the jail test, he ate slowly, rationed carefully, and survived — and became the king.

Final answer: 25% + decoration dies, 50% + contamination dies, 30% honest survives. Sense-check: the winning bag was the smallest — the test was never about volume, only about whether the food was real and uncontaminated, which is precisely the data-quality distinction of this lecture.

The story maps onto data quality — each contestant is a data strategy:

Contestant What they did The data-quality meaning
First 25% genuine food, decorated on top with dead leaves to look 100% full Data that looks complete but is not — decoration, not substance. It survives profiling glances and collapses the moment it is actually used.
Second 50% bought rice mixed with contaminated, damaged food Data leakage — literally. Once good and bad are mixed, everything downstream is damaged; washing it (cleaning) cannot restore it. He "started giving him leakages" — the contamination spread exactly like leakage spreads through a pipeline.
Third About 30% honest food, collected steadily every day Consistent, honest data quality — small daily increments that actually sustain the user. It "does not look biggest," but it is the only thing that survives.

The leakage lesson, made explicit: the second contestant's bag is the lecture's warning story for Section 9.4. Contamination is irreversible — "damage being damaged — data leakage already created." No amount of downstream cleaning, washing, or patching restores data that was mixed with garbage at the source. The first contestant's bag is the mirror-image failure: data engineered to look complete. Both fail in the jail test — the moment the data is actually consumed.

Recap + bridge: Success is not one big push; it is continuous effort — honesty is the best policy and there is no shortcut. The king's test is the data-quality allegory of the whole lecture: decoration dies, contamination spreads, and steady, honest, daily quality survives. That is the mindset behind the engineering work that follows: integration (9.9), data engineering (9.10), transformation (9.11), and the patterns that keep data clean layer by layer (9.12).

9.9 Data Integration

9.9.1 Why Data Must Be Integrated

Hook: No single system in your organization has the whole truth. The customer lives in the CRM, their orders live in the ERP, their behavior lives in the app logs, and the metadata about all of it lives somewhere else again — the model needs the joined picture.

The opening question of the new topic: why does data have to be integrated?

Q: Why does data have to be integrated?

A: Data comes from different sources — structured, unstructured, vast amounts of data — so it has to be integrated properly. A single source rarely gives everything; some data may be partial, so integrating it gives the correct context and makes decisions more informative. It is practically not possible to get all the data from a single source — it could be a database, a SaaS application, or a microservice — and we have metadata stored somewhere else, so we need to connect to it and join the data together so that we can fit it to the model.

Three reasons stand out in the answer:

  1. Data is fragmented. One source holds orders, another holds customers, another holds events — and each source is only a partial picture. Integrating gives the correct context.
  2. Decisions need the full picture. Each source says something; the joined data is what makes a decision informative rather than lopsided.
  3. Metadata is separate. The schema, the lineage, and the meaning of fields often live outside the data itself — integration is also about connecting data to its metadata.

9.9.2 What Data Integration Is

Data integration combines various types and formats of data from many sources across an organization into a data lake or a data warehouse to provide a unified fact base for analytics. The main purpose of data integration is to give a better insight and a good unified fact. Each source says something; finally we need to make a better decision, align the departments to work together, and serve the customer better.

It means consolidating the data from multiple sources into a single set for consistent business analytics — and at the end of the day you may use it for data engineering, data analytics, or business intelligence. To move the data from one place to another, we need to understand the structure and meaning of the data — you cannot integrate what you do not understand. That is why profiling (Section 9.1) and integration go hand in hand: profiling supplies the understanding of structure and meaning that integration needs.

9.9.3 Data Ingestion vs Data Integration

Data ingestion is where data is moved from one source into another system — normally taking from one source and putting into another system. But data ingestion could involve extended activities: data cleansing, data sorting, data enrichment, beautifying the data, data massaging, data scrubbing, web scraping, and other processes to make the data ready for use at its final destination. Sometimes this happens before the data is stored — that is why we call it ETL or ELT. Sources can be an OLTP database, a SaaS API, or AWS S3 buckets and containers. There is a data ingestion layer and a data integration layer.

Q: What is the difference between data ingestion and data integration?

A: Data ingestion involves collecting and transferring data from various input sources to the target storage for further processing. Data integration unifies raw data from disparate sources, applies transformation, and loads it into a data warehouse or a data lake.

Disparate means the data is not properly uniform — one source may use sensors, another may use something different — it is not uniform; it may be diversified, stratified sources. So we apply transformation, we do some normalization, we manage it — for example, a customer table with a customer ID as an integer column — we transform it and make some kind of formulas. That is why we use a lot of ETL tools.

Comparison — ingestion vs integration:

Dimension Data ingestion Data integration
Core job Collect and transfer data from input sources into target storage Unify raw data from disparate sources into one consistent picture
Orientation One source at a time, into a system Many sources at once, into a unified fact base
Handling differences Transfers; light preparation Applies transformation, normalization, and management across sources
Typical destination Target storage (bucket, warehouse, lake) Data warehouse or data lake (joined, consistent tables)
Tooling Often no dedicated tool needed ETL tools (DataStage, Informatica, and others)

One-line rule: ingestion gets data in; integration makes it one. Ingestion answers "how do I move it?" Integration answers "how do I make these many sources one consistent set?"

9.9.4 The Bronze, Silver, Gold Layers

Integration work is organized into layers — bronze, silver, gold — and gold is what we are really targeting.

Q: What does the gold layer consist of?

A: The gold consists of aggregated, normalized, clean tables — we take the silver data, aggregate it, normalize it, and make it better.

Your bronze consists of multiple things: we just ingest the data and put it there — the client table, the apps table, static data. In the silver layer we integrate everything: more normalized, more aggregated, a good clean table. Then the gold layer is the aggregated, normalized, clean result. (There is an Oracle product called Oracle GoldenGate — the joke in the session was that maybe that is why it is called the Golden Gate.)

The layers are a ladder of increasing quality and structure:

Layer What lives there Purpose
Bronze Raw ingested data, as-is Landing zone; nothing lost, nothing improved yet
Silver Integrated, normalized, aggregated, clean tables The working layer where sources are joined
Gold Aggregated, normalized, clean result tables The layer downstream consumers and models actually use

9.9.5 Tools for Data Integration

For data integration there are many ETL tools: DataStage, Informatica, Oracle Warehouse Builder, ODI — a lot of tools are available. For data ingestion you don't need a tool — you just take the data and put it there in the target. The distinction from Section 9.9.3 shows up in the tooling: integration is complex enough to warrant dedicated ETL platforms; plain movement is not.

9.9.6 Challenges of Modern Data Integration

The challenges with modern data integration: the explosion of data and data structures, combined with radical innovation and the demand for continuous, real-time data — that is why we need streaming. And with DevOps and agile practices being followed, we need to make sure we meet the increasing demand for always-on, self-service data.

Four pressures in one sentence: more data, more varied data, faster data (real-time, streaming), and more demanding consumers (always-on, self-service). Integration is no longer a quarterly batch job — it is a continuously running, continuously monitored system.

9.9.7 The Three Waves of BI

This world is moving towards third wave BI. Real-world: use your Fitbit app or any mobile banking app. Olden days — if you wanted a report, you had to go and beg the bank; two weeks, even two years ago, if you wanted to know something there was no way to get a PDF. Now they show charts — what is the spending, what is the amount in hand — and give you a self-customizable portal. That means data should be available to the customer: that is third wave BI.

  • First wave BI: only the database administrator can do something — pull the data, run some SQL queries, create one big report: what was the amount summary five years ago.
  • Second wave BI: you go to the bank, there is a portfolio administrator or bank administrator; you put a request, they have ready-made queries, they may go and pull the data from some other system and give it to you.
  • Third wave BI: you have everything — you configure whatever you want, you customize whatever you want.

Worked example — three waves, one question (from the session): "How much have I spent this month on my card?"

  • First wave: you call the bank. A database administrator pulls the data, runs SQL queries, and produces one big report — the amount summary. Days later, you get your answer. You had to ask; the query was not yours to run.
  • Second wave: you visit a portfolio administrator or bank administrator with a request. They use their ready-made queries — they may pull the data from some other system — and hand you the result. Faster than the first wave, but still mediated by a human with pre-built queries.
  • Third wave: you open the mobile banking app or your Fitbit. The charts are there — spending this month, amount in hand — and you can customize the portal yourself. Self-customizable, always on, no human in the middle.

Final answer: the third wave hands the data to the customer directly — self-service analytics, configurable by the person who owns the question. Sense-check: the same data, the same question, three different distances between the customer and the answer — and only the third wave makes the distance zero.

That is why data transformation and data integration play a vital role in the modern world: the third wave runs on integrated, transformed, reliable data.

Recap + bridge: Data integration unifies fragmented, partial, disparate sources into a unified fact base — ingestion moves data in, integration makes it one; the work is organized into bronze, silver, and gold layers; modern integration faces data explosion, real-time demand, and self-service expectations (third wave BI). Integration is the "bringing together" half of the engineering story — the next section looks at the discipline that builds and operates these pipelines: data engineering.

9.10 Data Engineering

9.10.1 Science vs Engineering

Hook: A physics textbook can explain Bluetooth; it takes engineering to ship a headset that millions of people can buy. The same gap separates knowing about data from building the systems that manage it — and that gap is data engineering.

A question the instructor always asks when teaching any analytics or engineering subject: what is the difference between science and engineering?

Q: What is the difference between science and engineering?

A: Engineering is a field where you apply the science. Science is a broader field; when we think about theory and practical, the practical part is mostly delegated — the application knowledge is there on the engineering side.

The instructor's own perspective: science gives the facts, the rules, the findings, information about a lot of things, how something should work — like Ohm's law, \(V = IR\), pressure, biology, geology — all the formulas, inventions, laws, and facts. Engineering puts that into an action: makes it a product, makes it a solution. Engineering provides a structured, disciplined methodology — a well-defined framework; we follow a framework, a structure, a method, a step-by-step procedure.

Worked example — the Bluetooth headset (from the session): There is science in the Bluetooth headset — Bluetooth communication is science, noise cancellation is science. But engineering makes it a product — a nice product, made in a structured way, with quality checks and a stringent, systematic, disciplined approach, so that many, many headsets are produced.

  • Science supplies the rules: radio wave propagation, the Bluetooth protocol, the physics of noise cancellation — the formulas, laws, and findings.
  • Engineering turns the rules into a product: a design, a bill of materials, quality checks, a manufacturing process that produces many headsets that all work the same way.
  • Technology makes life easier: Bluetooth, cloud computing, IoT, WiFi — there is science behind it all.
  • Management — selling it — people involved. The people who organize production, distribution, and sales.

Final answer: for anything, there is science, engineering, technology, and management — and the same four layers apply to data. Sense-check: knowing \(V = IR\) does not make you an electrical engineer; knowing SQL does not make you a data engineer — the engineering layer is the structured, repeatable application.

9.10.2 What Data Engineering Is

Data engineering means engineering the data. Doctors deal with the anatomy of a human — a doctor knows your entire anatomy just by checking your pulse when he touches your hand. Similarly, a data engineer — or a data scientist, with little variations between the two — applies an engineering way of dealing with the data.

The pulse analogy (from the session): a doctor touches your wrist and reads your whole anatomy from the pulse. A data engineer should be able to do the same with a data set: look at a sample, check the metadata, and know the state of the data — its quality, its sources, its problems. That deep familiarity is what turns data handling from a chore into an engineering discipline.

That is data engineering: using data integration by technical users to develop, manage, and optimize data pipelines, mostly for analytical use cases, in a systematic way — delivering modern data management architecture, self-service data integration, operational data integration, and supporting AI projects.

9.10.3 The Core Data Engineering Steps

The core data engineering steps:

Data generation, data ingestion, data storage, data processing, data pre-processing, data transformation, data management, data governance, data analytics, data visualization, data monitoring.

Everywhere we follow a systematic approach, until the data is monitored and governed. The loop starts where data is born (generation) and only ends where data is watched (monitoring) — with governance over the whole lifecycle. The data integration tools support extraction, ingestion, and delivery — bulk data, batch data — and simple data transformation: sync to text, text to number, number to text — doing some encoding, data encoding.

9.10.4 What Integration Tools Must Provide

The tool is supposed to provide data engineering, take care of any data architecture, take care of self-service data integration, take care of operational data integration, and of course support AI — any data integration tool may be SaaS-based or cloud-based, deployed on premises, public or private cloud.

An EDA code — an exploratory data analysis script shared in the session — gives you a lot about data engineering on the data: what features are we expecting, what is augmentation — how we expand this further — how we are managing the metadata, and data governance. Data engineering provides all the sophisticated techniques for data operations:

  • Pipeline design — what sort of pipeline we are going to build, how it is going to be integrated.
  • Automated testing — how we are automatically testing the data.
  • Orchestration — scheduling and coordinating pipeline steps.
  • Continuous integration, continuous delivery — the CI/CD pipeline that ships pipeline changes safely.
  • FinOps — the allocation of resources: what type of costs are involved for every data generation — you can attach the cost operations to the data operations.

And there are AI-focused features: any kind of text and NLP, vector databases, any kind of LLM or RAG — for sentiment analysis or bulk context — plus images, device information, and IoT data, where we may use machine learning packages like computer vision and neural networks, depending on the nature of the data you are trying to process.

Scope — engineering versus science in the exam sense: remember the session's framing — science supplies the facts and rules; engineering supplies the structured, disciplined, step-by-step method. On any question about data engineering, the expected answer is the method: systematic steps (generate → ingest → store → process → transform → manage → govern → analyze → visualize → monitor), organized tooling, and operational concerns (automated testing, orchestration, CI/CD, FinOps) — not just a list of facts.

Recap + bridge: Data engineering is the disciplined application of science to data — like the doctor reading anatomy from a pulse, the engineer knows the data's state; the core steps run from data generation to monitoring and governance; integration tools must cover architecture, self-service and operational integration, AI support, testing, orchestration, CI/CD, and FinOps. Engineering builds the pipelines — the next section covers the heart of the work those pipelines do: data transformation.

9.11 Data Transformation

9.11.1 What Data Transformation Is

Hook: Raw data is rarely usable data — dates arrive in six different formats, units mix kilometers with miles, names are crammed into one column, and typos hide in the middle of a million rows. Data transformation is the work of turning that mess into something a model or a report can trust.

The flow: you have a source, you can ingest; go to a stage; we do a transformation; we transform the data and move that into a destination. Data transformation is the process of converting raw, unstructured, inconsistent data into a clean, usable format for future analytics, reporting, and machine learning. It ensures the data is standardized, accurate, and aligned with your business keys — the identifiers your business actually uses to refer to entities (customer IDs, product codes, order numbers).

The source → stage → transform → destination picture is the pipeline skeleton: data enters, gets reshaped in the middle, and leaves in a form downstream systems can consume.

9.11.2 The Seven Types of Transformation

The session opened this topic with two questions that pinpoint where transformation starts:

Q: What was the first thing we do in the data transformation?

A: We check for null values, remove duplicates, handle missing values, correct typos, and validate formats.

Q: What is the second type of transformation?

A: Converting units of measurement, aligning date-time formats, and harmonizing conventions.

Where do these map to? The seven types of transformation:

  1. Data cleaning — removing duplicates, handling missing values, correcting typos, and validating formats. The first pass over the data: every row and field checked for the basic failures.
  2. Data standardization — converting units of measurement, aligning date-time formats, and organizing naming conventions. Example: I have DDMMYY; I change it to year, month, date, because US customers look for month and date.
  3. Data summarization (mostly aggregation) — summarizing granular data to high-level insights: quarter one, quarter two, quarter three; weekly sales, monthly sales — we call it the aggregated value; we sum it up.
  4. Data enrichment — enhancing the data set by adding new information: derived features, extended features.
  5. Data integration — combining data from multiple sources into a unified view: I get all the customer data from local, internal, external sources and combine it for a unified view.
  6. Data normalization — structuring the data to minimize redundancy and improve integrity.
  7. Data filtering — narrowing down the data set based on conditions or rules; in Excel we do a filtering.

Q: Removing duplicates, handling missing values, correcting typos, and validating formats — which transformation type do they belong to?

A: Data cleaning. Converting units of measurement and aligning date-time formats belong to data standardization — for example, changing DDMMYY into a US month-first format.

The correction to remember: cleaning and standardization are two different types — cleaning fixes what is wrong (duplicates, nulls, typos), standardization makes everything consistent (units, dates, naming). A common exam trap is calling date conversion "cleaning" when it is standardization.

Worked example — date standardization (from the session): A European source stores dates as DDMMYY — day, month, year, for example "25-09-98". US customers look for month and date first, so the target format is YYYY-MM-DD.

  • Step 1 — parse the source: "25-09-98" means day 25, month 09, year 98.
  • Step 2 — normalize the year: 98 is a two-digit year; the business rule expands it to the full year: 1998.
  • Step 3 — write the target format: the standard form is year, month, date: "1998-09-25".
  • Step 4 — check the ambiguity risk: "01-02-98" is 1 February under DDMMYY but 2 January under MMDDYY. A naive conversion treats the string the same way regardless of meaning — so the mapping rule must state the source convention before conversion.

Final answer: 25-09-98 → 1998-09-25, and the rule "source is DDMMYY" is part of the transformation. Sense-check: the value is unchanged in meaning — only the representation changed — which is the definition of standardization. Get the convention wrong and the same string silently means a different date, exactly the kind of error that cost banks dearly in the Y2K era below.

Units conversions: kilometers to miles, kilograms to pounds, liters to gallons. Each conversion is a standardization rule with a fixed factor: 1 mile ≈ 1.609 kilometers, 1 kilogram ≈ 2.205 pounds, 1 gallon ≈ 3.785 liters. So 5 km becomes 5 / 1.609 ≈ 3.1 miles; 10 kg becomes 10 × 2.205 = 22.05 lb; 4 liters becomes 4 / 3.785 ≈ 1.06 gallons. The session also mentioned a spoken phrase that was hard to make out — "learning deformer" — which in the context of the seven types is best read as a format transformation (reformatting): changing how a value is represented (text ↔ number ↔ date layout) rather than what it means, which is precisely what standardization does for date-time and numeric formats.

War story — the Y2K project: when working in the US on the Y2K project around the year 2000, many systems did not support the year; banks were so scared — till 1999 they knew the number, but the number was going to change to 2000 and they did not know what to do. Many people were hired just for Y2K; it was one of the biggest challenging projects. People were working through December and Christmas time. The lesson: date-time alignment is a real, massive-scale transformation problem — two-digit years, missing century logic, and systems that could not hold the year 2000 were hidden across millions of lines of code, and the fix was a giant, coordinated transformation project.

9.11.3 The Transformation Process Loop

The data transformation process consists of:

  1. Data discovery — discover the data, where the data is coming from.
  2. Data mapping rules — how we are going to map from field one to field two, source one to target.
  3. Transformation logic — what sort of transformation logic we are going to do.
  4. Execute the process — run the transformation.
  5. Validation and testing — check the results.
  6. Documentation and monitoring — record what was done and watch it.
  7. Repeat — the process starts again for the next cycle.

9.11.4 Data Discovery

Before any transformation begins, the team must understand the data they are working on: understand the data, look at the data profiling, look at the data quality dimensions — what the data is, where the data comes from, what the dimensions of the data are, what the data is all about.

Discovery covers the structure, types, volumes, and quality of the data — the quality dimensions from Section 9.1. Discovery helps identify inconsistency, anomalies, and areas where transformation is necessary. We also gather metadata: where the data has come from — key to automation and lineage tracking, and to detecting any contamination. Discovery is the profiling step inside the transformation loop: you cannot map or transform data you have not examined.

9.11.5 Data Mapping and Surrogate Keys

Data mapping is where we define the source-to-target mapping rules: how one field corresponds to another field — CUS ID to customer underscore ID or CID. Choose the right values so they end up in the right place across different schemas — for example, customer first name, how you are mapping it. Clear mapping is crucial for schema alignment when we integrate multiple sources, because the naming convention is very, very important. Every field needs a rule: which source field feeds which target field, and what conversion happens on the way.

A surrogate key is a system-generated sequence.

Q: Has anyone heard of a surrogate key?

A: In data warehousing, in fact and dimension tables, a surrogate key is a system-generated sequence used to identify a unique row — like an Oracle sequence, a UI screen ID, or a client transaction ID.

The surrogate key will correspond to all the other things: you define some rules, and only when everything is done — this done, this done, this done — a unique transaction ID is generated. If I have four values, four dimensions, all combined, then I generate a fact, then I create one sequence value — a screen ID, or a surrogate key — or simply a customer ID.

Worked example — generating a surrogate key: a fact row is identified by the combination of four dimensions: product ID = 7, region ID = 2, customer ID = 1041, and time ID = 202409. The business rule says a row is complete only when all four dimensions are present.

  • Step 1 — the rule check: all four values exist and pass validation (product exists, region exists, customer exists, time is a valid date).
  • Step 2 — create the fact: the fact row (sales amount = 350.00) is now ready to be inserted.
  • Step 3 — generate the sequence: the system assigns the next sequence value — say, surrogate key 12,345 — as the row's unique identifier.

Final answer: the surrogate key (12,345) is a system-generated sequence assigned only after the fact row is complete. Sense-check: the business keys (product 7, region 2, customer 1041, date 202409) tell you what the row is about; the surrogate key tells you which row it is, and it stays stable even if a business key later changes.

9.11.6 Transformation Logic Design and Execution

In transformation logic design we decide what type of logic we are going to do: which one we are trying to convert; what type of regular-expression-based logic; how we split a big name into first name, last name, and middle initial — what type of parsing. We can use SQL transformation — NVL, substring, aggregation. All those logics are defined in the transformation — ETL or ELT. We can write the transformation rules using Python or SQL; normally we do it in stored procedures — not triggers, mostly stored procedures. We execute that: once the transformation logic is defined, we execute it as a batch job or a streaming job.

Q: Does the transformation happen before or after the data is loaded?

A: In the traditional ETL pipeline the data is extracted, transformed, and loaded, so transformation happens before loading. In ELT the transformation happens after loading.

In the traditional ETL pipeline the data is extracted, transformed, and loaded into the destination system — transformation happens before the loading. In ELT, transformation happens after the loading — the raw data lands in the target storage first, and transformation runs inside the target environment (which is why the DBT pattern in Section 9.12 is an ELT pattern). Execution engines can be built in-house or managed through a toolkit — there are tools like DBT and Apache Beam, the standard names for the transformation frameworks the session pointed to.

Comparison — ETL vs ELT:

Dimension ETL ELT
Order Extract → Transform → Load Extract → Load → Transform
Where transformation runs In a staging environment before the warehouse Inside the target (warehouse/lake) after loading
Data movement Transformed data travels Raw data travels; transformation happens in place
Typical tooling Classic ETL tools (DataStage, Informatica, ODI) DBT, Apache Beam, modern lakehouse engines

One-line rule: ETL transforms before loading; ELT transforms after loading. If a question asks when transformation happens, the order of the letters is the answer.

9.11.7 Industry War Stories

Worked example — Lorenzo: unifying seven legacy systems (from the session): when working at a healthcare product company, we built a healthcare system called Lorenzo — L-O-R-E-N-Z-O. There were so many systems — pharmacy systems, lab systems, patient management systems — seven or eight different legacy tools, different software: one written in .NET, one written in VC, one just using Oracle — they built Oracle financials, they built something — different products, different schemas. It was a very hard time to do the transformation.

  • Step 1 — the problem: olden days, before the integrated system, pharmacy is separate; pharmacy doesn't talk to a patient management system; patient laboratory is separate.
  • Step 2 — the approach: use a replication logic: we created materialized views and a lot of stored procedures; from all these file systems we used to pull all the data, we create a procedure, and we try to get it — we do our own transformation rules and logics.
  • Step 3 — the result: everything goes into one unified system — an integration system that can serve patients, serve pharmacy — built with our own materialized views, replication, and surrogate keys.

Final answer: Lorenzo unified pharmacy, lab, and patient management by pulling data from seven or eight legacy systems through materialized views, stored procedures, and replication. Sense-check: the transformation was not one big rewrite — it was a steady replication-and-conversion process, exactly the "continuous, small increments" philosophy of Section 9.8.

Q: Has anybody heard of a materialized view?

A: We used materialized views with replication logic and stored procedures: pull data from all the legacy systems into an integration system like Lorenzo, so pharmacy, lab, and patient management finally talk to each other. (A materialized view is a stored copy of a query's result — unlike a plain view, it is an actual table of data, which makes it ideal for pulling data out of legacy systems into a new one.)

Worked example — the Oracle EHR case (a student's current project): an Oracle-acquired company that builds electronic health record (EHR) systems. The legacy system has pharmacy, patient management, and revenue cycle — each one is a decentralized system with its own monolithic database. When building modern systems with AI at the core, we need to create our own transformation strategy and execution plan.

  • Step 1 — take the whole database as-is and put it into the new tenancy.
  • Step 2 — create views — materialized views — out of it, and from those views we create an executor.
  • Step 3 — change data capture (CDC): anytime a change happens in the old system, immediately that hits the materialized view and the executor brings it back.
  • Step 4 — route the changes: a rule engine with classification rules decides whether a CDC change is pharmacy data, patient data, or documentation data, and routes it to the right table.
  • Step 5 — serve existing customers seamlessly: for existing customers we need all the previous data to work seamlessly — that means going with a Lambda architecture where batch processing is also entertained (batch keeps the historical load complete, streaming keeps the changes flowing).
  • Step 6 — zero compromise on safety: since these are healthcare data, zero compromise is possible: if there is missing data, it will call for FDA reporting — all those things come into play — so safety is taken care of.

Final answer: CDC + materialized views + a routing executor + Lambda architecture transform a monolithic legacy EHR into a modern tenancy without losing or corrupting patient data. Sense-check: the old system stays live and its changes flow through the executor — the transformation is continuous, not a risky cut-over, which is the only acceptable mode for FDA-reportable healthcare data.

Q: How do we route changes that arrive through change data capture?

A: We have a rule engine with classification rules: when a CDC change happens, we know whether it is pharmacy data, patient data, or documentation data, and route it to the right table.

The instructor's approach from 12–15 years ago: before building a new product or consolidating products, build a big repository — an enterprise data information store — a very big metadata model, a very big inventory that serves as a knowledge base, so you don't miss anything. Then create the rules, derive the rules: "I want to integrate everything, I want to create a new business line." You can use the Lambda approach, or materialized views, or write views, or create stored procedures, or use some AI tools, or run Python programs — it just goes and pulls the data and tries to create a new workflow; you can create a new database or data tables on the fly, and your application will be built on the fly. Once everything succeeds, you spin from this one and create a new product. That's how the world is moving.

And depending on the nature of the data: if the knowledge is content-driven, context-driven, or involves a lot of sentiments, you can start building a large language model on top — an ML pipeline on top of it. If it is more images, device information, or IoT data, you may use machine learning packages like computer vision or neural networks. Stored procedures may not work — but AI will work: AI works with text, audio, video, and image data.

Scope — choosing the execution tool for the data type: Stored procedures and SQL are the workhorses for structured, tabular data — the Lorenzo story. But when the data is content (text, sentiment), AI models like LLMs take over; when it is images, device information, or IoT streams, computer vision and neural network packages take over. The transformation strategy must match the data's nature: rules-based logic for structured data, AI-based logic for unstructured content.

9.11.8 Validation and Testing

Finally we need validation and testing. We discover the data, we build the mapping, we did the transformation, we define the rules, the rules are executed through some tools — DBT, Apache Beam, Oracle, or your own tools — and then it is the duty of validation and testing to make sure the data is properly transformed and validated.

Teams run a lot of tests:

  • Regression tests — check that new transformation logic did not break what previously worked.
  • Integrity tests — check that references and keys still hold after transformation.
  • System tests — check the whole pipeline end to end.

The point is to confirm all the data is properly transformed: data quality checks, schema validation, row counts, making sure data integrity is maintained. That is very important — a transformation that silently drops 10% of the rows has "succeeded" by the code's logic and failed by the data's reality. Row counts before and after, plus schema validation, catch that class of failure.

9.11.9 Documentation, Monitoring, and the Repeat Loop

Finally we start documenting the whole process, and then monitor, monitor, monitor. Documentation records the mapping rules and logic so the next team (or the next run) can reproduce the work; monitoring watches the executed jobs so a silently failing transformation gets caught, not ignored.

The instructor illustrated the loop with a time-loop joke — a famous Tamil movie dialogue where one person came to a meeting, was shot, became dead, and then it repeats — and the Doctor Strange example, where he keeps fighting the evil Dormammu for years together. The idea: whenever you think of this data transformation process, remember this — discover the data, map the data, build the rule, execute the rule, validate and test, document and monitor, and repeat the process.

Recap + bridge: Data transformation converts raw, inconsistent data into a clean, usable format through seven types (cleaning, standardization, summarization, enrichment, integration, normalization, filtering) inside a loop — discover, map, build the rule, execute, validate and test, document and monitor, repeat. Mapping and surrogate keys keep sources aligned; ETL transforms before loading, ELT after; war stories (Y2K, Lorenzo, Oracle EHR) show the scale and stakes. The next section organizes this work into repeatable patterns — the medallion architecture and the DBT pattern.

9.12 Data Transformation Patterns

9.12.1 Why Patterns Matter

Hook: Software engineers do not reinvent the wheel for every app — they reuse patterns, proven shapes for solving the same problem over and over. Data transformation has the same need, and this section gives you the two patterns the session flagged as key: the medallion architecture and the DBT (ELT) pattern.

There are a lot of patterns out there — design patterns, architecture patterns. We use a pattern to repeat some process, to simplify some process. Software architecture is worth studying: computer science is common sense — think and relate. In olden days, to develop software and mobile applications, we had patterns:

  • MVC — model, view, controller: most mobile applications follow this pattern. There is a model, there is a view, there is a controller. For example, playing a game: the game model is there — a database; who is a player, what is the score, everything is modeled. The view is what I am playing — I am playing with a bike, I am playing with a car. And the controller has all the power.
  • Publisher–subscriber: another pattern — producers publish events; consumers subscribe; the two never need to know each other directly.
  • Pipe and filter: another pattern — data flows through a chain of processing stages, each one transforming the stream.
  • Layered architecture style: an architecture style — systems organized into stacked layers, each with a defined role.
  • Broker architecture style: an architecture style — a central broker mediates communication between components.
  • Adapter pattern: when I want to send some data to another system, we need an adapter. Suppose I am sending an Excel file, but that other system cannot accept the Excel file — then I need a CSV file; use the adapter. This side may be something, the other side may be something else.

Patterns provide benefits that simplify the process — repeatability, structure, and shared vocabulary — and similarly, there are patterns available for data transformation: that is what we are going to study.

9.12.2 Medallion Architecture

Medallion architecture is a data design pattern used to logically organize data in a lakehouse, with the goal of incrementally and progressively improving the structure and quality of the data as it flows through each layer of the architecture — from bronze to silver to gold.

Q: What is the medallion architecture?

A: It is a data design pattern used to logically organize data in a lakehouse, with the goal of incrementally and progressively improving the structure and quality of the data as it flows through each layer — from bronze to silver to gold.

It is basically a component-based architecture: instead of taking everything into the target BI system, we have multiple levels, multiple layers. Each layer has one job, and quality improves step by step as data moves through.

  • Bronze — the landing zone for raw data. No schema needed. We ingest the raw data and put it there; you can use any technology for raw integration and ingestion, and you can use AI to stage everything. Nothing is filtered at the door — the raw data is preserved, which means nothing is ever lost.
  • Silver — filtered and cleaned. Correct documents, cleaned documents. Augmented means extra: you augment the data, add some more — beautification — for better visualization. Data should be visualizable and complete; sometimes raw data doesn't provide everything. When there are standards — for example, HIPAA standards in healthcare — if the data is not falling into that, the duty of the silver layer is to ensure that all the extra information is fitted in. Here we enforce a schema and evolve the schema as needed. Filtered only means we took only the data we need — like a data mart — not all the raw data from bronze; we take a segment of the data, and we can build multiple systems.
  • Gold — the deliverable. Aggregated, normalized, clean tables. Here you can build your CI/CD pipeline — continuous integration, continuous update — and from there you give it to your BI system, to a new system, maybe a .NET system, new products, new mobile applications, BI reports — Crystal Reports, Power BI, Tableau — or you run your machine learning to perform some pattern. Deliver continuously updated, clean data to downstream users.

Worked example — insurance adjudication (a student's real case): an insurance company organizes its data with the medallion pattern.

  • Bronze: all the raw data from different systems — certificates of coverage and all the coverage documents, all the CPT codes for insurance. Nothing processed, nothing lost.
  • Silver: filtered documents, corrected documents, cleaned documents — the working layer where standards are enforced.
  • Gold: combine everything into one aggregated table — the single fact base for adjudication.
  • Downstream: from the gold, many other accounts and systems — like healthcare, government programs — draw the data.

Final answer: raw → filtered/cleaned → aggregated, with downstream systems reading only the gold layer. Sense-check: "it is very structured — you know where to debug the stuff": when a number looks wrong, the layers tell you exactly which stage to inspect — bronze if the source is wrong, silver if the cleaning went wrong, gold if the aggregation went wrong.

The Oracle GoldenGate naming joke from the session: the gold layer — "that's why Oracle called this a Golden Gate, maybe." That led to the ColdFusion story: a product from the past that took HTML, CSS, and dynamic HTML, and with the click of a button generated nice pages — people fused things and came up with names. And the etymology: Oracle comes from the Sanskrit word Akashwani — a voice from above, from the divine — there is a story of a Rishi; it can carry a lot of data, because something comes from above with so much in it. (Two takeaway names to remember: Oracle GoldenGate is the data replication product, and the gold layer is the medallion deliverable.)

9.12.3 The DBT (ELT) Pattern

The DBT pattern is another layered data engineering pattern — again a type of medallion, layered architecture. Here we call the layers: staging, then an intermediate, then a data model (mart).

The DBT tool is available and it does ELT — extract, load, transform: during the transformation, we stage it, then we put it into the intermediate — which is like a silver data mart; we build multiple data marts. Staging is prior to the data warehouse. The flow: from landing we go to staging, then from intermediate we can go to the mart.

  • Staging layer — we have all the column-level transformations: type conversions, renaming, cleaning at the column level.
  • Intermediate layer — the aggregations, all the views and tables.
  • Data mart — the final layer, useful for your packs and dimensions and further reports.

You can use medallion architecture and the ELT DBT pattern together — combine them like a hybrid model:

Comparison — medallion and DBT mapped onto each other:

Medallion layer DBT layer Job
Bronze Staging Landing and column-level transformations
Silver Intermediate Aggregations, views, and tables
Gold Data mart Final, deliverable data for reports and models

One-line rule: bronze is basically the staging part, silver is nothing but the intermediate part, and the data mart is nothing but the gold — you can use it that way as well. The two patterns are the same ladder with different names, so the exam mapping is direct.

9.12.4 What to Check in Validation and Testing

For validation and testing we can validate manually, we can build our own data quality checks — what can go wrong with the data — and perform testing on whether the transformation logic worked. Why do we want to test? We want to make sure:

  • data is converted properly;
  • strings are manipulated properly;
  • date and time is transformed properly — is the reverse time zone transferred properly;
  • data is aggregated properly;
  • data is normalized properly;
  • data is standardized properly;
  • data is filtered correctly;
  • data enrichment is applied — lookup;
  • how we handle the null value;
  • how the data is being split;
  • how the data is merged;
  • error and outlier handling.

We check how the attribute is constructed, how the data is aggregated, how the data is discretized — that's where the binning technique comes into the picture — how we are splitting the data into multiple groups, how the data is generalized, how data is integrated, how data is normalized. Normalization examples: social security number, or the mobile number, or especially the patient ID, hospital ID, or clinical ID — that's why sometimes we use curated codes and data smoothing, and we remove the outliers. The test list is a checklist of everything that can go wrong in transformation — and every item on the seven-types list from Section 9.11 has a corresponding "was it done right?" check here.

9.12.5 Best Practices for Data Transformation

Q: What are the best practices for data transformation?

A: Document every rule with a transformation mapping sheet linking source fields, transformation logic, and target fields; automate validation with SQL scripts or Python tests; keep version control; and test the edge cases — missing data, outliers, and extreme values.

In detail:

  1. Document every rule. Maintain a clear transformation mapping sheet linking source fields, transformation logic, and target fields. Always have a checklist: what is the source field; what is the logic — we are converting from this to this, maybe we are increasing some value or decreasing some value; what is going to be the target field.
  2. Automate validation. Use SQL scripts, Python tests, or ETL tool validations for repetitive checks — repetitive tests — and test with a realistic volume; don't just do the normal data, test with realistic volume. A transformation that passes on a 100-row sample can collapse on a 100-million-row run.
  3. Version control. Keep everything properly — Git, SCCS, RCS, VCS, PVCS, ClearCase — use any version control system, so that every model, every version is checked in. When a transformation changes behavior, version control tells you what changed, who changed it, and how to go back.
  4. Test the edge cases. Include the missing data — don't underestimate — test outliers, extreme values. The boundary value analysis below is the systematic way to do this.

9.12.6 Boundary Value Analysis

In software testing there is a very nice technique called boundary value analysis (BVA) testing, and equivalence partitioning testing. The instructor was a tester and validation engineer at Honeywell Aerospace in 2010–2011, where boundary value testing was very, very important.

The idea behind BVA: bugs live at the edges. A condition like "age between 25 and 65" fails most often exactly at 25, 26, 64, 65, 24, and 66 — not at 40. Equivalence partitioning is the companion idea: group all inputs that the logic treats the same way into one "equivalence class," and test one representative from each class instead of every possible value.

Worked example — the doctors' age range (from the session): suppose we are working on a system for doctors, and the system should only allow doctors aged 25 to 65. The minimum age is 25; the maximum age is 65; anything below or above is not good. Boundary value analysis checks exactly these edges:

  • Step 1 — the boundary set: minimum = 25, maximum = 65. The valid range is [25, 65].
  • Step 2 — on-boundary tests (should pass): the boundary values themselves, 25 and 65.
  • Step 3 — just-inside tests (should pass): minimum plus one and maximum minus one — we check 26 and we check 64 — the system is passing.
  • Step 4 — just-outside tests (should fail): minimum minus one and maximum plus one — those should fail: 24 should fail, 66 should fail.
  • Step 5 — the verdict grid:
Input Expected result
24 fail (below minimum)
25 pass (on boundary)
26 pass (just inside)
64 pass (just inside)
65 pass (on boundary)
66 fail (above maximum)

Final answer: test 24 (fail), 25 (pass), 26 (pass), 64 (pass), 65 (pass), 66 (fail) — the six edge values instead of forty years of ages. Sense-check: if the system wrongly accepts 66 or wrongly rejects 25, BVA finds it immediately; testing "40, 41, 42" would never touch the edges where the bug lives. There is also a robust BVA variant that adds a second value beyond each boundary (23 and 67) for extra safety. The point of all of it: test the edge cases.

Real-world: boundary value testing was central to validation work at Honeywell Aerospace — aviation-grade systems cannot afford an off-by-one at the boundary of a safety condition.

9.12.7 What Comes Next

The next session will show a data transformation code — the instructor will generate some source data and run a data transformation code. There is also an insurance company exercise to prepare: what type of transformation would we do, and what could the data be? Think about it with the seven types of Section 9.11 in hand: cleaning (dirty claim fields), standardization (dates, units), enrichment (adding derived features), filtering (claims meeting criteria), aggregation (summaries by policy).

Exam note: it is fine to complete only 50–60% of the planned portion of a session — the important things need to be covered in detail; no rushing. For the comprehensive exam, the data profiling question (with drift, model drift, and data drift) and the transformation patterns (medallion and DBT) are the key things to have ready:

  • Medallion: bronze (raw) → silver (filtered, cleaned, schema) → gold (aggregated, normalized, clean deliverable).
  • DBT pattern: staging → intermediate → mart; hybrid mapping bronze = staging, silver = intermediate, gold = data mart.
  • BVA and equivalence partitioning: test the edges — 24/25/26 and 64/65/66 for a [25, 65] range.

Recap + bridge: Patterns make transformation repeatable and simple. The medallion architecture improves data quality layer by layer (bronze → silver → gold); the DBT pattern does the same under ELT names (staging → intermediate → mart), and the two map one-to-one. Validation checks every transformation type, best practices demand documentation, automation, version control, and edge-case testing — where BVA and equivalence partitioning do the systematic work. With integration (9.9), engineering (9.10), transformation (9.11), and patterns (9.12) in place, the lecture closes with the exam guidance and industry applications that follow.

Exam Guidance Summary

Everything below was stated explicitly in the session. Use this list as the final revision checklist before the comprehensive exam.

  • Data profiling question (stated explicitly as examinable): expect a question related to data profiling — making some decisions in drift, model drift, and data drift, and then the role of data profiling. Prepare the full chain: what profiling is, the quality dimensions, its role in ML data readiness, and how the drift decisions (data, model, concept) connect back to it.
  • Drift detection metrics: know the Population Stability Index (PSI) and its formula — observed minus expected times the natural log of observed over expected, summed — and KL divergence (relative entropy). PSI was flagged as "one of the very, very important indices." Be ready to interpret scores (low = stable, high = significant change) and to compute a small example by hand.
  • Data transformation patterns: medallion architecture (bronze, silver, gold) and the DBT (ELT) pattern (staging, intermediate, mart) — including the hybrid mapping where bronze = staging, silver = intermediate, gold = data mart.
  • Data transformation: the seven types of transformation (cleaning, standardization, summarization, enrichment, integration, normalization, filtering) and the process loop — discover, map, build rule, execute, validate, document, monitor, repeat. Remember the vocabulary correction: duplicates/nulls/typos belong to cleaning; units and date-time alignment belong to standardization.
  • Outliers: the three detection families (box plot with IQR fences, proximity with distance matrix and KNN, density-based), the worked numbers 50, 67, 90, 80, 55, 167, and the rule that outliers can be good or bad.
  • Leakage and drift concepts: the definition of data leakage (unintentional introduction of information), its three causes, and the difference between data drift, model drift, and concept drift (cholesterol example).
  • Next session: a data transformation code demonstration with generated source data, plus an insurance company exercise — think about what type of transformation we would do and what the data could be.
  • Pacing guidance: it is acceptable to complete only 50–60% of planned content; depth on important topics beats rushing.

Key Industry Applications

Where the lecture's concepts show up in the real world:

  • Population Stability Index — used by banks to monitor population stability between training and production data; the instructor taught it to banking professionals in Malaysia.
  • Generative AI adoption — organizations are adopting Gen AI tools for data pipelines and automating many data engineering tasks.
  • Amazon and Netflix — recommendation systems that suffer model drift and concept drift as user preferences change in production.
  • Mobile banking apps and Fitbit — third wave BI: self-service, customizable analytics available directly to customers.
  • Lorenzo — a healthcare integration system built with materialized views, replication logic, and stored procedures to unify pharmacy, lab, and patient management systems.
  • Oracle EHR — a modern healthcare transformation using change data capture (CDC), materialized views, and Lambda architecture, with FDA reporting and zero-compromise safety on missing data.
  • Insurance adjudication — bronze/silver/gold (medallion) architecture used for certificates of coverage, coverage documents, and CPT codes, with government programs drawing from the gold layer.
  • ETL tools — DataStage, Informatica, Oracle Warehouse Builder, ODI.
  • Execution engines — DBT and Apache Beam.
  • Explainable AI — SHAP and LIME packages for fairness in critical AI.
  • BI reporting — Crystal Reports, Power BI, Tableau.
  • Y2K — date and year handling at massive scale; one of the biggest challenging projects in banking.
  • Honeywell Aerospace — boundary value analysis used in validation engineering.
  • Agile at Cisco — Scrum, sprints, and backlogs as the practice behind "agility" for data teams.

DMML Lecture 9 notes · Data Integration and Data Transformation

Data Management for Machine Learning· postgraduate· 2026-08-07

Sections Breakdown

1Data Profiling and Data Quality Dimensions

Data profiling systematically examines a dataset before it enters a pipeline, using the CV analogy and a checklist of quality dimensions (timeliness, uniqueness, traceability, reliability, validity, completeness, accessibility, integrity, accuracy, consistency) plus extended dimensions (informative, coverage, real inputs, accurate, unbiased).

2Outlier Detection

Outliers are points that do not belong to the big bucket where most data sits; they can be good (new revenue behavior) or bad (fraud, errors). Detection methods: box plot with five-point summary and IQR fences, proximity-based with a distance matrix plus KNN, and density-based (local density / LOF); then exclude bad outliers or use models robust to them.

3Bias and Fairness

Bias is a systematic distortion entering data at collection, selection, labeling, or reporting; twelve bias types were read out (omitted variable, sponsorship, prejudice, value distortion, experimenter, labeling, reporting, automation, selection, group attribution, implicit, confirmation). Responsible AI demands fairness, antagonistic thinking with human in the loop, explainability (SHAP, LIME), and binning to handle missing, unexpected, and skewed feature values.

4Data Leakage

Data leakage (target leakage) is the unintentional introduction of information that should not have been available; it contaminates training data and inflates every validation metric, so the model looks better than it will ever be in production. Causes: the target being a function of a feature, a feature hiding the target, and a feature coming from the feature.

5Data Drift, Model Drift, and Concept Drift

Drift is movement away from a benchmark: data drift (skew between training and serving distributions, schema or distribution), model drift (weights/outputs go off, often caused by data drift), and concept drift (the input-output relationship changes, as with cholesterol weightage). Production data changes because of the dynamics of people and data generation; model decay speed varies; agility (Scrum, sprints) is the answer to static pipelines.

6Data Drift Detection Metrics

PSI (Population Stability Index) measures how much the distribution changes between a training dataset and a new dataset: sum of (observed - expected) times ln(observed/expected) over bins; high PSI means significant change, low PSI means stability. KL divergence (relative entropy) measures the difference between a probability distribution and a reference distribution: sum of P(x) ln(P(x)/Q(x)); it is asymmetric.

7ML Data Readiness and the Role of Data Profiling

ML data readiness is where data profiling comes in: systematically analyzing the dataset to evaluate its quality, providing insights into metadata, evaluating data integrity, and supporting data governance. Profiling is single-field (summary statistics, type, values, distribution) or multi-field (dependencies and keys); the comprehensive exam will include a data profiling question with drift decisions.

8The Leadership Story: Honesty and Continuous Effort

The king's final test: three contestants collect food in sacks; the decorator (25% food with dead leaves on top) dies, the fixer (50% rice mixed with contaminated food) dies of leakage-spread contamination, and the steady collector (about 30% honest food) survives and becomes king. Success is continuous effort, not one great push; the story maps onto data quality and leakage.

9Data Integration

Data integration combines various types and formats of data from many sources into a data lake or warehouse to provide a unified fact base; ingestion collects and transfers data to target storage while integration unifies disparate sources with transformation. Work is organized into bronze, silver, gold layers (gold = aggregated, normalized, clean tables); modern challenges include data explosion, streaming, and third-wave BI self-service.

10Data Engineering

Science supplies facts, rules, and findings (like Ohm's law); engineering applies them with a structured, disciplined methodology to make products. Data engineering means engineering the data: a data engineer knows the data's state like a doctor reads anatomy from a pulse, and develops, manages, and optimizes data pipelines systematically through the core steps from data generation to data monitoring and governance.

11Data Transformation

Data transformation converts raw, unstructured, inconsistent data into a clean usable format through seven types: cleaning, standardization, summarization, enrichment, integration, normalization, filtering. The process loop is discover, map, build rule, execute, validate and test, document and monitor, repeat. ETL transforms before loading; ELT after. War stories: Y2K dates, Lorenzo (materialized views + replication), Oracle EHR (CDC + Lambda architecture).

12Data Transformation Patterns

Patterns make transformation repeatable: the medallion architecture organizes a lakehouse into bronze (raw), silver (filtered/cleaned/schema), and gold (aggregated, normalized, clean deliverable); the DBT (ELT) pattern uses staging, intermediate, and data mart, mapping one-to-one onto bronze/silver/gold. Best practices: document rules, automate validation, version control, test edge cases with boundary value analysis and equivalence partitioning.

13Exam Guidance Summary

Comprehensive exam guidance from the session: a data profiling question with drift/model drift/data drift decisions; PSI formula and KL divergence; medallion and DBT patterns; seven transformation types and the process loop; next-session code demo and insurance exercise; pacing guidance.

14Key Industry Applications

Real-world applications of the lecture: PSI in banking (Malaysia), Gen AI adoption for pipelines, Amazon/Netflix recommendation drift, third wave BI (mobile banking, Fitbit), Lorenzo and Oracle EHR healthcare integration, insurance adjudication medallion layers, ETL tools, execution engines, explainable AI, BI reporting, Y2K, Honeywell BVA, agile at Cisco.

Postgraduate students in Machine Learning, Data Science, and Data Engineering

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Data Profiling and Data Quality Dimensions

Must-know: Profiling = systematically examining data before it enters a pipeline; check the ten quality dimensions; good data is not a result of the model itself (feedback loop); common data problems are noise, low predictive power, outliers, bias, leakage, outdated data.

⚠️ Top pitfall: Treating the dimension list as a formality instead of actually checking each one; ignoring traceability; forgetting that more data cannot fix low predictive power (underfitting).

Self-check: List the ten quality dimensions and give one worked integrity failure.

Connects to: Data Leakage (9.4), Data Drift, Model Drift, and Concept Drift (9.5)

Outlier Detection

Must-know: An outlier is data that does not belong to the big bucket. Three detection families: box plot (IQR fences: Q1 - 1.5*IQR, Q3 + 1.5*IQR), proximity (distance matrix + KNN, Euclidean vs Manhattan distance), density (LOF, local reachability density). Handle by excluding or using robust models.

\[d(\mathbf{x}, \mathbf{y}) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2}\]

⚠️ Top pitfall: Deleting good outliers without investigating; forgetting that the outlier label depends on the chosen distance metric.

Self-check: Among 50, 67, 90, 80, 55, 167, which is the outlier and why?

Connects to: Data Profiling and Data Quality Dimensions (9.1), Bias and Fairness (9.3)

Bias and Fairness

Must-know: Twelve bias types; bias is systematic not random; responsible AI parameters (validate outputs, verify facts, avoid blind trust, check citations, detect hallucinations, academic integrity); explainable AI via SHAP/LIME; binning for missing/skewed feature values.

⚠️ Top pitfall: Judging fairness by one metric or trusting the loss number alone — the loss hides bias that came from the data collection itself.

Self-check: How did the hyper-reactive toy poodle let confirmation bias enter the dog aggressiveness model?

Connects to: Data Profiling and Data Quality Dimensions (9.1), Data Leakage (9.4)

Data Leakage

Must-know: Leakage = unintentional introduction of information that should not have been available; consequence = overly optimistic expectations, inflated accuracy, production collapse; three causes: target a function of a feature, feature hiding the target, feature coming from the feature.

⚠️ Top pitfall: Scaling or imputing before the train/test split; leaving target-derived flags (e.g., chargeback_processed) in the feature table.

Self-check: Why did the fraud model's 96% validation accuracy collapse to 62% when the leaked feature was removed?

Connects to: Data Profiling and Data Quality Dimensions (9.1), Data Drift, Model Drift, and Concept Drift (9.5)

Data Drift, Model Drift, and Concept Drift

Must-know: Data drift = skew between training and serving data (schema skew vs distribution skew); model drift = weight computation/outputs off, often caused by data drift; concept drift = the interpretation of the relationship changes (cholesterol example); agility (Scrum, sprints, backlogs) is the answer.

⚠️ Top pitfall: Relying on a static data pipeline or static ML code when production data keeps changing; ignoring that thin, lean people can also have high cholesterol (stereotyped concepts).

Self-check: Which drift type is happening when cholesterol's risk weightage is lowered by new research?

Connects to: Data Drift Detection Metrics (9.6), Data Leakage (9.4)

Data Drift Detection Metrics

Must-know: PSI = sum over bins of (observed - expected) x ln(observed/expected); low PSI = stable (<0.1), high PSI = significant change (>0.25). KL divergence = relative entropy, sum of P(x) ln(P(x)/Q(x)), asymmetric. Banks use PSI for credit and risk populations.

\[\mathrm{PSI} = \sum_{i=1}^{n} \left( \mathrm{observed}_i - \mathrm{expected}_i \right) \times \ln\left( \frac{\mathrm{observed}_i}{\mathrm{expected}_i} \right)\]

⚠️ Top pitfall: Empty expected bins blow up the log ratio; binning scheme changes the PSI value; a stable distribution does not rule out concept drift.

Self-check: Compute PSI when expected shares are 30/50/20 and observed shares are 25/55/20.

Connects to: Data Drift, Model Drift, and Concept Drift (9.5), ML Data Readiness and the Role of Data Profiling (9.7)

ML Data Readiness and the Role of Data Profiling

Must-know: Data profiling is the process of analyzing the dataset systematically to evaluate its quality: metadata insights, integrity evaluation, governance support. Single-field profiling looks at summary statistics/type/value/distribution; multi-field looks at dependencies and keys. The comprehensive exam includes a data profiling question covering drift, model drift, data drift decisions and profiling's role.

⚠️ Top pitfall: Treating profiling as a formality instead of checking every quality dimension on actual data; profiling only single fields and missing broken keys and dependencies.

Self-check: What is the difference between single-field and multi-field profiling?

Connects to: Data Profiling and Data Quality Dimensions (9.1), Data Drift, Model Drift, and Concept Drift (9.5)

The Leadership Story: Honesty and Continuous Effort

Must-know: The story maps to data quality: contestant one = data that looks complete but is not; contestant two = data leakage (contamination cannot be cleaned away); contestant three = consistent honest effort that survives. Success is continuous, not one-time.

⚠️ Top pitfall: Believing shortcuts work: the cricket thing sometimes works but never stays; mixing good and bad data cannot be undone by cleaning.

Self-check: Which contestant represents data leakage, and why could washing not fix his bag?

Connects to: Data Leakage (9.4), Data Profiling and Data Quality Dimensions (9.1)

Data Integration

Must-know: Ingestion = collecting and transferring data from input sources to target storage; integration = unifying raw data from disparate sources with transformation into a warehouse or lake. Layers: bronze (raw), silver (integrated/clean), gold (aggregated, normalized, clean tables). Three waves of BI: DBA-only, bank administrator, self-service.

⚠️ Top pitfall: Confusing ingestion with integration; forgetting metadata and structure understanding before moving data.

Self-check: What does the gold layer consist of, and which tools are used for integration vs ingestion?

Connects to: Data Engineering (9.10), Data Transformation Patterns (9.12)

Data Engineering

Must-know: Science = facts/rules/findings (V = IR); engineering = structured disciplined methodology turning science into products/solutions. Core data engineering steps: generation, ingestion, storage, processing, pre-processing, transformation, management, governance, analytics, visualization, monitoring. Tools must provide architecture, self-service and operational integration, AI support, automated testing, orchestration, CI/CD, FinOps.

⚠️ Top pitfall: Confusing knowing the facts with being able to engineer the solution — application knowledge lives on the engineering side.

Self-check: What is the difference between science and engineering, and what are the core data engineering steps?

Connects to: Data Integration (9.9), Data Transformation (9.11)

Data Transformation

Must-know: Seven types of transformation: cleaning (duplicates, missing, typos, formats), standardization (units, date-time, naming conventions), summarization (aggregation), enrichment, integration, normalization, filtering. Loop: discover, map, build rule, execute, validate/test, document/monitor, repeat. ETL = transform before load; ELT = transform after load.

⚠️ Top pitfall: Calling date conversion 'cleaning' when it is standardization; forgetting row-count and schema validation after transformation; ambiguous date conventions (DDMMYY vs MMDDYY).

Self-check: What are the seven types of transformation, and when does transformation happen in ETL vs ELT?

Connects to: Data Transformation Patterns (9.12), Data Integration (9.9)

Data Transformation Patterns

Must-know: Medallion architecture: bronze (raw landing, no schema) -> silver (filtered, cleaned, schema enforced) -> gold (aggregated, normalized, clean tables with CI/CD). DBT pattern: staging -> intermediate -> data mart; hybrid: bronze=staging, silver=intermediate, gold=mart. BVA: for a [25,65] range test 24 fail, 25/26 pass, 64/65 pass, 66 fail.

⚠️ Top pitfall: Not testing edge cases (bugs live at boundaries); calling standardization 'cleaning'; testing only normal data instead of realistic volume.

Self-check: Which ages pass and fail in boundary value analysis for a doctor age range of 25 to 65?

Connects to: Data Transformation (9.11), Data Integration (9.9)

Exam Guidance Summary

Must-know: Comprehensive exam: data profiling question (drift, model drift, data drift decisions + role of profiling); PSI and KL divergence metrics; medallion and DBT transformation patterns; seven types of transformation and the process loop.

⚠️ Top pitfall: Rushing planned content; depth on the important topics (profiling, drift metrics, patterns) beats covering everything shallowly.

Self-check: What is stated explicitly as examinable for the comprehensive exam?

Connects to: ML Data Readiness and the Role of Data Profiling (9.7), Data Drift Detection Metrics (9.6), Data Transformation Patterns (9.12), Data Transformation (9.11)

Key Industry Applications

Must-know: Named applications: banks use PSI; Amazon/Netflix suffer drift; mobile banking and Fitbit are third wave BI; Lorenzo and Oracle EHR are healthcare integration war stories; insurance uses medallion layers; Honeywell used BVA; Cisco used Scrum.

Self-check: Which industry uses PSI to monitor population stability, and where was it taught?

Connects to: Data Drift Detection Metrics (9.6), Data Integration (9.9), Data Transformation (9.11), Data Transformation Patterns (9.12)

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Key

Select Provider & API Key
🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.