Skip to main content
Data Management for Machine Learning

The Machine Learning Lifecycle: From Business Understanding to Model Serving

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

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

  • Structured, semi-structured, and unstructured data classification — covered in Lecture 1 (Data Classification)
  • Data quality assessment and the garbage-in, garbage-out principle — covered in Lecture 1 (Data Quality Assessment)
  • ETL versus ELT pipelines — covered in Lecture 2 (Data Pipelines)
  • Data warehouse, data lake, and lakehouse storage — covered in Lecture 2 (Storage Architectures)
  • Data governance and DataOps — covered in Lecture 2 (Data Governance and the Data Management Framework)
  • Data cleaning, missing values, and imputation — covered in Lecture 3 (Data Cleaning and Handling Missing Data)
  • Feature engineering: binning, encoding, normalization, and derived attributes — covered in Lecture 4 (Feature Engineering Techniques)
  • Overfitting, best fit, and underfitting (the shirt analogy) — covered in Lecture 2 (ML and Data Management)
  • Framing the machine learning problem: business goals, costs, and KPIs — covered in Lecture 6 (Framing the Machine Learning Problem)
  • The 80–20 split and data drift — covered in Lecture 6 (The Data Level and When Pipelines Fail)

7.1 The CRISP-DM Lifecycle

Hook — why does every ML project need a lifecycle?

Why do so many machine learning projects fail? The usual answer is not "the model was wrong" — it is that the project was started in the wrong place: with a model, instead of with the business. CRISP-DM exists precisely to stop that mistake. It forces you to walk the whole path in order — business first, data second, model third — so that the model you finally build actually answers a real question.

CRISP-DM — the Cross-Industry Standard Process for Data Mining — is the de facto standard lifecycle for machine learning, data mining, and data management projects, and it is still used in modern projects. Every project of any of these kinds starts the same way: with business understanding. The traditional ML lifecycle you already know — business goal, problem framing, data processing, developing the model, evaluation, deployment, monitoring, and then the cycle continues — maps directly onto CRISP-DM's stages. The rule to keep in mind through all of it: a model is only effective if you have a good understanding of the business, a good understanding of the data, and good data preparation. Garbage in, garbage out.

Intuition — the cooking analogy

Think of CRISP-DM as cooking a meal for a guest. You first ask what the guest likes and dislikes (business understanding), then you check what is in the fridge and whether it is fresh (data understanding), then you wash, peel, and chop everything (data preparation), only then do you cook (modeling), taste and adjust the salt (evaluation), and finally serve the plate (deployment). If you skip the first three steps, no amount of cooking skill saves you — the meal still tastes wrong. That is exactly what "garbage in, garbage out" means. The analogy breaks in one place: cooking ends when the plate is served, but ML deployment begins a second lifecycle of monitoring, drift detection, and retraining.

7.1.1 Business Understanding

Before anything else, the business must be understood. Determine the objectives of the project, and assess the situation you are trying to evaluate: what is feasible, what are the risks, what contingencies exist, and what goal are you trying to achieve? Then separate two related goals — the data mining goal and the machine learning goal — and come up with a project plan for the project, following whatever method you choose, for example an agile approach.

To see why the two goals must be kept separate, take a churn-prediction project for a subscription service:

  • Business goal (what the company wants to happen): reduce customer loss by 15% within two quarters, measured by the subscription renewal rate.
  • Data mining goal (the measurable technical target that serves the business goal): build a model that predicts, for each customer, the probability of leaving next month, with at least 85% accuracy on a held-out test set.

The business goal is the why; the data mining goal is the how we will measure progress. A project whose only goal is "build a good model" has no success criterion — you cannot tell whether you succeeded until you know which business number the model is supposed to move.

7.1.2 Data Understanding

If you do not understand the data, you can do nothing with it. Data understanding has four activities, each with its own report:

  • Collect initial data — produces the initial data collection report.
  • Describe data — produces the data description report.
  • Explore data — produces the data exploration report.
  • Verify data quality — produces the data quality report.

Before going anywhere, you need to know how your data is dispersed: what is the lowest value, what is the middle one, what is the higher one, what is the mean value, what is the median value, what is the range of the data, what data types it has, and what the quality of the data is. Understanding data quality is the first and foremost step in any data management project.

These four reports are the deliverables of the stage, and each answers a different question. The initial data collection report answers "where did the data come from and what did we actually get?" — how many rows arrived, from which source systems, over which period. The data description report answers "what do the columns look like?" — data types, means, medians, minimums, maximums, and ranges, which is exactly the dispersion check listed above. The data exploration report answers "what patterns are hiding in the data?" — distributions, relationships between columns, and anything surprising. The data quality report answers "can we trust this data?" — missing values, duplicates, outliers, and inconsistencies. In short, data understanding is the look before you leap step: you cannot clean data well, or later build a model on it, if you never found out what it contains.

7.1.3 Data Preparation

Data preparation continues from data understanding and covers these activities:

  • Data set description.
  • Select data — with criteria for inclusion and exclusion.
  • Clean data — produces the data cleaning report.
  • Construct data — derive attributes, generate reports.
  • Integrate data — merge data.
  • Format data — produce reformatted data.

Four things are addressed here: data transformation, data mapping, data integration, and data construction with derived attributes. In industry, data understanding and data preparation are sometimes lumped together and called data cleaning or data pre-processing — different people call it different ways. Whatever the name, by the end of this stage the data must be completely ready before it is handed to modeling.

Worked example — deriving a car age attribute

The professor's practical example: a dataset of used cars contains the registration year (say, 2015) but not the car's age. Because buyers care about age — a 2015 car is much older than a 2022 car — the team derived a new attribute from the existing one:

  1. Construct data (derived attribute): compute \(\text{age} = \text{current year} - \text{registration year}\). For a car registered in 2015, evaluated in 2023, the derived attribute is \(\text{age} = 2023 - 2015 = 8\) years.
  2. Format data: reorder columns so that age sits next to the other car-condition features, and change the data type of the year column from text to integer so arithmetic works.
  3. Clean data: remove rows with impossible values (a registration year of 2099) and fix inconsistent formats ("2015" versus "15").
  4. Integrate data: merge the car-specification table with the sales table on the shared car_id column so each sale row carries its car's full history.

The final dataset now has a feature the model could never have discovered on its own. The sense-check: every derived value must pass the common-sense test — an 8-year-old car with 20,000 km on the odometer is believable, but an 8-year-old car with 5 km is a data error, not an insight.

7.1.4 Modeling

Modeling has six activities:

  • Select modeling technique.
  • Modeling assumptions.
  • Generic test design — the test design.
  • Build model — with parameter settings and a model description.
  • Assess model — the model assessment.
  • Revise parameter settings.

This is the main thing for the machine learning and data mining part of the project. The selection step is where you decide: for my problem, should I use linear regression, logistic regression, a decision tree, a random forest? What method, what algorithm, what technique will be useful for me? Then you state your assumptions, generate training and test data, and decide the parameters — for a neural network these include batch size settings and the learning rate. Normally in machine learning we talk about precision, accuracy, bias, and many other things we define. Then you assess the model and revise the settings. This core stage works only when the earlier stages worked — the model will be effective only with a good understanding of business, a good understanding of data, and good data preparation.

Notice the discipline built into the stage: you do not just "run an algorithm." You pick the technique with a reason (the data is tabular and small, so a gradient-boosted tree beats a deep network), you write down the assumptions you are making, you design the test before building the model (so you cannot tune toward the test), and you treat the parameter settings as something to revise. The assess — revise — rebuild loop is the modeler's real work: build, measure, adjust the batch size or learning rate, build again.

7.1.5 Evaluation

Evaluation results cover two things. First, assess the data mining results with respect to the business success criteria, and choose the approved models. Second, review the process that was done and determine the next step — a list of possible actions and decisions. In practice you may use a couple of techniques, and based on the results you select the model: this one is performing better, this is my approved model, I want to go with it. Then you review the process: anything else missed out? Could we freeze it? And what goes with the next stage?

This is the stage where the two goals from 7.1.1 finally meet. The data mining goal says the model reached 87% accuracy — good, but the business goal says customer loss must drop 15%, so the team must check whether that accuracy actually produces the promised business effect, and must review whether the whole project was run honestly: was the test data ever touched during training? Were the assumptions recorded in modeling actually true? Evaluation answers two different questions — "is the model good enough to approve?" and "did we do the project the right way?" — and both must be answered before the model is allowed to move on.

7.1.6 Deployment

Deployment is the final stage of the classic cycle:

  • Plan deployment — the deployment plan.
  • Plan monitoring and maintenance — the monitoring and maintenance plan.
  • Produce the final report — the final report and final presentation.
  • Review project experience documentation.

Once the code is done you deploy it — on AWS, on Google Cloud, on Azure, on a website, or on a mobile app, whatever you have built — and then you monitor and maintain it, produce the final report, and review the project experience. That final review is called the post-mortem analysis: how it all happened, what went well, what went wrong. Deployment is not the end; the machine learning cycle continues from there.

Assumptions and scope

CRISP-DM assumes you can reach the business stakeholders at the start (business understanding is only as good as the people you interview), and it assumes the business problem is genuinely expressible as a data problem. It breaks down when:

  • The business objective is vague or changes every week — the data mining goal keeps moving and the model never converges.
  • The data does not exist yet or is in such poor quality that preparation dominates the project budget.
  • The organization treats deployment as the finish line instead of the start of monitoring — the model rots in production without anyone noticing.

In all three cases the failure is not in the modeling stage; it is upstream. That is the whole point of a lifecycle: the earlier stages exist so these failures are caught before money is spent on modeling.

Pitfalls

  • Skipping business understanding. Teams that jump straight to Kaggle-style model building deliver a technically good model that solves a problem nobody asked about. The professor's rule: a model is only effective with a good understanding of the business.
  • Confusing the data mining goal with the business goal. "Build a churn model" is not a goal; "reduce customer loss by 15%" is. The model is the means, not the end.
  • Treating the reports as paperwork. The four data understanding reports are the only record the team has of what the data looked like before cleaning; when a later stage goes wrong, these reports are where you look first.
  • Believing deployment ends the work. CRISP-DM's monitoring and maintenance plan exists because production data drifts. A deployed model that is never monitored is a model that is silently degrading.

Recap and bridge

CRISP-DM gives every ML project the same six-stage spine — business understanding, data understanding, data preparation, modeling, evaluation, deployment — and the golden rule is that each stage only works if the earlier ones worked: understand the business, understand the data, prepare the data, and only then model. The next section looks at the one stage most teams rush — the deployment stage's post-mortem analysis — and at why writing one honestly is so hard.

Real-world connection: every major cloud platform ships tooling that mirrors these stages — AWS SageMaker, Google Vertex AI, and Azure Machine Learning each provide labeled phases for data preparation, training, evaluation, and deployment, and modern ML platforms such as MLflow and Kubeflow track the artifacts and parameters produced at each stage. Data engineers and ML engineers in industry effectively implement CRISP-DM whether or not they use the name; the lifecycle survives because the failure modes it prevents — starting with the wrong question, or shipping an unmonitored model — are exactly the failures that still sink projects today.

7.2 Post-Mortem Analysis and Unbiased Analytics

The deployment stage's post-mortem analysis is worth a story, because it shows what a post-mortem is for and how hard it can be to stay objective while writing one. After the Vietnam war — a small country that beat the American army through guerrilla tactics, then suffered a brutal return attack with massive civilian damage — the army chief assigned two experienced officers to fly out separately and write complete post-mortem reports of what had happened in the war. Both were skilled, experienced people. The same incident, the same war, the same caliber of person — and two opposite outcomes.

Hook — what is a post-mortem actually for?

A post-mortem is a review written after the event is over: what happened, what went well, what went wrong. It sounds like routine paperwork, but the story of the two officers shows that the person writing the report decides what the report contains — and that a post-mortem is only worth anything if its author stays objective. The same war, the same skill level, two officers, two completely different reports.

7.2.1 The Two Post-Mortem Reports

The first officer started walking the ground and looking at the people. He saw children crying without a father or mother, mothers who lost their children, people who lost eyes, ears, hands. He could not control his emotion; he felt so much empathy and pity that he could not digest it. In his letter he realized that when people speak in anger they do not know what they say — during the war nobody cared about anything else. He wrote that he could not tolerate what he had been part of, called it a sin, and committed suicide on the spot, sending the letter back with the pilot.

The second officer also felt the pity, but he moved in the opposite direction. He walked among the people and talked to them, pacified them, gave them what he had — milk and biscuits for a hungry child — and arranged help through the Red Cross. And he documented everything: he took pictures and videos, recorded audio, captured every scene — a mother who lost a son, a son who lost a mother, people missing limbs — and he measured the damages. Back home he submitted a two-page report of the damages caused and how many people were killed and wounded. Right after that he handed in a second letter: he was resigning his position, no reason given. On his way home he was walking, and his son asked why there was no jeep. He answered: see this person, he lost his father; see this boy, he does not even have a leg; you have two legs — today we walk to the park. He started counseling his own family, then his neighbors, reframing every small complaint — a wife complaining her husband snores, people unhappy with their noses or eyes — against the suffering he had documented. He became a well-known psychology consultant.

The two reports differ in exactly the way that matters for analytics. The first officer's report was a record of his emotion — he could not separate what he saw from how it made him feel, and the report became a confession rather than an account. The second officer's report was a record of evidence — photographs, audio, measurements, counts of people killed and wounded. Both men felt the same pity; only one of them kept the pity out of the report. That is the entire difference between a post-mortem that informs and a post-mortem that only expresses.

7.2.2 What the Story Teaches About Analytics

Two lessons come out of the story. First, the coin always has two sides — in life you always have two options, and in a tough situation you should not get disappointed; always look for alternatives. Second, the evidence the second officer brought back — the videos, the photos, the measurements — is what let people finally understand how brutal the war had been. That is what good analytics does: sometimes you find findings you did not expect, and the evidence carries the truth. But for that to work, you have to be unbiased and agnostic — tool agnostic and model agnostic. A good analyst stays neutral, like a fair judge, and lets the data speak even when the result is inconvenient. If you come into the analysis already decided, the post-mortem is worthless.

Lesson 1 — always look for alternatives

Same war, same skill level, opposite outcomes: one officer destroyed by the experience, the other turned it into a life of helping people. The professor's moral is that in any tough situation there are always at least two options, and the second option only becomes visible if you refuse to stop looking. For a data scientist this is practical advice: when a model fails, the first reaction ("the data is bad") is never the only option — the alternative list includes a different algorithm, a different feature set, a different target definition, and a different way of measuring error. Disappointment closes the list; discipline keeps it open.

The bias trap — analytics must be unbiased and agnostic

The first officer decided what the war meant before he finished looking; the report then confirmed what he already believed. That is the exact failure mode the professor warns against in analytics: coming into the analysis already decided. Concretely:

  • Tool agnostic means you do not decide the answer because of the tool — you do not force a deep neural network onto a problem just because you know TensorFlow, or refuse a simpler decision tree because it is "too basic." The tool must fit the evidence, not the other way around.
  • Model agnostic means you do not fall in love with one model family. If the data says logistic regression beats the random forest on your metric, you report that, even if you spent two weeks on the forest.
  • A fair judge listens to both sides before ruling. An analyst who already wants the result — a churn model that blames a certain customer group, a marketing report that makes the campaign look good — will find evidence for that result no matter what the data actually shows.

The sign that you are doing it wrong: your conclusions never surprise you. A post-mortem (or any analysis) that only confirms what you already believed is worthless, because the surprise is where the learning lives.

Recap and bridge

A post-mortem is the deployment stage's final review — what happened, what went well, what went wrong — and its value depends entirely on the author's objectivity: evidence, not emotion; unbiased and tool-agnostic, like a fair judge. That discipline of neutral measurement is carried directly into the next topic: framing the ML problem itself, where the confusion matrix gives us a neutral vocabulary for counting what the model gets right and wrong.

Real-world connection: the same discipline is institutionalized in modern engineering practice as the blameless post-mortem — Google's Site Reliability Engineering approach and similar incident-review culture at cloud providers require the review to focus on what the system did and what evidence exists, never on blaming the person who was on call. Modern ML platforms carry the idea further with automated lineage tracking: the model registry records exactly which data, code, and parameters produced a model, so a later "post-mortem" of a bad model in production can be conducted on reproducible evidence instead of memory and emotion.

7.3 Problem Framing, Confusion Matrix, and Error Costs

Goals have to be identified before a machine learning project starts. Part of that is evaluating the cost of data acquisition — how much it costs to get the data — plus the cost of training, the cost of inference, and the answer to this question: what happens if I make a wrong prediction?

Hook — is a wrong prediction free?

The professor's framing question: what does it cost your business if the model predicts wrong? Most project plans budget for data and compute but never for errors. A wrong prediction is not a free event — and the confusion matrix is the vocabulary we use to price the four different ways a model can be wrong.

7.3.1 Goals, Costs, and Problem Framing

In problem framing you need to find the criteria: what is the criterion that makes a successful project? What is observable? What are all the quantities you can measure? And you must check with the business stakeholders: what is the input, what is the output we are getting, and are we getting the right performance?

A wrong prediction is not a free event. If a machine learning code predicts the gold price wrong, or predicts a wrong material composition and the production line produces something wrong, people who invested in tools and equipment lose a lot of money — budgets and sizing issues cause serious problems and headaches. So part of framing the problem is deciding how you will handle the errors.

Problem framing has four concrete questions that must be answered in writing before any modeling starts:

  1. What is the success criterion? Which number, measured how, tells us the project worked? Without a criterion, the project can never "succeed" — it can only be declared finished.
  2. What is observable? Which quantities can we actually measure in the business? The churn model can observe past subscriptions and past exits; it cannot observe customer intent directly.
  3. What are the costs? Data acquisition (buying data or building pipelines to collect it), training (compute, people, time), inference (running the model on every prediction — especially when predictions happen thousands of times per second), and error (what a wrong prediction costs).
  4. What is the input and output contract? Confirm with the business stakeholders exactly what goes into the model and what comes out, and how performance will be judged — "are we getting the right performance?" asked before, not after, the project runs.

The gold-price example shows why error cost belongs in this list: a model that predicts tomorrow's gold price and is wrong by a few dollars can wipe out positions held by people who trusted it, and a manufacturing model that predicts a wrong material composition sends a production line making parts that must be scrapped. Budgets and sizing issues cause serious problems and headaches — the framing stage is where those headaches are either planned for or ignored.

7.3.2 Confusion Matrix and Error Types

You have all studied the confusion matrix, so this is a review, and it is the vocabulary for error costs. The professor's example: he plays a doctor, and predicts that a person does not have Corona, while the machine learning program predicts that he does have Corona. The actual result is negative, the predicted result is positive — the machine got it wrong. Four outcomes are possible when we line up actual versus predicted:

Predicted positive Predicted negative
Actually positive True positive (correct) False negative (type 2 error)
Actually negative False positive (type 1 error) True negative (correct)

When actual positive and predicted positive agree, that is a true positive — no problem. When actual negative and predicted negative agree, that is a true negative — fine. When you predicted positive but the actual is negative, that is a false positive. When you predicted negative but the actual is positive, that is a false negative. The professor labels false positives as type 1 errors and false negatives as type 2 errors, and the whole point of evaluation is to reduce the false predictions — both the type 1 error and the type 2 error.

Worked example — the Corona diagnosis

The professor plays the doctor. The machine learning program looks at the evidence for one person and predicts: positive — this person has Corona. The true state of the world is different: the person does not have Corona — the actual result is negative.

  • Predicted = positive, Actual = negative → false positivetype 1 error.
  • In the table: row "Actually negative" column "Predicted positive" — the cell that means the model cried wolf.

The sense-check: every prediction lands in exactly one of the four cells, because each prediction pairs one predicted value with one actual value. If the model had instead predicted negative while the person actually had Corona, it would have been a false negative (type 2 error) — the dangerous opposite mistake, where a sick person is sent home.

Assumptions and scope

The confusion matrix assumes a binary classification problem with a known true label. It applies when:

  • The task is classification (yes/no, positive/negative), not regression — you would not use it to score a price-prediction model.
  • A ground-truth label exists for evaluation, which is why labeling quality (7.4) matters: a confusion matrix over bad labels is a lie.
  • You care about both error directions. When the two error types have different costs, the confusion matrix alone is not enough — you must weight the cells by their costs.

It breaks when the classes are highly imbalanced (99% negative, 1% positive: a model that always says "negative" scores 99% accuracy yet is useless) — that is when precision, recall, and the F1 score, which are all derived from the four cells, become the real metrics.

7.3.3 Qualitative vs Quantitative Metrics

There are always two kinds of parameters to keep in mind: qualitative parameters and quantitative parameters. Saying a teacher is nice, jovial, and good at teaching is qualitative — it does not substantiate anything. Saying the teacher was on time for seven out of seven sessions, that the class of thirty students gets good results, that the CGPA numbers and pass counts are good — those are all quantitative metrics. When you frame a machine learning problem, you need observable, quantifiable performance metrics — accuracy, how accurately we are predicting — not impressions. That is why the success criteria for the project have to be stated in measurable terms.

Dimension Qualitative parameter Quantitative parameter
What it is A judgment or impression in words A number from measurement
Example from class "The teacher is nice, jovial, and good at teaching" "On time for 7 of 7 sessions"; "30 students, CGPA and pass counts"
Can it be verified? No — it does not substantiate anything Yes — anyone can recount and check
Role in ML projects Never acceptable as a success criterion Required — accuracy, error counts, cost

The lesson for framing: a project's success criteria must be quantitative. "The model should work well" is qualitative and unverifiable. "The model should reach at least 85% accuracy on the held-out test set, and reduce false positives by half" is quantitative — it is observable, measurable, and checkable by an independent reviewer, which is exactly the fair-judge discipline from the post-mortem section.

Recap and bridge

Problem framing fixes the success criterion and the cost of being wrong; the confusion matrix then gives us the four-cell vocabulary (true positive, false negative/type 2, false positive/type 1, true negative) for counting and pricing those errors; and quantitative metrics — never impressions — are what the success criteria must be built from. With the problem framed, the next section moves into the platform work: storing features, registering models, and keeping a deployed model healthy through the drift feedback loop.

Real-world connection: error costs are why medical screening (Corona tests, cancer scans) weights the four cells by lives, while fraud detection weights them by money — a bank losing a genuine transaction (false negative) costs the transaction's value, while a false positive costs a customer relationship. Credit scoring, insurance pricing, and algorithmic trading all carry explicit cost matrices over the confusion matrix cells; modern ML platforms expose this as "business metrics" that convert raw counts into the dollars the business actually cares about.

7.4 Feature Stores, Model Registry, and the Drift Feedback Loop

Once the data is prepared, the platform work begins. Everything that happens to the data — data processing, data pre-processing, data engineering, data acquisition, data collection, data staging — whatever you want to call it, falls under one category: process data. Then, with the data ready, the features are stored, the model is trained and tuned and evaluated, and the deployed model is monitored and kept healthy.

Hook — where do features live between training and serving?

A model trained yesterday needs the same features at serving time tomorrow. If the training code and the serving code each recompute features their own way, the model quietly degrades. Feature stores exist to close exactly that gap: one place where features are stored, versioned, and served to both sides.

7.4.1 From Data to Features: Online and Offline Feature Stores

After the data is pre-processed and engineered, the right next step is to store the features — and sometimes you do it both online and offline.

Q: After the data is pre-processed and engineered, what is the right next step? A: Store the features — online as well as offline. Then comes the blue color: train, tune, evaluate. After we have the features, we check whether each feature is useful — we find the correlation between different features to confirm that they add value, and whether we can drop the features. Then we evaluate, deploy, and start building the model for deployment.

The online feature store offers low-latency retrieval, which is ideal for real-time inference. The offline store is used for duplication and deduplication purposes. When the model is deployed and an application starts giving data, you monitor it, check it, and store the artifacts — data, code, and model. The model is registered, the data is registered, and catalogs are maintained.

Dimension Online feature store Offline feature store
Purpose Serve features to a live model making real-time predictions Supply features to training, evaluation, and batch jobs
Retrieval speed Low latency — milliseconds, because a user is waiting High throughput — speed matters less than volume
Typical storage Fast key-value or in-memory systems Data lake or warehouse tables, Parquet files
Real-world use Recommendation at request time, fraud scoring per transaction Training runs, backtesting, deduplication, audits
Why the professor stores both Real-time inference needs immediate values Training needs the full history; offline copy supports duplication and deduplication checks

The check-before-train step deserves emphasis: after storing the features, you examine the correlation between features before building the model. Two highly correlated features (for example, years as customer and total months billed) carry largely the same information; keeping both inflates the model without adding insight. The correlation check is the practical version of the feature-selection exercise in section 7.6.

7.4.2 Saving and Versioning Models: The Model Repository

A trained model itself can be saved to disk and reused later, and there are two standard ways to do it.

Q: How do you create a model repository? Could we collect the model itself — the weights and other parameters — along with the accuracy and statistics that tell us how good the model was, put that metadata in a flat file or registry, and store it with a version like 1.0? A: Two tools save the model: pickle and joblib. With pickle you open a file in write-binary mode, dump the trained model into it, and the model is saved as model.pkl. Later you load that pickle and reuse the model — for example to predict house prices for a new value like 5000 square feet. Joblib's dump does the same job. You can also put the model folder in GitHub with a README describing the parameters: one person saves it as version 1.0, the next person checks it out, makes changes, and saves it as 1.2. Both the machine learning serialization method and the version control method work together.

So the model repository combines serialization with version control. The professor's tip was a versioning scheme: name the first registered model 1.0; when someone else checks out, updates the weights for the new data that comes from different sources, and checks back in, that becomes 1.2.

Worked example — pickle and joblib in action

Suppose a house-price model was trained with linear regression. Saving it with pickle is three lines:

  1. with open('model.pkl', 'wb') as f: pickle.dump(model, f) — open the file in write-binary mode and dump the trained model object into it. The file model.pkl now holds the whole trained model: the learned weights, the intercept, the feature names.
  2. Later, in a new session: with open('model.pkl', 'rb') as f: model = pickle.load(f) — load the pickle back into memory. The model is ready to predict without any retraining.
  3. Use it: model.predict([[5000]]) — the professor's example, predicting the house price for a 5000-square-foot house from the saved model.

Joblib (joblib.dump(model, 'model.pkl') / joblib.load('model.pkl')) does the same job, and is often faster for models with large NumPy arrays inside.

The versioning layer sits on top: the same folder goes into GitHub with a README that lists the parameters and the accuracy. Version 1.0 is the first registered model. A colleague checks it out, retrains the weights on newer data from different sources, verifies the accuracy, and checks in the result as version 1.2. Both layers work together: serialization captures the model bytes; version control captures the history.

The sense-check: model.pkl is only useful if it can be loaded — a pickle that errors on load, or a version folder without a README, is a model that exists but cannot be trusted or reused. That is why the metadata (parameters, accuracy, statistics) matters as much as the bytes.

7.4.3 Model Registry and Lineage

The model registry is a repository for storing ML model artifacts, including the trained model and related metadata such as data, code, and model. It enables the tracking of the lineage of ML models, because it can act as a version control system. Most people in the room already know version control: the history runs from SCCS, VCS, RCS, through ClearCase, to GitHub. We check in, we check out, check in, check out, and we keep a proper code base for normal non-ML code. When it comes to ML, we can use a version control system for the models too.

The lineage tracker goes further: it enables a recreation of the ML environment at a specific point in time. That is like point-in-time recovery in databases — in Oracle there is point-in-time recovery and rollback, with RPO-type recovery, so you can roll back to the version you want. For change auditing we use this: you can re-create what environment and what resources existed at the time you want to go back to.

A model registry, then, answers four questions about any model in production:

  1. What is this model? — the artifact itself, the algorithm, the version number.
  2. What produced it? — which training run, which data snapshot, which code commit.
  3. How good was it? — the recorded accuracy and statistics attached at registration time.
  4. What did it replace? — the version history, check in / check out, 1.0 to 1.2 to 2.0.

The version-control lineage of the field runs from SCCS (the earliest source control system) and RCS through ClearCase to GitHub — the same check-in/check-out discipline applied to ordinary code is applied to models. The lineage tracker is the stronger cousin: point-in-time recovery in Oracle databases can restore the database to any chosen moment; the ML lineage tracker can re-create the whole environment — data, code, model version, resources — as it existed at any recorded point, which is what makes change auditing and rollback possible for ML systems.

7.4.4 The Model Drift Feedback Loop

The model drift feedback loop informs the iterative data preparation phase, based on the evaluation of the model during the production deployment phase. What happens is that the model drifts: we keep iterating — this is not good, let me prepare the data again, let me do it again — and we do not allow the model to be considered ready until active learning has done its work. We have an alarm manager to monitor the models; any model that is not giving the proper targets can be flagged, and retraining can happen. Retraining can be scheduled — the model runs and retrains at a certain time. And because data changes, the model keeps learning and relearning: learn, relearn, learn and relearn.

Pitfalls in the loop

  • Ignoring drift until it hurts. The model drifts slowly: customer behavior changes, and the model's predictions slowly stop matching reality. Without the alarm manager watching, nobody notices until the business metric drops. Drift detection — comparing the incoming data distribution to the training distribution — is the early-warning system.
  • Retraining without re-evaluating. Retraining on newer data is not automatically an improvement. The loop only works when the retrained model is evaluated again before it is allowed to replace the old one; otherwise you can deploy a worse model.
  • Confusing the loop with one-time tuning. The professor's phrase — learn, relearn, learn and relearn — is the point: the loop is continuous. A team that treats hyperparameter tuning as a one-week task at the end of development has missed the mechanism that keeps the deployed model healthy.

Recap and bridge

After pre-processing, features are stored in online and offline feature stores; models are saved with pickle or joblib and versioned like 1.0 to 1.2 in a model registry that also tracks lineage; and the drift feedback loop — alarm manager flags a drifting model, retraining is scheduled, the model relearns — keeps the deployed model healthy. That loop is a natural bridge to the next topic: the pre-processing and sampling work that feeds the whole cycle in the first place.

Real-world connection: feature stores such as Feast, Tecton, and AWS SageMaker Feature Store, and model registries such as MLflow Model Registry and Vertex AI Model Registry, are the production products of exactly these concepts — they store features online and offline, version models, and record lineage so an audit can reproduce which data and code produced which model. The drift feedback loop is institutionalized in continuous training pipelines (for example, scheduled Airflow or Vertex Pipelines jobs that retrain nightly and gate deployment on evaluation), and drift monitoring tools quantify distribution change with metrics such as PSI and KL divergence, exactly the "alarm manager" role from the lecture.

7.5 Data Pre-processing and Sampling

This section reviews the data pre-processing toolkit. In the data pre-processing stage we clean the data, remove the outliers, partition the data into training and test data, scale the data, normalize it, standardize it, balance it so it is unbiased, and augment it — whenever you want to expand something, you can expand it. We have already studied feature engineering: feature selection, feature transformation, encoding, binning.

Hook — the 70% of ML work

The professor's earlier point returns: pre-processing is where most of the real work in a data project happens, because models only learn what the data teaches them. This section is the toolkit review — cleaning, imputation, sampling, partitioning, scaling, and normalization — and it ends with the two scaling formulas that every ML student must be able to write from memory.

7.5.1 Cleaning, Imputation, and the Pre-processing Toolkit

Q: What is data imputation? A: Replacing data — sometimes missing data will be replaced with the mean or some value.

Imputation is the standard answer to missing values: fill them with the mean or another chosen value. Alongside imputation, the cleaning toolkit removes outliers and removes duplicates, and then you partition the data. Data collection matters too: data can be time series data, it can come from sensors, from IoT, from social media, from multiple sources. Data ingestion means you capture the data and store it on storage media — for example, a smart refrigerator or a smart device connected by Bluetooth or Wi-Fi collects readings and pushes them to a disk, or the data is pushed directly through a streaming method. Then come the data technologies already seen: ETL and ELT pipelines that extract from Oracle, SQL Server, MongoDB, or Excel, then the data catalog, then the data lake, then EDA.

The new mantra in industry is no-code and low-code platforms: within fifteen minutes you can build an ML pipeline — for example, by giving a proper prompt to an AI assistant you can build a nice data pipeline. These automation platforms offer visual capabilities that improve productivity and reduce cost, and they are used together with generative AI code tools.

The toolkit, in the order a real project uses it:

  1. Clean — fix or drop corrupt rows, correct inconsistent formats.
  2. Impute — replace missing values with the mean, the median, a constant, or a model-based estimate. A column of monthly charges with 5% of rows missing gets its missing cells filled before training.
  3. Remove outliers — drop or cap extreme values that would distort the model.
  4. Remove duplicates — delete repeated rows; duplicates are the classic channel for data leakage (see 7.5.3).
  5. Partition — split into train, validate, and test.
  6. Scale and normalize — z-score or min-max (see 7.5.4).
  7. Balance and augment — fix skewed classes and expand the data.

An imputation example with real numbers: a column holds monthly charges in rupees, and the column mean is 1200. The missing 5% of cells are filled with 1200. The choice of filler matters — filling with the mean preserves the column's average but shrinks its variance, so it is a trade-off, not a free fix. That is why the professor's answer says "the mean or some value": the right filler depends on the column's distribution and the model that will consume it.

7.5.2 Sampling: The Shirt Story

Sampling was discussed in the previous session with a shirt story. At the age of five, the professor's son could wear his father's shirt — it did not fit, it was overfitting. Now the son and father are almost the same size, so the shirt fits well — best fit. And if the father tried to wear his son's shirt, that would be underfitting. The point: you need to choose the sample correctly, and the fit of your sample to the population decides whether your model overfits or underfits. Data sampling is the key. There are different types of sampling techniques, and choosing the right strategy for your machine learning work is a question worth your time — you can use an AI assistant for ideas, but you should be able to argue for the strategy yourself.

The shirt story, extended

The professor's son at age five could technically get into his father's shirt — but it hung off him and taught him nothing about fit. That is overfitting: the model "fits" the training data so completely (like the shirt swallows the five-year-old) that it fails on anything new. Now the son and father are almost the same size — the shirt fits well, the best fit, the model generalizes. And the father squeezing into his son's shirt is underfitting: the garment is too small to describe the person, just as an oversimplified model cannot capture the real pattern in the data. Where the analogy breaks: shirts are fixed garments, while a sample can be enlarged — underfitting is often fixable by adding data or model capacity, which no shirt can do.

The practical message: the fit between your sample and the population decides overfit or underfit. A sample that does not represent the population — only churned customers, say, when the population is mostly loyal ones — guarantees a model that memorizes or misses instead of generalizing.

Q: How do you choose a sample for your problem — for customer churn prediction or any problem? What would be the sampling strategy? A: Stratified sampling — sampling based on the strata — is the first answer, and it is a good one. Random sampling is the default option. Any other thoughts are welcome; the choice depends on the data.

Two sampling strategies, and when each is the right tool:

  • Random sampling (the default). Every row has an equal chance of entering the sample. Simple, unbiased in expectation, and fine when the data is large and fairly balanced.
  • Stratified sampling (the careful choice). You split the population into strata (groups) — for churn, the strata might be "will churn" versus "will stay" — and sample from each stratum so that the sample mirrors the population's proportions. If 20% of customers churn, a stratified sample keeps roughly 20% churned rows in the training set; a random sample of a small dataset could accidentally draw 5% or 40%.

For churn prediction specifically, stratified sampling matters because churn is usually rare: a random sample can end up with so few churned examples that the model never learns to see churners. Stratified sampling guarantees the rare class appears in proportion. The professor's final note is a fair-judge reminder: you can ask an AI assistant for ideas, but you must be able to argue for your strategy yourself.

7.5.3 Train, Validate, Test Partitioning and Data Leakage

Why partition at all?

Q: Why do we partition the data into train, validate, and test sets? A: The partition blocks ML models from overfitting and lets us evaluate the trained model accurately: randomly split data into train, validate, and test sets. Data leakage can happen when information from the holdout test data set leaks into the training data. One way to avoid data leakage is to remove the duplicates before splitting the data.

Common split ratios are 60-40-20, 60-20-20, 80-20, 80-10-10, or 90-10 — whatever you choose, before you split you must make sure the data conforms and there are no duplicates. That is very, very important: duplicates that appear in both the training side and the holdout side are the classic channel for leakage.

Worked example — an 80-10-10 split and the leakage channel

Start with 10,000 rows of customer data. With an 80-10-10 split:

  • Train gets 8,000 rows — the model learns from these.
  • Validate gets 1,000 rows — the model's hyperparameters are tuned against these.
  • Test (holdout) gets 1,000 rows — this set measures the final model, and is never touched during training or tuning.

Now suppose 200 rows are exact duplicates of one another. If a duplicated row lands in train (say it appears 3 times there) and once in the holdout test set, the model saw that exact row during training. Its "test" performance on that row is not a test at all — it is a memory. That is data leakage: information from the holdout set leaks into training. Because duplicates inflate the training data's apparent diversity and let the model memorize instead of generalize, the professor's rule is to remove duplicates before splitting. The sense-check: after any split, verify that no row in test also exists in train — the classic one-line sanity check in industry is a join of the two sets on all columns and a count of zero matches.

The three sets each have a different job: the train set teaches the model; the validate set is the tuning judge (it is used repeatedly while choosing hyperparameters, so it also gradually "leaks" — which is why it must never be used for the final score); the test set is the final, untouched judge that gives the honest accuracy number. A split ratio with only two numbers, like 80-20 or 90-10, is a train/test split that uses cross-validation (section 7.7.4) for the validation role instead.

7.5.4 Scaling and Normalization

To scale the data we use z-score normalization, min-max normalization, and other encoding techniques. Both formulas below are the standard forms used across ML practice: z-score normalization maps each value to how many standard deviations it sits from the mean, and min-max normalization squeezes the column into a fixed range.

\[ z = \frac{x - \mu}{\sigma} \]

Here \(x\) is an original value, \(\mu\) is the mean of the column, \(\sigma\) is the standard deviation, and \(z\) is the scaled value — it tells you how many standard deviations the value sits from the mean.

\[ x' = \frac{x - \min(x)}{\max(x) - \min(x)} \]

Here \(\min(x)\) and \(\max(x)\) are the smallest and largest values in the column, and \(x'\) is the rescaled value, squeezed into the unit interval \([0, 1]\).

Worked example — z-score normalization

A column of exam scores: 60, 70, 80, 90. The mean is \(\mu = 75\) and the standard deviation is \(\sigma = \sqrt{125} \approx 11.18\) (variance \(\frac{15^2+5^2+5^2+15^2}{4} = 125\)).

  • For \(x = 60\): \(z = \frac{60 - 75}{11.18} \approx -1.34\) — 1.34 standard deviations below the mean.
  • For \(x = 90\): \(z = \frac{90 - 75}{11.18} \approx 1.34\) — 1.34 standard deviations above the mean.

The transformed column has mean 0 and standard deviation 1, regardless of the original units (rupees, feet, or scores). The sense-check: the value exactly at the mean maps to \(z = 0\), values above the mean to positive \(z\), and the transformed column's average is 0.

Worked example — min-max normalization

The same column, 60, 70, 80, 90, has \(\min(x) = 60\) and \(\max(x) = 90\), a range of 30.

  • For \(x = 60\): \(x' = \frac{60 - 60}{90 - 60} = \frac{0}{30} = 0\) — the smallest value maps to the bottom of the range.
  • For \(x = 70\): \(x' = \frac{70 - 60}{90 - 60} = \frac{10}{30} \approx 0.33\).
  • For \(x = 80\): \(x' = \frac{20}{30} \approx 0.67\).
  • For \(x = 90\): \(x' = \frac{30}{30} = 1\) — the largest value maps to the top.

The transformed column is squeezed into \([0, 1]\). The sense-check: no output can fall outside \([0, 1]\) because the numerator is always between 0 and the denominator — unless a future value arrives that is larger than any training value, in which case \(x' > 1\), which is why the training min and max must be stored and reused at serving time.

Assumptions and scope

  • Both formulas assume the column's mean and spread (or min and max) are computed on the training data only — then the same \(\mu, \sigma\) (or \(\min, \max\)) are applied to validation, test, and future live data. Computing them from the whole dataset, test set included, is itself a form of leakage: the test values influence the transform and inflate the reported accuracy.
  • z-score assumes the data is roughly bell-shaped and symmetric. Heavy outliers drag \(\mu\) and \(\sigma\) far from the bulk of the data, compressing normal values into a tiny band of \(z\)-scores.
  • min-max is fragile to outliers. One extreme value stretches the range so that most points cluster near one end. When outliers exist, clipping or robust scaling on percentiles is preferred.
  • Why scale at all? Models that use distance or gradients — k-nearest neighbours, SVM, neural networks, PCA — treat feature units as comparable; a salary column in rupees dominates a 0–1 rating column otherwise. Tree models (decision trees, random forests, gradient boosting) are invariant to monotone scaling and do not need it.

On the imbalance side, when classes are skewed you can add bias to the algorithm, augment the data, or synthesize more extra samples to get multiple insights; you can also use the standard techniques that regularize and reduce overfitting. Three remedies for a skewed target class: add class weights (bias the algorithm so rare classes are punished more when missed), augment the data (create realistic new examples of the rare class), and synthesize samples (for example SMOTE-style interpolation between rare-class neighbors). These run alongside the standard regularization techniques — L1/L2 penalties, dropout, early stopping — that reduce overfitting when the model has too much capacity for the data.

7.5.5 Feature Engineering and Dimensionality Reduction

Feature engineering is all about selecting the feature, transforming the feature, creating new features, doing the encoding, doing the binning, and feature extraction. In deep learning, feature extraction becomes automated. Everything is a feature: customer location is a feature, age is a feature, income level is a feature — and every variable needs a proper way to be selected and transformed when you apply the predictive model. The toolset includes feature transformation, feature imputation, and combining features.

For feature reduction and feature selection people use PCA — principal component analysis — plus linear discriminant analysis and independent component analysis. The goal is to have the right amount of data by reducing the dimensions: from 10,000 features down to 1,000, or from 50 columns down to 5 columns. You can reduce the columns, reduce the features.

The feature toolset in one place:

  • Feature selection — pick the useful columns and drop the rest (variance and correlation are the guides; see the churn exercise in 7.6).
  • Feature transformation — scale, normalize, take logs, bin continuous values into categories.
  • Feature creation / derived attributes — build new columns from existing ones (the car-age example in 7.1.3).
  • Feature extraction / dimensionality reduction — PCA, linear discriminant analysis (LDA), and independent component analysis (ICA) compress many raw columns into fewer engineered ones.

The three reduction methods differ in what they optimize: PCA finds the directions of greatest variance in the data and projects onto them; LDA finds the directions that best separate the classes; ICA separates a signal into statistically independent components. The lecture's scale of ambition: 10,000 features down to 1,000, or 50 columns down to 5 — the churn exercise in the next section actually reduces its feature set to five.

Recap and bridge

The pre-processing toolkit: clean, impute missing values (mean or another value), remove outliers and duplicates, sample (random as the default, stratified when classes are skewed), partition into train/validate/test with duplicates removed before the split to block leakage, and scale with z-score \((z = \frac{x - \mu}{\sigma})\) or min-max \((x' = \frac{x - \min(x)}{\max(x) - \min(x)})\). The next section puts all of it to work in a live exercise — feature selection for a customer churn prediction dataset.

Real-world connection: every serious ML platform exposes these operations as built-in components — Scikit-learn's StandardScaler, MinMaxScaler, SimpleImputer, and train_test_split; Pandas for cleaning; feature stores that apply the same normalization at training and serving so the transform never drifts between the two. In regulated industries, the stored \(\mu, \sigma\) and \(\min, \max\) values are themselves versioned artifacts: an audit must be able to reproduce exactly how every input was scaled.

7.6 Feature Selection Exercise: Customer Churn Prediction

Here is a live exercise: a customer churn prediction dataset. The question to answer: which features are redundant — which are likely to be removed due to low variance or irrelevance?

Hook — the exercise that tests your judgment

The professor runs this as a live classroom exercise: a real customer churn dataset, a real question ("which features are redundant?"), and a real trap. The trap is that the obvious answer — drop the features that look unimportant — is wrong, and the class falls into it every time. The exercise is a test of whether you think like a fair judge or like someone who already decided.

7.6.1 The Churn Prediction Problem

The business problem: a service — a ticketing tool, a mobile application, a subscription model — gives monthly charges for the service, there is a tenure (how long each customer has used it), and customers report a satisfaction score. We have about five years worth of customer data. The question: in July — the next month after June — what will be the percentage of satisfied customers? Dissatisfied customers will leave the product, the tool, or the support service. So we want to predict the expected percentage of satisfied customers, and from that the percentage of dissatisfied customers who will churn next month.

Worked example — framing the churn exercise

The dataset holds about five years of customer records, one row per customer, with columns such as monthly charges, tenure (months since signup), satisfaction score, contract type, payment method, gender, age, and region. The target is binary: churn next month — will this customer be gone in July?

The prediction the business wants is not per-customer; it is an aggregate: what percentage of customers will still be satisfied next month? If the model predicts a probability of leaving for each customer, the expected percentage of dissatisfied customers is the average of those probabilities. Suppose the model marks 30 of 150 customers with a high churn probability; the expected dissatisfied share is about \(30/150 = 20\%\), so the expected satisfied percentage is about \(80\%\).

The question posed to the class: which features in the dataset are redundant — likely to be removed because their variance is low or because they seem irrelevant to churn?

The sense-check: the answer must survive a business question — if you remove a feature, can you still explain why customers left? That business test is what the next subsections turn on.

7.6.2 Low Variance and Redundancy

Variance is the measure of how far a feature's values spread around their own average:

\[ \operatorname{Var}(X) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2 \]

Here \(X\) is the feature, \(x_i\) is the \(i\)-th value of the feature, \(\bar{x}\) is the mean of those values, and \(n\) is the number of rows. This is the standard form for the population variance; some texts write the sample version with \(n - 1\) in the denominator for the same reason they do for any sample statistic. A feature that barely varies carries little information, so low-variance features are the first candidates for removal. But "irrelevance" is a business question, not just a statistics question — a feature with low variance can still matter if it explains churn.

Worked example — computing variance by hand

Take a tiny feature column with \(n = 4\) values: \(x = [10, 12, 14, 16]\).

  1. Mean: \(\bar{x} = \frac{10 + 12 + 14 + 16}{4} = \frac{52}{4} = 13\).
  2. Deviations from the mean: \(10 - 13 = -3\), \(12 - 13 = -1\), \(14 - 13 = 1\), \(16 - 13 = 3\).
  3. Squared deviations: \((-3)^2 = 9\), \((-1)^2 = 1\), \(1^2 = 1\), \(3^2 = 9\).
  4. Sum of squared deviations: \(9 + 1 + 1 + 9 = 20\).
  5. Variance: \(\operatorname{Var}(X) = \frac{20}{4} = 5\).

The sense-check: a constant column — every customer in the same region, say — has all deviations equal to 0, so its variance is 0, and it contributes nothing to separating customers: a classic removal candidate. The opposite extreme, a column where one value dominates the range, is the outlier problem from 7.5 — variance is sensitive to it.

7.6.3 Student Q&A: Which Features Can We Remove?

Q: Students proposed removing payment method, age, and gender as unnecessary. Which features can be removed, and why? Payment method is something not needed. What else? I think gender is also not needed here. Age — maybe not needed. A: The initial answer was: payment method, age, and gender are all removable. But think differently. Age and gender can stay, because sometimes the satisfaction score depends on them, and then you can do prescriptive analytics — you want to find root causes of churn, you want the correlation. Payment method also matters: in this app's data, people are told not to pay through SBI UPI because there is about a 70% chance the payment will be rejected — UPI sometimes slows down and does not work. So it depends on the business case we have to build. You have successfully biased our thinking — but you need to be like a fair judge, morally agnostic: even a hypothesis you already believe should have to prove itself in the data. That is where the improvements come.

The key correction: a feature is not redundant just because it looks irrelevant at first glance. If you want root-cause and prescriptive insight, age, gender, and even payment method can be the features that reveal why customers leave.

Why the students' answer seemed right, and why it was wrong:

  • Why it seemed plausible. "Payment method, age, and gender" look like demographics, not like churn drivers. Dropping them shrinks the feature set, which usually sounds like simplification.
  • Why it was rejected. Three separate reasons:
  1. Satisfaction depends on them. If satisfaction scores differ by age group or gender, those features carry signal the model needs.
  2. Root-cause and prescriptive analytics. Age and gender let the business answer why churn happens and prescribe action — "customers under 25 on yearly plans churn at twice the rate." A model without those features cannot be used to explain churn, only to predict it.
  3. Payment method is a business fact, not noise. In this app's data, SBI UPI payments are rejected about 70% of the time — UPI sometimes slows down and does not work — so a customer paying by SBI UPI is measurably more likely to be frustrated and leave. A "redundant" feature that marks the frustrated cohort is the opposite of redundant.
  • The replacement mental model. The fair judge, again: even a hypothesis you already believe has to prove itself in the data. The students "successfully biased our thinking" — the professor's point is that every proposed removal is a hypothesis about the business, and hypotheses get tested, not assumed.

7.6.4 The Modeling Code and PCA

The code for this exercise builds the feature set for customer churn prediction next month. Gender, contract type, payment methods, and region are treated as categorical columns. There is a churn threshold for the target "churn next month", and PCA is used to reduce the feature set — the exercise reduces the data to five features. Then the model is developed and trained.

The pipeline the code follows:

  1. Load and inspect the five years of customer data; confirm the target column (churn next month) and its threshold — a customer is marked as churned when the churn probability crosses the chosen cutoff.
  2. Encode categorical columns — gender, contract type, payment methods, and region are converted from text to numbers (one-hot or label encoding), because models need numbers.
  3. Scale the numeric features with the techniques from 7.5.4, since PCA is sensitive to units.
  4. Reduce with PCA — principal component analysis compresses the full feature set down to the five most informative components for this exercise (recall 7.5.5: from 50 columns to 5).
  5. Train the model on the reduced features and evaluate it.

The important tension: PCA gives you five engineered components (linear combinations of the originals), while the feature-selection question from 7.6.3 was about keeping the original features for explainability. For a pure prediction score, the PCA-reduced set is compact and fast; for root-cause and prescriptive analysis, the original age, gender, and payment-method columns must survive — which is exactly why the professor kept them in the earlier exchange.

Recap and bridge

The churn exercise shows feature selection as a business judgment, not a statistics reflex: variance \(( \operatorname{Var}(X) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2 )\) identifies features that barely vary, but a low-variance or "unimportant-looking" feature (age, gender, payment method — including the 70%-rejected SBI UPI case) can be the very feature that explains churn, so removals must pass the fair-judge test. With the features settled, the next section turns to the modeling stage itself: choosing the algorithm, validating with RMSE, and tuning hyperparameters.

Real-world connection: the SBI UPI example is a real, named business case — payment-failure frustration driving churn — and it is why banks and payment providers monitor their UPI rejection rates as a churn-leading indicator. The same "explainability versus compactness" trade-off is what separates prediction platforms (which happily ship five PCA components) from regulated analytics teams (which must keep interpretable columns for audit and root-cause reporting).

7.7 Model Development, Algorithm Selection, and Hyperparameters

After the exercise, model development: we build the model and train it. This is where algorithm selection happens — which model are you going to choose, and are you going to do model parallel or data parallel?

Hook — there is no single best algorithm

Beginners ask "which algorithm is best?" The professor's answer, from years of reviewing data science and AI projects, is the same every time: do the literature review, then try multiple algorithms and compare them on your metric. The best algorithm is the one that wins on your data with your validation metric — and you only find it by trying.

7.7.1 Choosing the Algorithm: What to Consider

When many projects are reviewed — the professor has been a reviewer for many data science and AI projects — the standard advice is always the same: do the literature review. Try, try, try multiple algorithms, and see which one works for you. You have to select the right algorithm and find the factors to consider: what metrics you are going to use, whether the model is explainable, and what type of computations it is going to take. All of these matter.

On parallelism: data parallel means the data is split across multiple instances or nodes, each running the model on its share; model parallel means the model itself is split across nodes. Bagging and boosting are the related ensemble ideas. Then come debugging and profiling: debug the code, find the errors, and profile the entire system.

The selection factors, as a checklist:

  • Literature review first. Look at what others solved with this type of problem and this type of data. The review is both a time-saver (avoid re-discovering that trees beat raw deep networks on small tabular data) and an exam discipline (the professor's review advice, repeated in the Exam Guidance Summary).
  • Metrics. What will you measure? Accuracy, RMSE, precision and recall — the metric must match the business criterion framed in 7.3.
  • Explainability. Can you say why the model made a decision? A credit-rejection model must be explainable; a recommender's ranking score may not need to be.
  • Computational cost. What type of computations does the algorithm need — how much memory, how long per training run, and what will inference cost per prediction?
  • Parallelism when the data or model is huge. Data parallel splits the data across multiple instances or nodes — each node runs the whole model on its own share of the data, and the results are combined (the standard choice for deep learning on large datasets). Model parallel splits the model itself across nodes — needed when a single model does not fit in one machine's memory. Related ensemble ideas are bagging (many models trained on different samples, results averaged — the "bootstrap aggregating" behind random forests) and boosting (models trained in sequence, each correcting the previous one's mistakes).
  • Debugging and profiling. Debug the code and find the errors, then profile the whole system — measure where time and memory actually go before assuming the algorithm is the bottleneck.

7.7.2 Validation Metrics: RMSE

The validation metrics tell you whether the model is actually good. The very important one used here is the root mean square error — RMSE — or the mean square error, MSE. RMSE compares predicted versus actual: the professor's example is a prediction of 90 where the actual value is 80.

\[ \text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2} \]

Here \(y_i\) is the actual value for sample \(i\), \(\hat{y}_i\) is the predicted value, and \(n\) is the number of samples. This is the standard form of RMSE: the square root of the average of the squared prediction errors. We do this for multiple samples to find out what the error is, and RMSE is one of the methods used to validate the system. The other pillar is hyperparameter tuning, which gets its own session later.

Worked example — RMSE with the professor's numbers

The professor's example: predicted 90, actual 80. The error is \(y_i - \hat{y}_i = 80 - 90 = -10\); its square is \((-10)^2 = 100\); with a single sample (\(n = 1\)), RMSE = \(\sqrt{100} = 10\). (Note: the stated difference in class is "2", but the arithmetic of the stated values 90 and 80 gives 10 — we work with the stated values, where the error is 10.)

Now three samples: predictions 90, 85, 78 against actuals 80, 82, 76.

  1. Errors: \(80 - 90 = -10\), \(82 - 85 = -3\), \(76 - 78 = -2\).
  2. Squared errors: \(100\), \(9\), \(4\).
  3. Mean of squared errors (MSE): \(\frac{100 + 9 + 4}{3} = \frac{113}{3} \approx 37.67\).
  4. RMSE: \(\sqrt{37.67} \approx 6.14\).

The sense-check: RMSE is always at least as large as the average absolute error (because squaring punishes big errors), it is 0 only for a perfect model, and it is measured in the same units as the target (rupees for a price model), which is why RMSE beats MSE for talking to business users. Squaring also explains the "predicted versus actual" framing: signs cancel in the squares, so over-predictions and under-predictions both count as errors instead of averaging each other out.

Pitfalls when using RMSE

  • Reading RMSE as the "average error." RMSE is the root of the average squared error. One large error dominates: errors of 10 and 1 give RMSE \(\sqrt{(100+1)/2} \approx 7.1\), far above the arithmetic average of 5.5. If large individual errors are tolerable, MAE (mean absolute error) is the metric that reports the true average.
  • Comparing RMSE across different units or targets. An RMSE of 6 for house prices in lakhs and 6 for a rating scale are not comparable; compare RMSE only between models on the same target and units.
  • Outliers inflating the score. Because squaring magnifies big errors, a few bad predictions can make a good model look bad — check the per-sample errors before trusting the single number.
  • The reported 90-vs-80 style slip. When an example's numbers and its stated difference disagree, trust the numbers and recompute — the arithmetic is the ground truth.

7.7.3 Hyperparameters: How the Brain Works

Hyperparameters were introduced with a live brain exercise.

Q: What is 5 times 4? What is 20 divided by 2? What is ten to the power 100? A: The first two answers come instantly — 20, then 10 — and then everyone stalls on ten to the power 100. That is not about mistakes; it is about how your brain works, and it is very hard to measure. Different people store and recall things differently: someone is good at math, someone at physics, someone at chemistry. There are hidden parameters and hidden layers inside — it is all brain functionality. Step size matters too: reverse the number 1781, and the careful answer 1871 takes a little time; people who take faster steps make mistakes, people who take smaller steps may do it better. Those internal settings are hyperparameters. You can find out some things directly — ask a question, get a yes or no, correct or not correct — those are known parameters. The indirect parameters, the hyperparameters, you cannot observe directly; you have to tune them, especially in deep learning: step size, epoch, error rates — a lot of hyperparameters are there.

The brain exercise maps directly onto machine learning vocabulary:

  • Known parameters — the things you can observe directly: ask a question, get a yes or no, correct or not correct. For a model, these are the weights and biases the training algorithm learns and writes down; you can read them out of the model at any time.
  • Hyperparameters — the hidden settings you cannot observe directly, which control how the system learns: step size (how big a jump each learning step takes), epochs (how many passes over the training data), and error rates or tolerance thresholds. They are not learned from data; they are chosen before training and tuned by training — which is why the tuning is called hyperparameter tuning and gets its own session later.
  • The 1781 lesson. Reversing 1781 step by step gives 1871, and it takes a little time. People who take faster steps make mistakes; people who take smaller, careful steps may do it better. Step size is the model's equivalent: a step size too large overshoots the optimum and the loss jumps around; a step size too small converges painfully slowly. The right step size is a hyperparameter that must be tuned.

The model artifacts are the outputs that result from a trained model. Before production there is a pre-production pipeline: we prepare the system, we get the pipeline — online features, offline features — and finally the CI/CD/CT pipeline: continuous integration, continuous deployment, and continuous testing. That is the future now. Once the pipeline is built, we evaluate; the train pipeline keeps training, confirming that performance matches expectations — and if not, you retrain, retrain.

7.7.4 Training Many Models with Cross-Validation

Model training applies a machine learning algorithm on training data to train the model, and the key practice is: train many ML models from different categories — linear regression, logistic regression, K-means, naive Bayes, SVM, random forest — using standard parameters. That is what ensemble technique is about: apply multiple models with standard parameters, measure and compare their performance. For each model use n-fold cross-validation — the method is available as a package in Scikit-learn, so you just apply it and use the cross-validation score.

\[ \mu_{\text{CV}} = \frac{1}{k}\sum_{i=1}^{k} s_i \]

Here \(k\) is the number of folds and \(s_i\) is the score of fold \(i\). The cross-validation score is the average of the per-fold scores — the standard form of the n-fold cross-validation result. You use this technique to find overfitting: look at the tenfold results, look at the standard deviation around that 90% accuracy — what was the variation — check the errors on every fold, and then select the features you need. Identify the top five most promising models for the problem. It is like buying a phone: you selected Samsung, you selected Google Pixel, you selected another phone, and you compare them on your parameters — which is better, what type of errors. You can also combine the models: ensemble methods like bagging, boosting, or stacking, or a simple majority vote of which model gives the right answer. Then you evaluate the model and test the model.

Worked example — 5-fold cross-validation

Split the training data into \(k = 5\) equal folds. For fold 1: train on folds 2–5, score on fold 1. For fold 2: train on folds 1, 3, 4, 5, score on fold 2. Repeat so every fold is the test set exactly once. Suppose the per-fold accuracy scores come out as \(s = [0.88, 0.90, 0.86, 0.92, 0.89]\).

  1. Sum: \(0.88 + 0.90 + 0.86 + 0.92 + 0.89 = 4.45\).
  2. Cross-validation score: \(\mu_{\text{CV}} = \frac{4.45}{5} = 0.89\) — the model is "89% accurate" by cross-validation.

The second number the professor points to is the spread: the fold scores range from 0.86 to 0.92, a standard deviation of about 0.022. If one fold scores 0.70 while the others score 0.90, the model is unstable — it performs badly on some slice of the data — and that instability is exactly the overfitting signal cross-validation exists to expose.

The sense-check: high average with low spread means a trustworthy model; high average with high spread means the average flatters a model that fails on parts of the data; and a model that overfits (from the shirt story) will show a large gap between its training accuracy and its cross-validation score.

The phone-buying analogy

Buying a phone: you shortlist Samsung, Google Pixel, and another model, then compare them on your parameters — camera, battery, price — and pick the one that wins for you. Model selection is identical: shortlist candidates from different model families — linear regression, logistic regression, K-means, naive Bayes, SVM, random forest — run each with standard parameters, measure with cross-validation, and compare the scores and the error patterns. Where the analogy breaks: you can combine the shortlist — ensembling (bagging, boosting, stacking, or a majority vote) builds one model from several, which no phone buyer does.

7.7.5 Model Serialization Formats

A working model has to be distributable, and the serialization formats should be language agnostic — the model should not be restricted to one package; it should be usable from Python, Ruby, or any other code. The formats:

  • PMML — Predictive Model Markup Language. Serialize the model to a .pmml file; it is standardized by the data mining group, but it does not support all ML algorithms.
  • PFA — Portable Format for Analytics — a JSON-formatted text.
  • ONNX — Open Neural Network Exchange format.
  • pickle — saves a model as Python objects in a .pkl file.
  • H2O — converts the model to either POJO, a plain old Java object, or MOJO, a model object optimized for the model.
  • TensorFlow and PyTorch — give a .pt file.

Use whichever is good for your case. You can also choose online training or offline training, and batch predictions or real-time prediction: for batch prediction you forecast and predict; for offline you can use a REST API.

The common thread is interoperability: a model serialized in a portable format can be loaded and executed by a different runtime than the one that trained it — a TensorFlow model served from Java, a PMML scoring engine, an ONNX model moved between frameworks. The trade-offs between the formats: PMML and PFA are standardized and language agnostic but support only the algorithm families their spec covers; pickle is simple and complete for Python but Python-only and unsafe to load from untrusted sources; ONNX is the modern exchange format between frameworks; H2O's POJO (plain old Java object) and MOJO (model object optimized for scoring) target Java runtimes; TensorFlow and PyTorch write their own formats (a .pt file) with native serving stacks.

The training and serving choices complete the picture: online training updates the model as new data arrives (close to the learn-and-relearn loop of 7.4.4); offline training runs on a fixed snapshot; batch prediction forecasts for many records at once (nightly scoring of all customers); real-time prediction answers one request at a time — typically served through a REST API, the standard interface for offline-built models.

Recap and bridge

Model development is a disciplined comparison, not a single shot: do the literature review, try many algorithms with standard parameters, score each with n-fold cross-validation (the mean of the per-fold scores \(\mu_{\text{CV}} = \frac{1}{k}\sum_{i=1}^{k} s_i\), with the fold spread as the overfitting signal), validate with RMSE \(\sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2}\), tune hyperparameters (step size, epochs, error rates — the hidden settings the brain exercise stood for), and distribute the winner in a portable serialization format (PMML, PFA, ONNX, pickle, H2O POJO/MOJO, TensorFlow/PyTorch .pt). The next section follows the model out of the lab: deployment strategies and the inference pipeline that keeps it healthy.

Real-world connection: these are the exact mechanics behind modern ML platforms — Scikit-learn's cross_val_score package implements n-fold cross-validation directly; MLflow tracks models, metrics, and parameters so comparisons are reproducible; ONNX is the industry bridge between PyTorch research models and optimized production runtimes; and the phone-buying comparison mirrors how Kaggle winners and industrial teams maintain leaderboards of candidate models with their RMSE or accuracy scores.

7.8 Deployment Strategies and the Inference Pipeline

Deployment and testing strategies reduce the downtime and risk when releasing a new or updated version of a model. Four strategies were covered: blue-green, canary, A/B testing, and shadow deployment.

Hook — why not just switch the model over?

Updating a model in production is not like updating a document — a bad release can serve wrong predictions to thousands of users before anyone notices. The four deployment strategies are different answers to one question: how do you put a new model into production with the least downtime and the least risk?

7.8.1 Deployment Strategies

  • Blue-green deployment: two identical production environments — blue is the existing infrastructure, and green is an identical infrastructure for testing. You know this in industry as staging versus pre-prod versus prod. When green passes testing, traffic switches over.
  • Canary deployment: a new release is deployed to a small group of users, while other users continue to use the previous version.
  • A/B testing: similar to canary, but with a larger user group and a longer time scale, typically days or even weeks. You partition the users and give each group a version.
  • Shadow deployment: the new version is available alongside the old version; the old version keeps serving while the new one is validated on live traffic without users noticing.

Exam note: you may expect a question on this — what deployment strategy you would follow, maybe the lowest-cost strategy, which environment you would use. It is worth taking a screenshot of the strategy table.

Strategy How it works User impact Typical duration Cost profile
Blue-green Two identical environments; green is tested, then traffic switches over Instant switch — users see the new version at cutover Minutes to hours per release Higher (two full environments)
Canary New release goes to a small group of users first (often 1–5% of traffic) Small fraction sees the new version Hours to days Low to medium
A/B testing Users are partitioned; each group gets one version for measurement A large share of users sees one of the two versions Days to weeks Medium (longer measurement)
Shadow New model runs on live traffic in parallel; old model keeps serving; results are compared None — users never see the new version Days Low (extra compute only)

When to pick which: choose shadow when you must validate on live data without any user risk; canary when you want a small, controlled exposure with automatic rollback; A/B when the question is scientific — which model actually moves the business metric; and blue-green when the goal is near-zero-downtime switching and you can afford the duplicate environment.

Worked example — releasing a churn-scoring model with blue-green

The churn model from 7.6 is version 1.2 and must replace version 1.0 in production.

  1. Blue is the live environment serving version 1.0 to all customers.
  2. The team builds green — an identical environment with the same database, same API, same monitoring — running version 1.2.
  3. Green runs the full test suite: load test (500 requests/second), accuracy check against a golden batch of labeled records, and a latency check (p95 under 200 ms).
  4. All green checks pass → traffic switches over in one cutover. If version 1.2 had failed any check, the team would simply keep blue serving and fix green — zero user impact.
  5. After a soak period, blue is retired or kept as the rollback target.

The sense-check: the cost is two environments running at once, and the benefit is that the switch is atomic — users never see a half-migrated system.

7.8.2 The Inference Pipeline: Trainer, Scheduler, Drift, XAI

Beyond the initial deployment, the system runs an inference pipeline. A real-time inference pipeline serves predictions for what is happening now. A trainer component trains and retrains. A scheduler runs retraining at different intervals, using the data accumulated since the last training, to minimize the risk of drift between the data and the model.

One important thing: the model has to be explainable. XAI — Explainable AI — is one of the latest trends in industry: whatever parameters and methods you use should be explainable. Wherever there are issues, wherever there is a trust problem, you check the fairness and the accountability of the results: keep checking the fairness results, detect the drift, monitor the system, and detect data drift or concept drift. When the incoming data distribution is no longer correct compared with the previous dataset — suddenly there is a difference in the data — you need to update the pipeline. You explain the model, you find out whether the accuracy problem comes from the data or from the method, and then you update the model through the model update pipeline.

The inference pipeline has four cooperating parts:

  • Inference — serves predictions for what is happening right now (the live API answering each request).
  • Trainer — trains and retrains the model as new labeled data accumulates.
  • Scheduler — runs retraining at set intervals (nightly, weekly) on the data accumulated since the last training run; regular retraining is the simplest defense against drift between the data and the model.
  • Explainability and monitoring — XAI makes the model's decisions explainable; drift detection watches whether the incoming data distribution still matches what the model was trained on. Data drift means the input distribution changed; concept drift means the relationship between inputs and answers changed. When the incoming data is suddenly different from the previous dataset, the pipeline must be updated — and the first diagnostic question is whether the accuracy problem comes from the data or from the method.

7.8.3 The Model Update Pipeline

Q: What do you see in the model update pipeline at the leftmost part of the architecture? A: If the alarm manager identifies violations, it launches the model update pipeline for a retrain.

The alarm manager watches the production model; when drift or a violation is detected, the model update pipeline is launched for a retrain. After the retrain, the model is re-evaluated and, if it passes, re-deployed.

The leftmost part of the architecture is the trigger side: the alarm manager is the watchdog that decides when to retrain. It monitors production signals — accuracy dips, drift metrics, fairness violations, latency or availability problems — and when it identifies a violation, it launches the model update pipeline. The update pipeline then retrains on newer data, the retrained model is re-evaluated (against the same quantitative criteria from 7.3), and only a model that passes is re-deployed. This closes the loop that began in 7.4.4: alarm → retrain → evaluate → deploy.

7.8.4 Three Levels of ML Pipeline Software

Machine learning pipelines have three levels of software. Level one is model engineering: a structured method where you perform feature engineering first, then model engineering. Level two is model training: applying a machine learning algorithm on training data to train the model, which is where you train many models from different categories with standard parameters and compare them. The third level is the deployment and monitoring machinery around the model — the serving, the scheduling, the drift detection, and the update pipeline that keep the trained model working in production.

  • Level 1 — Model engineering. The structured method that runs feature engineering first, then model engineering: the features built in 7.5 and 7.6 become the model built in 7.7.
  • Level 2 — Model training. Applying the learning algorithm to the training data — the cross-validation comparison from 7.7.4, training many models from different categories with standard parameters and comparing them.
  • Level 3 — Deployment and monitoring machinery. Everything around the trained model that keeps it working: serving, scheduling, drift detection, the update pipeline. This level is where the current section lives, and where most production ML teams actually spend their effort.

Pitfalls in deployment

  • Releasing without a rollback path. Every strategy in 7.8.1 assumes you can undo the release. With no rollback target, a bad model is stuck in production until a new one is trained.
  • Cutting over without validation. Green must pass its tests before traffic switches; canary must pass its small-group window before widening. Teams that skip validation because "the offline accuracy was good" discover that production data differs from training data.
  • Ignoring the environment question. The professor's exam hint — which environment, which strategy, lowest cost — mirrors the real mistake: teams pick a strategy without checking whether their infrastructure (two environments? traffic routing? canary capability?) can even support it.
  • Treating drift detection as optional. The scheduler exists to prevent drift; the alarm manager exists to catch it. A deployed model with neither is a model whose decay goes unnoticed until the business metric falls.

Recap and bridge

Deployment is risk management: blue-green (identical environments, atomic switch), canary (small user group first), A/B (larger, longer scientific comparison), and shadow (parallel validation with no user impact) reduce downtime and risk; the inference pipeline pairs real-time serving with a trainer, a scheduler, XAI and drift detection; the alarm manager launches the model update pipeline for a retrain when violations appear. The next section zooms into the serving side itself — the architecture patterns (model as a service, model as dependency, pre-compute, on demand, hybrid) that decide how predictions actually reach users.

Real-world connection: these strategies are the daily practice of MLOps platforms — Kubernetes-based serving with canary traffic splits, AWS CodeDeploy and Azure Deployment Slots for blue-green, feature-flag platforms for A/B, and "shadow mode" built into SageMaker endpoints. XAI tooling (SHAP, LIME, and model-card reporting) is mandated in regulated industries for fairness and accountability checks, and the alarm-manager role is filled by monitoring stacks (Prometheus-style metrics plus dedicated drift-detection libraries) that page engineers when a violation appears.

7.9 Model Serving Architecture Patterns

Architecture patterns are reusable solutions to software problems, and ML systems use the same idea. Why do we need patterns? Because the problems we see in the software industry are repetitive in nature: design patterns like the observability pattern or the factory pattern exist to solve a problem that is already solved and repeatable. Patterns are easy to maintain, people understand the pattern, and when other problems come in the pipeline it is easy to detect them.

Hook — you already know a design pattern

You have used the iterator pattern your whole programming life without knowing its name: the humble for loop. Architecture patterns are simply names for solutions that the industry has solved before — once a pattern has a name, every new team inherits the solution instead of re-inventing it. This section names the patterns that decide how a trained model reaches its users.

7.9.1 Why Architecture Patterns

You all have used the iterator pattern without knowing it. A for loop — start i at 1, while i is less than or equal to 10, increment i — appears in C, C++, Java, .NET, and Python. It is needed whenever you have a set of data: a market basket holds 20 items, and to find out how many items there are and what they cost, you check them one by one — take one, scan it, put it in the chart. That is the iterator pattern. Other well-known patterns are model-view-controller (MVC), the broker pattern, and the factory pattern. The question for us: which patterns are useful for machine learning?

The market-basket walkthrough makes the iterator concrete: the basket holds 20 items; the loop starts at item 1, takes it, scans its price, records it in the chart (the running total), moves to item 2, and repeats while the counter stays at or below 20. The pattern is the visiting of every element in a collection exactly once, and it is the reason the same loop shape works in C, C++, Java, .NET, and Python — the languages differ, the pattern is the same. Because problems are repetitive, patterns are easy to maintain: people understand the named pattern immediately, and new problems arriving in the pipeline are detected faster because they map onto known shapes. MVC, the broker pattern, and the factory pattern are the same idea applied to user interfaces, message routing, and object creation.

7.9.2 Pattern Review: Iterator and Publisher-Subscriber

ML is about predicting and relearning. Machines are not gods — they just learn from data, relearn, learn and relearn. For automated systems, AutoML is the sophisticated version of online learning: you give it a model, an interpreter, and input data. For serving the model, there are specific patterns: model as dependency, model as service, pre-compute, model on demand, and hybrid serving.

Q: What pattern do Instagram, Facebook, and YouTube use? We guessed a user graph. A: Publisher-subscriber, mostly. Facebook, Twitter, Instagram, YouTube — yes, publisher-subscriber. If I have a YouTube channel and you follow me, you subscribe and you get the notification; whatever you subscribe to, you receive updates from.

Why the class's guess — a user graph — seemed right, and why it was rejected: Instagram and Facebook do maintain friendship graphs internally, so "user graph" is a plausible architecture guess. But the pattern they present to the outside world — and the pattern this lecture is about — is publisher-subscriber: content publishers post updates, and subscribers who follow the channel receive them. A YouTube channel is the publisher; following it makes you a subscriber; every new upload arrives as a notification without you asking for it. The replacement mental model: think about the flow of updates (who publishes, who receives), not the network of friends.

ML's own framing of the same idea: "machines are not gods — they just learn from data, relearn, learn and relearn." AutoML is the sophisticated, automated version of online learning: you give it a model, an interpreter, and input data, and it runs the learn-and-relearn loop for you.

7.9.3 Model Serving Patterns: An Overview

The five serving patterns for ML models:

  • Model as a service — the model is wrapped and exposed as an independent service.
  • Model as dependency — the model is packaged inside the software application.
  • Pre-compute — predictions are computed ahead of time and stored.
  • Model on demand — the model is loaded at runtime, typically behind a message broker.
  • Hybrid serving — a combination, of which federated learning is the famous example.
Pattern Where the model lives When to use it
Model as a service Standalone service with its own API Many consumers need the model; scale it independently
Model as dependency Inside the application (an import) One application, straightforward packaging
Pre-compute Predictions stored in a database ahead of time Forecastable demand; latency must be near zero
Model on demand Loaded at runtime behind a message broker Variable request rates; decoupled producers and consumers
Hybrid serving Combination (e.g., federated learning) When no single pattern fits all users

7.9.4 Model as a Service and Model as Dependency

Model as a service is the common pattern for wrapping an ML model as an independent service. You give your input to a web application, the web application passes the input to a web service that wraps the ML model with an interpreter, the model predicts, and the result comes back to the web application. It is software as a service applied to models: the model might be predicting the gold price, and the web app just consumes the prediction through the API. You use this pattern every day with AI assistants such as GYANMATI and Copilot — you give them input through a web application and they predict the response.

Model as dependency is the opposite packaging: the ML model is considered a dependency within the software application, and the application must use it. It is the most straightforward way to package the ML model — you use an import statement in your code.

The two patterns are opposites in packaging but both simple:

  • Model as a service. The model lives behind its own web service: the web application takes the user's input, calls the service, the service's interpreter runs the model, and the prediction returns. Because the model is an independent service, it can be scaled, versioned, and replaced without touching the web application — software as a service applied to models. A gold-price model wrapped this way is consumed through an API by any number of client apps. Everyday examples: GYANMATI and Copilot — you type input into a web application, and a model service predicts the response.
  • Model as dependency. The model is packaged inside the application and used directly — typically one import statement in the code. It is the most straightforward packaging, at the cost of coupling: updating the model means rebuilding and redeploying the application.

7.9.5 Pre-compute Serving

Pre-compute serving is for forecasting. You use an already trained model to pre-compute predictions for the incoming data ahead of time, persist those predictions in the database, and serve them directly when asked. Think of a table booking in a hotel: 50 people are coming, so the table is made ready — water, juice, sandwiches — before they arrive. When you invite people home, the water and snacks are ready immediately, and the cooking starts afterward. It is the same idea as pre-fetching in databases: every database — Oracle, Sybase, DB2 — performs pre-fetching, pulling data into a buffer so it is already in memory when you refer to the table. That is the data buffer and data cache — the redo or transaction log buffer — and the optimization pulls the result from what is available. When the request is real time and cannot be pre-computed, you move to the next pattern.

The table-booking analogy

Pre-compute serving is reserving the outcome before the request arrives. The hotel knows 50 people are coming, so the table is made ready — water, juice, sandwiches — before they arrive; when you invite people home, the snacks are ready and the cooking starts only afterward. Every major database does the same: Oracle, Sybase, and DB2 pre-fetch data into a buffer so it is already in memory when a query refers to the table — the data buffer and data cache, including the redo and transaction log buffers. The optimization serves answers from what is already available. Where the analogy breaks: pre-computed predictions can go stale — the forecast was made on yesterday's data, so if the world changed, the stored answer is outdated. That is why the pattern is for forecasting (stable, scheduled demand) and the next pattern takes over when requests are truly real time.

7.9.6 Model on Demand and the Message Broker

Model on demand means the ML model is available at runtime on request. The message broker architecture is typically used for such on-demand model serving. It has two main types of components. The broker component contains the event channels that are utilized within the event flow — those event channels are message queues; a message broker allows one process to write prediction requests to an input queue. The event processor component contains the model serving runtime and the ML model: it connects to the broker, reads the requests in batch from the queue, sends them to the model to make the predictions, and the model serving process writes the resulting predictions to the output queue.

A story makes it concrete: the professor acts as a broker for stories — someone sends him a message that a story needs to be read, and he hands it to the right reader, a different person for a Hindi story, a Tamil story, or another language. You are the mediator. The chat in the class worked the same way: a student asked a question in the chat at 11:19, and the professor answered at 11:29 — the question sat in a message queue, and the answer came after ten minutes based on priority.

Worked example — the 11:19 chat question

A student types a question in the class chat at 11:19. The question is not answered instantly — it sits in the message queue, waiting for the professor (the event processor) to read it. Other messages with higher priority are handled first. At 11:29 — ten minutes later — the professor reads the question from the queue and posts the answer. The chat worked exactly like on-demand serving with a message broker:

  1. The student (a producer) writes the question to the input queue.
  2. The broker holds the message in its event channel until the processor is ready.
  3. The professor (the event processor, reading in batch by priority) takes the question, works out the answer, and writes it to the output queue.
  4. The answer is rendered back to the student.

The sense-check: producer and consumer are decoupled — the student did not have to wait for the professor to be free at that instant, and the professor did not have to be online when the message arrived. The queue absorbs the timing difference, which is exactly what a message broker does for prediction requests.

Q: What do you infer from that description of on-demand serving? A: Requests go into a message queue; the event processor reads the request from the queue, runs the prediction, and writes the answer to a prediction queue, and the prediction service renders it back to the requester. The processor can choose which model serves which type of request.

The components in one picture: the broker holds the event channels — the message queues — and lets any process write prediction requests to the input queue; the event processor holds the model serving runtime and the ML model, connects to the broker, reads requests in batch, runs the predictions, and writes the results to the output queue. The processor can also route by request type — choosing which model serves a Hindi story versus a Tamil story, or which model scores a credit request versus a fraud request. The broker story is the professor in the mediator role, handing each message to the right reader.

7.9.7 Federated Learning and Hybrid Serving

Federated learning is also called hybrid serving. The idea: individually, anyone can learn, and then they share; finally the results are aggregated and summarized. On the server side, the model is trained only once, with real-world data, and it sets the initial model for each user — a relatively general trained model that fits the majority of users. Then as many models as users exist, in addition to the one held on the server: each user's device keeps refining its own model, and the results are aggregated back. This goes into personalization — a server-side model that is general enough for everyone, plus per-user models that learn from each individual.

Federated learning is hybrid because it combines two patterns at once: the server model serves the general case (model as a service at the center), while each user's device serves its own personalized copy (model on demand / as dependency at the edge). The training flow is what makes it federated: the server trains a general model once on real-world data, ships that model to every user as a starting point, each user's device keeps refining the model on that user's private data — as many models as users exist, on top of the server's copy — and the individual learnings are aggregated back to improve the shared model. The privacy benefit is the point: raw user data never leaves the device; only model updates travel. The result is personalization at scale — a server-side model general enough for everyone, plus per-user models that learn from each individual.

Recap and bridge

Serving patterns are named, reusable answers to the repetitive problem of getting predictions to users: model as a service (independent API), model as dependency (an import inside the app), pre-compute (forecast ahead, serve stored answers), model on demand (message broker with queues between producers and processors), and hybrid serving (federated learning as the famous example). The next section steps back from the serving layer to the raw material of every pattern: where data comes from, and how to categorize it by structure, by ownership, and by regulation.

Real-world connection: these five patterns are what production ML platforms implement — SageMaker endpoints and Vertex AI Prediction as model-as-a-service; embedded TensorFlow Lite models in mobile apps as model-as-dependency; recommendation caches and daily forecast tables as pre-compute; Kafka- or RabbitMQ-backed scoring pipelines as model-on-demand; and federated learning frameworks such as TensorFlow Federated for keyboard prediction on phones. The 11:19-to-11:29 chat story is exactly the async pattern behind every request queue in a real serving architecture.

7.10 Data Sources and Data Types

ML systems can work with many data sources, and you have to categorize the data properly. The Netflix case study is the canonical example of how many data sources a recommendation system consumes.

Hook — one system, a dozen data sources

A recommendation engine looks like a single product, but under it runs a dozen different data sources: ratings, popularity metrics, queue patterns, metadata, social data. The exam-relevant skill in this section is classification — for any data source, can you say whether the data is structured, semi-structured, or unstructured, and who owns it?

7.10.1 The Netflix Recommendation Case Study

According to the Netflix technology blog, the data sources for their recommendation system are:

  • Several millions (billions) of ratings from its members, with more than a million new ratings added every day.
  • Popularity metrics, computed in many aspects and at different intervals — hourly, daily, and weekly.
  • Clusters of members, formed geographically or by using other similarity metrics — different dimensions over which popularity is computed.
  • Stream-related data, such as duration, time of playing, time of device, day of week, and other context-related information.
  • The patterns and titles that subscribers add to their queues each day — millions in number.
  • All the metadata related to a title in their catalog, such as director, actor, channel, rating, and reviews from different platforms.
  • Social data of users, added recently, so that social features related to them and their friends can be extracted to provide better suggestions.
  • Search-related text information from Netflix subscribers or members.
  • External data, such as critic reviews.
  • Other features: demographics, culture, language, and other temporal data used in their predictive models.

Every step has its source. The billion ratings are structured data already stored in databases — raw data, structured. The social media data is semi-structured — that is the HTML kind of data you tokenize and parse. The search-related text is unstructured: a user searches for "what is the movie recently acted by Kamal Haasan or Shah Rukh Khan or Aamir Khan this year" — free text, unstructured.

Exam note: you may get a case study like this in the examination. You may be asked to identify what the source is and what the type of data is — structured, semi-structured, or unstructured.

The case study's lesson is that a single ML system is fed by many sources, and the classification per source:

  • Ratings (billions, a million new ones daily) — structured: stored in databases as rows of member, title, score.
  • Popularity metrics (hourly, daily, weekly intervals) — structured, computed from raw logs.
  • Member clusters (geographic or similarity-based) — structured descriptions of groups.
  • Stream-related data (duration, time of playing, day of week) — structured event data.
  • Queue patterns and titles (millions per day) — structured user-action data.
  • Title metadata (director, actor, channel, rating, reviews) — structured catalog data.
  • Social data — semi-structured: the HTML-like data you tokenize and parse.
  • Search text ("what is the movie recently acted by Kamal Haasan or Shah Rukh Khan or Aamir Khan this year") — unstructured free text.
  • External critic reviews — text, largely unstructured.
  • Demographics, culture, language, temporal data — structured feature tables.

7.10.2 Structured, Semi-structured, and Unstructured Data

The professor's own example of the unstructured-to-semi-structured boundary is a Flipkart review mining program: he built a complete program for building recommendation systems for Amazon and Flipkart. For the OnePlus Nord CE 3 Light phone, he went to the Flipkart website, pulled all the reviews, did some scraping and HTML parsing and extraction, and collected all the tokens. Then he built word clouds: a unigram word cloud and a bigram word cloud. The bigrams showed phrases like "camera is good", "battery fast", "mobile quality", "charging nice" — whichever phrases had high frequency tell you what buyers care about. Social media data and HTML data become semi-structured as soon as you parse them; the raw text is unstructured.

Worked example — the Flipkart review mining program

For the OnePlus Nord CE 3 Light, the professor built a complete review-mining pipeline:

  1. Scrape — pull all the customer reviews from the Flipkart website.
  2. Parse — scrape and HTML-parse the pages, extracting the review text from the page structure. This is the moment the data changes class: raw HTML is semi-structured (it has tags and structure), but the free-text review itself is unstructured.
  3. Tokenize — split each review into tokens (individual words).
  4. Aggregate into word clouds — build a unigram word cloud (single words, by frequency) and a bigram word cloud (two-word phrases, by frequency).
  5. Read the result — the high-frequency bigrams came out as "camera is good", "battery fast", "mobile quality", "charging nice". Those phrases tell you what buyers actually care about — the feature-level sentiment of the product.

The sense-check: word clouds of tokens convert thousands of unstructured reviews into a structured frequency summary that a business can read in seconds. The same pipeline — scrape, parse, tokenize, count — is how social media data and HTML data become semi-structured then structured: the raw text is unstructured; the parsed page is semi-structured; the frequency table is structured.

Data type Definition Example from the lecture
Structured Organized in fixed rows and columns, fits a schema, queryable Netflix's billion ratings in databases; popularity metrics
Semi-structured Has tags or markers but no rigid schema — becomes structured once parsed Social media data, HTML pages, JSON
Unstructured Free text or media with no internal structure Search queries, review text, critic reviews

7.10.3 Data Categories: First, Second, and Third Party

Data can be categorized by origin: first party data, second party data, or third party data; some is internal, some external, some hybrid. It is similar to intranets: an intranet is only the company, an extranet extends to partners, and the internet is hybrid — part of the data can be accessible to people. There is also user input — data explicitly given by users, often text, images, or tabular data. User data is the uncontrollable kind: the point is made with a trivia question (the longest railway station name in the world is in Wales, UK, and the longest in India is the M.G. Ramachandran Central Railway Station) — users type anything. Some user data exists, some does not. So user input needs heavy-duty validation, and because results are expected immediately after input, it needs faster processing.

  • First party data — collected by your own company from your own users and systems (your customers' purchase history).
  • Second party data — another organization's first-party data that they share or sell directly to you (a partner's catalog).
  • Third party data — aggregated data bought from data brokers or platforms (demographic segments for advertising).

The intranet analogy maps the ownership spectrum: an intranet is only the company (first party), an extranet extends to partners (second party), and the internet is hybrid — partly accessible to the public (third party and open data).

User input is the special, uncontrollable category: data explicitly given by users — text, images, tabular data. The professor's trivia proof that users type anything: the longest railway station name in the world is in Wales, UK, and the longest in India is the M.G. Ramachandran Central Railway Station. Some user data exists, some does not — it arrives unvalidated, in free form, and in unpredictable volumes. Two consequences: user input needs heavy-duty validation, and because results are expected immediately after input, it needs faster processing.

7.10.4 Automated Data, User Behavior, and Regulations

Automated data is the easy kind: logs record the systems — who did what, when. On your own machine you can open the Task Manager and look at app history, or the Event Viewer for application logs; you can export that data and process it. Logs get processed fast — Oracle logs, for example, are captured quickly depending on the checkpoint, in milliseconds. User behavior data is about what people actually do: when their mind changes, they click, they scroll, they zoom, they look for suggestions, they ignore pop-ups — and sometimes a good offer pops up and we miss it. You check whether the user is always clicking, always scrolling, whether they give attention to pop-ups, how much time they spend.

Then come the legal questions: is it legal to capture the user location? Healthcare data and nuclear data have regulations — patient data cannot be exposed, so we have HIPAA compliance; payment card information and data has PCI-DSS, so they mask everything. Regulations control what data you may collect, store, and use.

  • Automated data — system-generated logs: who did what, when. The easy kind, because it is regular and structured. On your own machine, the Task Manager's app history and the Event Viewer's application logs are exactly this; you can export and process them. Logs are processed fast — Oracle logs are captured within milliseconds depending on the checkpoint.
  • User behavior data — what people actually do, not what they say: clicking, scrolling, zooming, looking for suggestions, ignoring pop-ups. The analyst's questions: is the user always clicking or always scrolling, do they pay attention to pop-ups, how much time do they spend? Note the professor's aside — sometimes a good offer pops up and we miss it — behavior data records what really happened, not what the user intended.
  • Regulations — the legal boundary on collection, storage, and use. Healthcare data is protected by HIPAA compliance — patient data cannot be exposed. Payment card data falls under PCI-DSS, which requires masking. The question "is it legal to capture the user location?" is asked before the pipeline is built, not after.

7.10.5 Storage Formats and Data Systems

Data generation systems can produce data in many formats, and those systems could even be the outputs of other systems. The storage options:

  • SQL databases.
  • NoSQL — strictly no structured query language: key-value stores, document stores (MongoDB is a document database), column databases, and search databases.
  • Time series databases — data saved by time; Windy.com uses that kind of data.
  • GIS databases — geographic information system databases.
  • Graph databases and graph query languages — Neo4j is one of the most important graph databases; when you are trying to create a lot of relations, especially complex and heterogeneous relationships, graph databases are very powerful where SQL does not work effectively.
Storage system Shape of data it fits Named example
SQL databases Tables with fixed schemas, joins, transactions Any relational store
NoSQL No strict query language — key-value, document, column, search MongoDB (document database)
Time series databases Values saved by time Windy.com's weather data
GIS databases Geographic information systems Maps and location data
Graph databases Many complex, heterogeneous relationships Neo4j — powerful where SQL does not work effectively

The rule of thumb: SQL is the default for structured tabular data; document stores like MongoDB handle flexible, self-describing records; time series databases serve sensor and weather data (Windy.com); GIS databases serve location data; and graph databases such as Neo4j win when the value lives in the relationships — complex, heterogeneous relationship structures that SQL joins express poorly.

7.10.6 APIs, Webhooks, gRPC, and GIS Services

Data can be collected through APIs. The PNR status app, the Google live flight tracker that shows exactly where a flight is, and the railway tracker apps all push your input — the location, your longitude and latitude — to an API that pulls the data back. Open source libraries exist, and many SaaS products can generate data. Webhooks are the streaming-friendly variant:

Q: What is a webhook? A: Webhooks are mostly used for streaming services. You basically keep yourself connected to that particular service — you stay hooked. A webhook keeps you connected: it is like WhatsApp — your system is already hooked, and data is collected and read automatically — what time you woke up, when you turned on your mobile, when you saw the messages are all captured. Webhooks deliver events to you without you asking.

RPC and gRPC are also used — Google has deployed a lot of remote procedures, and you can use gRPC. For geographic information, the Indian government has built a separate service: ArcGIS for India, used for maps and location-based services; its village geo-proximity API lets you integrate geographic data into your own application, and one former student used it in a company for satellite-based maps.

The data-collection toolbox, in one view:

  • APIs — request-driven: your app pushes input (a PNR number, your longitude and latitude) to an API, and the API pulls back the data. The PNR status app, the Google live flight tracker, and railway tracker apps all work this way. Open source libraries and many SaaS products generate data through the same channel.
  • Webhooks — event-driven, the streaming-friendly variant: instead of asking repeatedly, you keep yourself connected to the service — you stay hooked — and the service delivers events to you automatically. WhatsApp is the everyday example: the connection is already open, and data — when you woke up, when you turned on your mobile, when you saw the messages — is collected and read automatically. The mental model: API = you ask; webhook = the service tells you.
  • RPC and gRPC — remote procedure calls let one program invoke another's functions across a network; Google has deployed a great many remote procedures, and gRPC is the modern, high-performance protocol to use.
  • GIS services — geographic information services: the Indian government's ArcGIS for India provides maps and location-based services, and its village geo-proximity API lets developers integrate geographic data into their own applications — one former student used it in a company for satellite-based maps.

7.10.7 Third-Party Data and Data as a Currency

Some people share data publicly, some privately — you can have data sharing through third-party data sources. The US government publishes statistics about the labor market; NASA publishes lots of data for researchers; Facebook also shares data. Data is a new currency now — a lot of people on the black market supply large volumes of data to many customers. Data also arrives through message queues, through streaming — subscribe to events, as in the publisher-subscriber pattern — and through the webhook-style hooks described above.

The third-party landscape: open data published for public use — US government labor-market statistics, NASA research data, and data shared by Facebook. The dark side of data's value: data is a new currency, and a black market supplies large volumes of stolen data to many customers. Delivery channels beyond direct download: message queues, streaming subscriptions (the publisher-subscriber pattern from 7.9.2), and webhook-style hooks.

Recap and bridge

Every ML system is fed by many data sources, and the exam skill is classification: structured (Netflix's billion ratings), semi-structured (social and HTML data), and unstructured (search text); first, second, and third party data; user input, automated logs, and behavior data — each with its own validation and processing needs; regulated by HIPAA for healthcare and PCI-DSS for payment cards; and arriving through APIs, webhooks, gRPC, and streaming. The final topic ties the whole picture together: the ingestion path and the six-layer pipeline design.

Real-world connection: Netflix's architecture is documented publicly and is the textbook example of multi-source ML; the Flipkart review-mining pipeline is the same NLP pattern used across e-commerce for product intelligence; compliance regimes (HIPAA, PCI-DSS) are enforced with data masking and access logging in every regulated data platform; and the PNR/flight-tracker API model is the everyday pattern behind government and transport data services worldwide.

7.11 Data Ingestion and Pipeline Layers

Data ingestion was covered in an earlier session, so this is the recap plus the architecture. You collect the data — data comes from sources — you do the data collection and ingest the data, and then you decide where it lands: a cloud data warehouse, a cloud data lake, or a lakehouse. Once that is done, you start the data transformation steps.

Hook — the exam's 8-mark question

The professor flags this material directly: there is a set question on designing the data layers — layer 1 through layer 6 — from a scenario, worth about 8 marks. This section is that answer, written down in advance: the full data store and data pipeline flow from sources to governance.

7.11.1 The Ingestion Path

The full flow runs: data sources to data ingestion, to the ETL or ELT layer, to the cloud data warehouse or data lakehouse, to data transformation, then you build a BI layer, then a data science layer, then data governance — and the governance layer can be an autonomous layer, depending on the company: some companies care about data privacy, some care about governance.

The complete data store and data pipeline flow, in order:

  1. Data sources — the systems from section 7.10: databases, APIs, webhooks, logs, user input, third-party feeds.
  2. Data ingestion — data collection: capturing the data and moving it off the source systems (the earlier-session material: batch, streaming, push, pull, CDC).
  3. ETL or ELT layer — the extract-transform-load (or load-then-transform) processing that shapes the raw data.
  4. Cloud data warehouse, data lake, or lakehouse — the landing zone: warehouse for structured analytics, lake for raw files, lakehouse combining both.
  5. Data transformation — modeling, cleaning, and feature preparation for the consumers.
  6. BI layer — dashboards and reporting for business users.
  7. Data science layer — the ML lifecycle from 7.1: features, models, evaluation, deployment.
  8. Data governance — the cross-cutting layer that can be autonomous: some companies care about data privacy first, some about governance; either way it sits over the whole flow.

7.11.2 Designing the Data Layers

Exam note: there is a set question from this material — you will be asked to design the layers: do you have layer 1, layer 2, layer 3, then layer 4, 5, 6? You have to design your own layers based on the scenario, and the question is worth about 8 marks. Related questions cover the types of data — discrete data versus continuous data — and the big data characteristics: describing big data, possibly as an easy match-the-following question. The professor's emphasis is strong: remember the entire data store and data pipeline flow — data sources to ingestion, ETL/ELT layer, cloud data warehouse or data lakehouse, data transformation, BI layer, data science layer, data governance. This is very, very important.

A reusable six-layer answer

The professor's flow decomposes into six designable layers that you can adapt to any scenario:

  1. Layer 1 — Data sources and ingestion. Name the sources from the scenario (transactional databases, APIs, logs, IoT sensors) and how data is collected (batch, streaming, webhooks).
  2. Layer 2 — ETL/ELT. The processing that extracts, transforms (or transforms after load), and lands the data.
  3. Layer 3 — Storage. The cloud data warehouse, data lake, or lakehouse where the data lands.
  4. Layer 4 — Data transformation and serving. The transformation steps plus the BI layer that serves dashboards and reports.
  5. Layer 5 — Data science layer. Feature engineering and the ML lifecycle — models trained, evaluated, deployed (sections 7.4–7.9).
  6. Layer 6 — Data governance. Lineage, contracts, privacy, and compliance — an autonomous layer that can be owned separately.

The skill the exam tests: given a scenario, map its specific pieces onto these six positions, name what each layer does, and justify why it sits where it does.

Two related exam topics:

  • Discrete versus continuous data. Discrete data takes separate, countable values (number of customers, churn yes/no, star ratings); continuous data can take any value in a range (temperature, price, time). The distinction decides which models and chart types apply.
  • Big data characteristics. The classic description of big data — possibly as an easy match-the-following question — is the V's: volume (amount), velocity (speed of arrival), variety (types and formats), plus the extended V's (veracity, value, and others) from the earlier sessions on big data.

7.11.3 Deployment Options and Governance

Deploying the pipelines themselves can be done in different ways: code it yourself manually; build or use a single-purpose tool; use a data integration platform; or go with the DataOps approach. The pipeline closes with data contract, lineage, and governance — knowing what data was promised, where it came from, and who governs it.

Four ways to deploy the pipeline:

  • Manual coding — build and run the pipeline yourself, script by script. Maximum control, maximum maintenance.
  • Single-purpose tools — one tool for one job (a scheduler, an orchestration tool, a transformation engine).
  • Data integration platforms — platforms that handle the whole integration workflow with connectors, monitoring, and management built in.
  • DataOps approach — applying DevOps discipline (automation, CI/CD, monitoring, collaboration) to the data pipeline, the philosophy the earlier sessions introduced.

The pipeline closes with three governance artifacts: the data contract (what data was promised — schema, quality, freshness), lineage (where it came from — traceable from source to model, the lineage of 7.4.3), and governance (who governs it — ownership, access, privacy, compliance). Every layer of the flow is wrapped by this governance layer, which may be autonomous depending on the company.

Pitfalls in designing the layers

  • Forgetting the sources. A layer design that starts at ingestion is missing layer 1 — the exam scenario will name specific sources, and they belong in the answer.
  • Mixing BI and data science. The BI layer serves dashboards to business users; the data science layer serves models. They consume transformed data differently and are separate layers.
  • Leaving governance until the end as an afterthought. Governance is an autonomous layer over the entire flow — the professor's point that some companies care about privacy, some about governance — not a footnote after deployment.
  • Ignoring the data types in the scenario. Whether the scenario's data is discrete or continuous, and whether it is big data by the V-characteristics, changes what you design into each layer.

Recap and bridge

Data ingestion is the recap of the whole lecture in one flow: sources → ingestion → ETL/ELT → cloud warehouse/lake/lakehouse → transformation → BI layer → data science layer → data governance (possibly autonomous). The exam question asks you to design layers 1 through 6 from a scenario — worth about 8 marks — alongside discrete versus continuous data and the big data characteristics. That flow, with the lifecycle from 7.1 and the monitoring loop from 7.8, is the complete mental model of data management for machine learning.

Real-world connection: this layered flow is exactly the modern data stack deployed in industry — Fivetran and Airbyte for ingestion, dbt for transformation, Snowflake, BigQuery, and Databricks for the warehouse/lakehouse, Looker and Power BI for the BI layer, MLflow and SageMaker for the data science layer, and Collibra or DataHub for governance — and DataOps platforms orchestrate the whole stack with Airflow or Dagster. The six-layer answer to the exam question is also the standard diagram a data engineer draws on day one of a new architecture.

Exam Guidance Summary

Exam note — deployment strategies (Section 7.8)

A question on deployment strategy is plausible — which strategy you would follow, maybe the lowest-cost strategy, and which environment — the blue-green, canary, A/B testing, and shadow deployment options. This material is worth capturing, and the strategy table is worth a screenshot.

Exam note — designing the data layers (Section 7.11)

Expect a question where you design the layers — layer 1 through layer 6 — based on a scenario; it is worth about 8 marks. Related topics: discrete versus continuous data, and the big data characteristics, possibly as a match-the-following question.

Exam note — data sources case study (Section 7.10)

A case study question may ask you to identify the data source and the type of data — structured, semi-structured, or unstructured.

  • Question format. The past-year question paper is shared in the course folder; this term's questions will probably be different, but mostly questions give a scenario and ask you to come up with an answer.
  • Study emphasis. The entire data store and data pipeline flow — data sources, ingestion, ETL/ELT layer, cloud data warehouse or lakehouse, data transformation, BI layer, data science layer, data governance — is very important; remember it.
  • Review advice (Section 7.7). In project reviews, do the literature review and try multiple algorithms before choosing — same discipline helps in the exam.
  • Exam logistics. The exam is in person — there is no online option — and international students were given extra options (multiple dates and locations) in the professor's other papers, since flexibility was offered for students affected by travel problems.

The whole lecture compresses into four exam-ready answers:

  1. Deployment strategy question — name the strategy (blue-green, canary, A/B, shadow), say which environment it uses, and justify with cost and risk.
  2. Layer design question — write the six layers from the scenario: sources and ingestion, ETL/ELT, storage (warehouse/lake/lakehouse), transformation and BI, data science, governance.
  3. Case study question — for each data source, name the source and classify the data as structured, semi-structured, or unstructured.
  4. Big data question — state the big data characteristics (the V's) and the discrete-versus-continuous data distinction.

Key Industry Applications

  • Cloud deployment. Models and pipelines are deployed on AWS, Google Cloud, and Azure, or on websites and mobile apps.
  • Model persistence and versioning. pickle and joblib save trained models (model.pkl); GitHub, ClearCase, SCCS, VCS, and RCS are the version-control lineage of model registries; Oracle point-in-time recovery with RPO is the database analog of ML lineage tracking.
  • Validation tooling. Scikit-learn provides n-fold cross-validation with cross-validation scores for comparing models.
  • Model interchange. PMML, PFA, ONNX, H2O (POJO and MOJO), and TensorFlow and PyTorch (.pt) files make models language agnostic; REST APIs serve offline predictions.
  • Recommendation systems. Netflix's recommendation system consumes billions of ratings, popularity metrics, queue patterns, metadata, and social data; the Flipkart and Amazon review mining program shows unstructured review text becoming semi-structured through HTML parsing and tokenization, summarized in word clouds with unigrams and bigrams.
  • Data systems. MongoDB as a document database, Neo4j for graph and heterogeneous relationship queries, Windy.com-style time series data, and GIS databases like ArcGIS for India with its village geo-proximity API.
  • Real-time data integration. PNR status apps, live flight trackers, and railway tracker apps work through APIs; webhooks keep systems connected so events stream in automatically, the WhatsApp-style hook; gRPC from Google; publisher-subscriber feeds for Instagram, Facebook, and YouTube.
  • Compliance. HIPAA governs healthcare data and PCI-DSS governs payment card data, with masking applied to card information.
  • Open and third-party data. US government labor statistics, NASA research data, and Facebook data are shared sources; data has become a currency, including on the black market.
  • No-code and low-code. AI assistants and no-code platforms such as GINNI AI, ChatGPT, Perplexity, and Copilot build pipelines quickly with prompts.

The industry picture behind the lecture: the same stack appears at every modern data-driven company — a cloud platform (AWS, Google Cloud, Azure) hosting the pipeline; a feature store and model registry keeping features and models versioned; Scikit-learn and cross-validation for honest evaluation; portable model formats (PMML, PFA, ONNX, H2O POJO/MOJO, TensorFlow and PyTorch .pt) moving models between languages; recommendation and review-mining pipelines (Netflix, Flipkart, Amazon) turning structured ratings and unstructured text into predictions; data systems matched to the data (MongoDB, Neo4j, time series, GIS); real-time integration through APIs, webhooks, gRPC, and publisher-subscriber feeds; compliance enforced by HIPAA and PCI-DSS; open data from NASA and government sources; and no-code platforms plus AI assistants (GINNI AI, ChatGPT, Perplexity, Copilot) compressing pipeline construction to minutes.

DMML Lecture 7 notes · The Machine Learning Lifecycle: From Business Understanding to Model Serving

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

Sections Breakdown

17.1 The CRISP-DM Lifecycle

The six-stage process of business understanding, data understanding, data preparation, modeling, evaluation, and deployment, and the golden rule that each stage only works when the earlier ones worked.

27.2 Post-Mortem Analysis and Unbiased Analytics

The two-officer story and what it teaches about analytics: evidence over emotion, always looking for alternatives, and staying unbiased and tool- and model-agnostic like a fair judge.

37.3 Problem Framing, Confusion Matrix, and Error Costs

Setting success criteria, observable quantities, and error costs, plus the four-cell confusion matrix vocabulary for counting the ways a model can be wrong.

47.4 Feature Stores, Model Registry, and the Drift Feedback Loop

Online and offline feature stores, saving models with pickle and joblib, versioning in a model registry with lineage, and the alarm-manager drift feedback loop.

57.5 Data Pre-processing and Sampling

The toolkit of cleaning, imputation, outlier and duplicate removal, random and stratified sampling, train/validate/test partitioning against leakage, and the z-score and min-max scaling formulas.

67.6 Feature Selection Exercise: Customer Churn Prediction

A live exercise where variance identifies low-information features but removal is a business judgment, ending with PCA reducing the feature set to five.

77.7 Model Development, Algorithm Selection, and Hyperparameters

Literature review and multi-algorithm comparison, RMSE validation, hyperparameters as hidden settings, n-fold cross-validation, and portable model serialization formats.

87.8 Deployment Strategies and the Inference Pipeline

Blue-green, canary, A/B testing, and shadow deployment, plus the inference pipeline of trainer, scheduler, drift detection, and XAI with the model update pipeline.

97.9 Model Serving Architecture Patterns

The five serving patterns: model as a service, model as dependency, pre-compute, model on demand behind a message broker, and hybrid serving with federated learning.

107.10 Data Sources and Data Types

The Netflix case study, structured versus semi-structured versus unstructured data, first/second/third party data, regulations, storage systems, and collection channels.

117.11 Data Ingestion and Pipeline Layers

The ingestion path from sources to governance and the reusable six-layer design answer to the exam's scenario question, plus deployment options and governance artifacts.

Postgraduate students in Machine Learning and Data Management

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.

The CRISP-DM Lifecycle

Must-know: The CRISP-DM six-stage lifecycle in order: business understanding, data understanding, data preparation, modeling, evaluation, deployment. A model is only effective with good business understanding, good data understanding, and good data preparation (garbage in, garbage out).

⚠️ Top pitfall: Skipping business understanding or confusing the business goal with the data mining goal; treating deployment as the end instead of the start of monitoring.

Self-check: What are the four activities of data understanding, and what report does each produce?

Connects to: Post-Mortem Analysis and Unbiased Analytics, Problem Framing, Confusion Matrix, and Error Costs.

Post-Mortem Analysis and Unbiased Analytics

Must-know: A post-mortem is the final review of what happened, what went well, and what went wrong. Its value depends on the author staying objective: always look for alternatives, and keep analytics unbiased and agnostic (tool agnostic and model agnostic) — the evidence carries the truth, like a fair judge.

⚠️ Top pitfall: Coming into the analysis already decided — the conclusions never surprise you, and the post-mortem only confirms prior belief.

Self-check: What two lessons does the Vietnam war story teach about analytics?

Connects to: The CRISP-DM Lifecycle, Problem Framing, Confusion Matrix, and Error Costs, Feature Stores, Model Registry, and the Drift Feedback Loop.

Problem Framing, Confusion Matrix, and Error Costs

Must-know: Confusion matrix cells: true positive, false negative (type 2 error), false positive (type 1 error), true negative. A wrong prediction is not free: evaluate cost of data acquisition, training, inference, and wrong predictions. Success criteria must be quantitative (accuracy, counts), not qualitative impressions.

⚠️ Top pitfall: Using qualitative success criteria ('model works well') instead of observable quantitative metrics; ignoring that false positives and false negatives carry different costs.

Self-check: If the model predicts Corona positive and the person does not have it, which cell of the confusion matrix is that, and what type of error?

Connects to: Post-Mortem Analysis and Unbiased Analytics, Feature Stores, Model Registry, and the Drift Feedback Loop, Model Development, Algorithm Selection, and Hyperparameters.

Feature Stores, Model Registry, and the Drift Feedback Loop

Must-know: After pre-processing, store the features online (low latency for real-time inference) and offline (duplication/deduplication); check feature correlations to decide what to drop; save models with pickle or joblib (model.pkl) and version them in a model registry/GitHub (1.0 to 1.2); the model drift feedback loop — alarm manager flags drift, retraining is scheduled, model relearns.

⚠️ Top pitfall: Ignoring drift until business metrics drop; retraining without re-evaluating the retrained model before redeploying.

Self-check: Why store features both online and offline? What are pickle and joblib used for?

Connects to: Problem Framing, Confusion Matrix, and Error Costs, Data Pre-processing and Sampling, Deployment Strategies and the Inference Pipeline.

Data Pre-processing and Sampling

Must-know: Imputation replaces missing data with the mean or another value; stratified sampling samples by strata (random is the default); partition train/validate/test blocks overfitting and lets us evaluate accurately, removing duplicates BEFORE the split to prevent data leakage; z-score normalization z = (x - mu)/sigma; min-max normalization x' = (x - min(x))/(max(x) - min(x)).

\[z = \frac{x - \mu}{\sigma}\] and \[x' = \frac{x - \min(x)}{\max(x) - \min(x)}\]

⚠️ Top pitfall: Leaving duplicates in the data when splitting — duplicates in both train and holdout sets are the classic leakage channel; computing the scaling statistics from the whole dataset including the test set.

Self-check: A column has min 60 and max 90. What does min-max normalization map the value 80 to?

Connects to: Feature Stores, Model Registry, and the Drift Feedback Loop, Feature Selection Exercise: Customer Churn Prediction, Model Development, Algorithm Selection, and Hyperparameters.

Feature Selection Exercise: Customer Churn Prediction

Must-know: Variance Var(X) = (1/n) sum (x_i - x-bar)^2 measures spread around the mean; low-variance features are removal candidates, but irrelevance is a business question — age and gender enable prescriptive analytics and root-cause analysis, and payment method matters because SBI UPI payments get rejected about 70% of the time. The exercise reduces features to five with PCA.

\[\operatorname{Var}(X) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2\]

⚠️ Top pitfall: Dropping features because they look irrelevant at first glance; a feature with low variance can still explain churn if it identifies a frustrated cohort.

Self-check: Why did the professor keep the payment method feature in the churn exercise?

Connects to: Data Pre-processing and Sampling, Model Development, Algorithm Selection, and Hyperparameters.

Model Development, Algorithm Selection, and Hyperparameters

Must-know: RMSE = sqrt((1/n) sum (y_i - y-hat_i)^2) — the professor's example: predicted 90, actual 80, error 10. Hyperparameters (step size, epochs, error rates) are hidden settings you cannot observe directly and must tune; known parameters are directly answerable. Train many models with n-fold cross-validation, average the per-fold scores, and watch the fold-to-fold variation for overfitting.

\[\text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2}\] and \[\mu_{\text{CV}} = \frac{1}{k}\sum_{i=1}^{k} s_i\]

⚠️ Top pitfall: Reading RMSE as the plain average error (squaring lets one large error dominate); trusting a cross-validation average without checking the fold spread; taking faster steps (too-large step size) causes mistakes.

Self-check: If a model predicts 90 and the actual value is 80, what is the squared error and the RMSE for that single sample?

Connects to: Data Pre-processing and Sampling, Feature Selection Exercise: Customer Churn Prediction, Deployment Strategies and the Inference Pipeline.

Deployment Strategies and the Inference Pipeline

Must-know: Blue-green: two identical environments, traffic switches over after green passes testing. Canary: new release to a small user group first. A/B testing: larger group, longer time scale (days to weeks), users partitioned per version. Shadow: new version validated on live traffic while the old one keeps serving. Alarm manager identifies violations and launches the model update pipeline for a retrain.

⚠️ Top pitfall: Releasing without a rollback path; cutting over without validation; choosing a strategy the infrastructure cannot support; skipping drift detection so model decay goes unnoticed.

Self-check: Which deployment strategy serves the new model on live traffic without users noticing anything?

Connects to: Feature Stores, Model Registry, and the Drift Feedback Loop, Model Development, Algorithm Selection, and Hyperparameters, Model Serving Architecture Patterns.

Model Serving Architecture Patterns

Must-know: Five serving patterns: model as a service (independent service), model as dependency (import inside the app), pre-compute (predictions stored ahead of time), model on demand (loaded at runtime behind a message broker: requests go into a message queue, the event processor reads them, runs predictions, writes answers to an output queue), hybrid serving (federated learning). Instagram/Facebook/YouTube use publisher-subscriber: subscribe and receive notifications.

⚠️ Top pitfall: Guessing a user graph for social platforms instead of seeing the publisher-subscriber update flow; treating pre-compute as suitable for real-time requests it cannot serve.

Self-check: In the message broker architecture, what happens between a prediction request and the prediction answer?

Connects to: Deployment Strategies and the Inference Pipeline, Data Sources and Data Types.

Data Sources and Data Types

Must-know: Structured data: fits rows/columns (Netflix ratings, popularity metrics). Semi-structured: tags/markers, becomes structured once parsed (social media data, HTML). Unstructured: free text (search queries, review text). First/second/third party data by origin. User input needs heavy-duty validation and faster processing. HIPAA for healthcare, PCI-DSS masks payment cards. Webhook keeps you connected; data is collected and read automatically, like WhatsApp.

⚠️ Top pitfall: Misclassifying raw HTML/review text as structured; thinking webhooks are only for streaming services instead of seeing the stay-hooked automatic collection model; forgetting regulations (HIPAA, PCI-DSS) govern collection, storage, and use.

Self-check: In the Netflix case study, which type of data is the search text 'what is the movie recently acted by Kamal Haasan this year'?

Connects to: Model Serving Architecture Patterns, Data Ingestion and Pipeline Layers.

Data Ingestion and Pipeline Layers

Must-know: Full flow: data sources to data ingestion, ETL or ELT layer, cloud data warehouse or lakehouse, data transformation, BI layer, data science layer, data governance (autonomous). Exam set question: design layers 1-6 for a scenario (~8 marks). Related: discrete vs continuous data, big data characteristics (V's). Pipeline deployment: manual, single-purpose tool, data integration platform, DataOps. Pipeline closes with data contract, lineage, governance.

⚠️ Top pitfall: Starting the layer design at ingestion and forgetting the sources; mixing the BI layer with the data science layer; treating governance as an afterthought instead of an autonomous layer.

Self-check: What is the complete data store and data pipeline flow from sources to governance?

Connects to: The CRISP-DM Lifecycle, Feature Stores, Model Registry, and the Drift Feedback Loop, Data Sources and Data Types.

Exam Guidance Summary

Must-know: Four exam-ready answers: deployment strategy (which strategy, lowest cost, which environment), layer design 1-6 from a scenario (~8 marks), case study data source and type (structured/semi-structured/unstructured), big data characteristics and discrete vs continuous data. The full flow — sources, ingestion, ETL/ELT, warehouse/lakehouse, transformation, BI, data science, governance — is very important.

⚠️ Top pitfall: Treating the layer design question without naming the sources, or answering the case study without classifying each data type.

Self-check: Which three exam topics does the professor explicitly flag as likely questions?

Connects to: Deployment Strategies and the Inference Pipeline, Data Sources and Data Types, Data Ingestion and Pipeline Layers.

Key Industry Applications

Must-know: The industry stack: cloud platforms host pipelines; pickle/joblib and version control persist models; cross-validation scores validate; portable formats move models between languages; recommendation systems consume structured ratings and unstructured review text; data systems match the data shape; APIs, webhooks, gRPC, and pub-sub feed real time; HIPAA and PCI-DSS govern regulated data; no-code platforms and AI assistants build pipelines fast.

⚠️ Top pitfall: Naming tools without linking them to the concept they serve (pickle = model persistence, ONNX = language-agnostic exchange, Neo4j = heterogeneous relationships, HIPAA = healthcare data).

Self-check: Which formats make a serialized model usable from Python, Ruby, or any other language?

Connects to: Feature Stores, Model Registry, and the Drift Feedback Loop, Model Development, Algorithm Selection, and Hyperparameters, Model Serving Architecture Patterns, Data Sources and Data Types.

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.