In the previous lesson, artificial intelligence appeared as just one more trend on the radar: platforms that tune themselves. It was deliberately short-changed. AI is not a feature bolted on to data platforms; it is at once their main customer and, increasingly, one of their tools. Massive data made today's AI possible, and AI is changing how that data is built, monitored and queried.

This lesson puts that relationship in order. It places the machine learning you already know within a broader map, reviews what AI does with massive data, builds NovaMarket's fourth pending use case, demand forecasting, and examines, with the same scepticism as the previous lesson, the assistants that write SQL and document tables. It ends with the question that saves the most money: does this problem really need AI?

Big Data and AI: a two-way relationship

flowchart LR
    BD["Big Data<br>storage, processing,<br>quality, governance"]
    IA["Artificial intelligence<br>models"]
    BD -->|"1. Training data,<br>features, evaluation"| IA
    IA -->|"2. Predictions that return<br>to the lake as new data"| BD
    IA -->|"3. Help in managing the data:<br>cataloguing, monitoring, optimising, querying"| BD

Data feeds AI. The ideas on which neural networks rest are decades old. What changed was the availability of three things at once: data in enormous quantities, cheap compute to process it and the distributed infrastructure you have studied in this course. A model is, to a large extent, a distillation of its training data.

AI produces data. Every prediction (a segment, a fraud score, a forecast) is a new piece of data that returns to the lake, is used in decisions and must be governed like any other. gold/customer_segments is exactly that.

AI helps manage data. This is the most recent direction: models that document tables, detect anomalies or translate a question into SQL. It is covered further down.

A practical consequence follows for anyone who works with data: the platform is the foundation of any AI project. An organisation without reliable, accessible and governed data does not have an AI problem to solve; it still has a data problem.

AI, machine learning and deep learning

The three terms are used as synonyms, and they are not. Each one contains the next:

flowchart TB
    subgraph IA["Artificial intelligence: systems that perform tasks we associate with intelligence"]
        subgraph ML["Machine learning: they learn from examples instead of following written rules"]
            subgraph DL["Deep learning: neural networks with many layers"]
                GEN["Generative AI: models that produce text, images or code"]
            end
        end
    end
  • Artificial intelligence is the broadest term, and it includes techniques that do not learn from data, such as rule-based systems. The fraud rule from lesson 03-05 ("three purchases in ten minutes") would be AI in the classical sense.
  • Machine learning is what you practised in lesson 04-03: K-Means, logistic regression, ALS. It is often called classical ML, and it still solves most problems involving tabular data.
  • Deep learning uses neural networks with many layers. Its fundamental difference is that it learns the features by itself. In predict_purchase.py it was you who decided which variables to calculate (num_views, start_hour…); a deep network receives the pixels of an image or the words of a text and discovers which patterns matter.
  • Generative AI is the branch of deep learning that produces content. It has a lesson of its own, 08-03.

Why deep learning needs massive data and GPUs

A deep network has millions or billions of parameters, numbers that are adjusted during training. Adjusting so many without the model simply memorising requires a huge number of examples; with little data, a classical model usually performs as well or better. And training it consists of repeating, millions of times, operations on matrices: exactly the kind of calculation that a GPU (graphics processing unit) runs in parallel far more efficiently than a conventional processor.

Classical ML Deep learning
Typical data Tables: rows and columns Unstructured: image, text, audio; also long sequences
Features Designed by a person Learnt by the model
Volume needed From thousands to millions of rows Much larger, unless you start from an already trained model
Compute CPU; often a single machine GPU, sometimes many
Explainability High to medium Low
Role of Big Data Calculating the features (Spark) Preparing, storing and serving enormous volumes of raw data

The caveat in the third row is important: today almost nobody trains a deep network from scratch. You start from a pre-trained model built by third parties with vast quantities of data, and adapt it or use it as it is. That shifts the work but does not eliminate it: your own data is still what sets one organisation apart from another.

Data-centric AI

For years, improving an AI system meant improving the model: another algorithm, more layers, better hyperparameters. The data-centric AI approach holds that, once the algorithms are good and within everyone's reach, performance is gained above all by improving the data: consistent labels, examples of the hard cases, less noise, better coverage of under-represented groups.

You already have small-scale evidence:

  • In lesson 04-03, the "perfect" model (AUC of 0.976) was perfect because of data leakage, not because of the algorithm. Both the problem and the solution lay in the data.
  • In lesson 07-04, the bias came from a proxy variable and from historical labels, and it was corrected by acting on the data rather than on the model.
  • In lesson 05-05, the sentiment lexicon failed on negations and irony: no tweak to the method could fix it without better examples.

The consequence is that the six quality dimensions from lesson 05-02 are not hygiene before the "real" work: they are the work. In an AI project, an hour spent reviewing labels usually pays off more than an hour spent trying algorithms. And it puts Laura and Marc, not just the data scientists, at the centre of any AI project at NovaMarket.

What AI does with massive data

Area What it does Data it needs At NovaMarket
Computer vision Classifies, detects and describes images and video Labelled images Checking that product photos comply with the guidelines; classifying photos of returns
Language Classifies, extracts, summarises, translates and searches text Text, sometimes labelled Reviews, support emails, product descriptions (lesson 08-03)
Time series and forecasting Estimates future values from the history Long, clean series, calendar, external variables Demand forecasting (below)
Anomaly detection Flags whatever departs from the usual Plenty of "normal" history; few or no labels Fraud; drops in quality in the pipelines
Recommendation Suggests items based on behaviour Customer-product interactions ALS (lesson 04-03), "bought together" (lesson 06-02)

Two of the five areas work with unstructured data, which lesson 01-01 described as most of the world's data and the hardest to exploit. That is deep learning's great novelty for Big Data, and the starting point of the next lesson.

Hands-on: demand forecasting at NovaMarket

Of the four use cases NovaMarket set itself in lesson 01-02, three already have a first solution: the funnel, recommendations and fraud. Demand forecasting is still missing: estimating how many units of each category will be sold, in order to adjust purchases from suppliers and warehouse staffing.

A warning before you start, the same one as in lesson 04-03. The practice data was generated without seasonality or trend: there are no strong weekends, no campaigns and no sales. No model is going to find a pattern that does not exist. The value of the exercise lies in the method, which is identical with real data and has three pieces that almost every failed project leaves out:

  1. Temporal split. In a forecast you cannot split randomly between training and test, as randomSplit did in lesson 04-03: the model would learn from the future to predict the past, which is another form of data leakage. You train on what comes before a date and test on what comes after.
  2. Naive baseline. Before any model, a trivial prediction ("the same as the same day last week"). A model only adds something if it beats it.
  3. A metric the business understands. The MAE (mean absolute error) is expressed in units sold; the MAPE (mean absolute percentage error), as a percentage.

Create ~/novamarket/demand_forecast.py (usual environment; it needs scikit-learn, which you installed in lesson 04-03):

from pathlib import Path

import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from sklearn.linear_model import LinearRegression

LAKE = Path.home() / "novamarket" / "lake"
TEST_START = "2026-06-01"

spark = SparkSession.builder.master("local[*]").appName("demand_forecast").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

# 1. Spark aggregates: units sold per day and category (181 days x 6 categories)
facts = spark.read.parquet(str(LAKE / "gold" / "fact_sales"))
products = spark.read.parquet(str(LAKE / "gold" / "dim_product")).select("product_id", "category")
dates = spark.read.parquet(str(LAKE / "gold" / "dim_date")).select("date_id", "date")
daily = (
    facts.where("status != 'returned'")
    .join(F.broadcast(products), "product_id")
    .join(F.broadcast(dates), "date_id")
    .groupBy("date", "category")
    .agg(F.sum("quantity").alias("units"))
    .toPandas()
)
spark.stop()

# 2. pandas prepares the series: one row per day and category, in time order
daily["date"] = pd.to_datetime(daily["date"])
daily = daily.sort_values(["category", "date"]).reset_index(drop=True)
by_category = daily.groupby("category")["units"]

# Method A (naive baseline): tomorrow the same will be sold as 7 days ago
daily["pred_naive"] = by_category.shift(7)
# Method B: mean of the previous 28 days (shift(1) avoids using the day itself)
daily["pred_moving_avg"] = by_category.transform(lambda s: s.shift(1).rolling(28).mean())

# 3. TEMPORAL split: train on January-May and test on June
training = daily[daily["date"] < TEST_START]
test = daily[daily["date"] >= TEST_START].copy()


# Method C: linear regression with calendar variables
def features(df):
    categories = pd.get_dummies(df["category"], dtype=float)             # level of each category
    days = pd.get_dummies(df["date"].dt.day_of_week, prefix="day", dtype=float)
    days = days.drop(columns="day_0")                                    # Monday is the baseline
    trend = ((df["date"] - pd.Timestamp("2026-01-01")).dt.days / 30).rename("trend")
    return pd.concat([categories, days, trend], axis=1)


model = LinearRegression(fit_intercept=False).fit(features(training),
                                                  training["units"])
test["pred_regression"] = model.predict(features(test))

# 4. Evaluation on June: MAE and MAPE of each method
print(f"Training: {len(training)} rows | Test: {len(test)} rows")
print(f"Mean daily units per category in June: {test['units'].mean():.1f}\n")
for name in ["pred_naive", "pred_moving_avg", "pred_regression"]:
    error = (test["units"] - test[name]).abs()
    mae = error.mean()
    mape = 100 * (error / test["units"]).mean()
    print(f"{name:<18} MAE = {mae:5.2f} units   MAPE = {mape:5.1f}%")

coefficients = pd.Series(model.coef_, index=features(test).columns).round(2)
print("\nRegression coefficients:")
print(coefficients.to_string())

Step by step:

  • Step 1. Spark does the heavy lifting: it joins the 50,107 lines of gold/fact_sales with their dimensions, discards the returns and aggregates. What reaches pandas is 1,086 rows (181 days times 6 categories). It is the rule from lesson 04-01, once again.
  • Step 2. shift(7) shifts the series seven positions within each category: the prediction for a day is the actual value from a week earlier. In the moving average, shift(1) is essential: without it, the mean would include the very day you want to predict.
  • Step 3. The split is a simple date comparison. Methods A and B, moreover, only use data from before the day they predict.
  • Method C. get_dummies turns the category and the day of the week into columns of zeros and ones (what OneHotEncoder did in MLlib). The model learns a level for each category, an adjustment for each day of the week relative to Monday and a monthly trend. fit_intercept=False is used because the category levels already act as the intercept.
  • Step 4. MAE = mean(|actual − predicted|) and MAPE = mean(|actual − predicted| / actual). The MAPE cannot be calculated if any actual value is zero; that does not happen here because the data is aggregated by category, but at product level it would be the norm.
Training: 906 rows | Test: 180 rows
Mean daily units per category in June: 55.5

pred_naive         MAE = 12.32 units   MAPE =  24.0%
pred_moving_avg    MAE =  8.55 units   MAPE =  17.3%
pred_regression    MAE =  8.51 units   MAPE =  17.3%

Regression coefficients:
appliances    51.82
audio         79.97
computing     49.29
home          67.56
phones        50.38
television    47.01
day_1          0.76
day_2          0.47
day_3         -1.94
day_4         -1.27
day_5          1.92
day_6         -0.69
trend         -0.06

Reading the result honestly

  • The naive baseline is the worst, with an error of 12.3 units on a mean of 55.5. Copying a single past day drags along all of its noise.
  • The moving average and the regression tie at around 8.5 units (17%). Averaging removes the noise, and that is all there is to gain.
  • The coefficients explain it. The category levels are clear (audio sells about 80 units a day, television 47), but the day-of-week adjustments do not exceed ±2 units and the trend is practically zero. The model confirms what the EDA in lesson 04-02 had already said: there is no weekly pattern or trend in this data.

What would Marc tell Irene? "With this data, no model beats a simple average of the last four weeks, and the error is around 17% a day per category. It is not worth deploying anything more complex." It is a perfectly valid conclusion, and it can only be reached because there was a baseline.

With real data the story would change: weekly and annual seasonality, campaigns, public holidays, promotions and stock-outs would appear. That is where calendar variables, models specific to time series and, with many series and a long history, deep learning start to make sense. The order of work would be the same: baseline, simple model, and complexity only if the remaining error costs money.

AI applied to data engineering itself

This is the third direction of the relationship, and the one that has changed the team's day-to-day work the most. Many of these functions rely on the language models explained in lesson 08-03.

Application What it does Advantage Risk
Coding assistants Suggest or write PySpark, SQL, tests and DAGs from a description They speed up routine work; they help with APIs you cannot remember Code that runs and is wrong, or that uses non-existent or obsolete functions
Text-to-SQL Translates a natural-language question into a query Brings data closer to people who do not know SQL Choosing the wrong table or definition and giving a plausible, false figure
Automatic cataloguing and documentation Suggests descriptions of tables and columns, tags personal data Tackles the weak spot of every catalogue: nobody fills it in Plausible but inaccurate descriptions; personal data that goes undetected
Quality anomalies Learns the usual behaviour of volumes, nulls and distributions, and warns of deviations Detects problems for which nobody wrote a rule False alarms; alert fatigue
Automatic optimisation Tunes query plans, physical clustering and compute size (lesson 08-01) Less manual tuning Opaque decisions that come at a cost

The common risk has a name: plausible errors. An assistant does not fail like a compiler, with an error message; it fails with a result that is well written, well formatted and wrong. Three rules of use for the NovaMarket team:

  1. What is generated is reviewed and tested just like what is written by hand. Same tests, same code review, same validate_load.py. Whoever adds it to the repository is answerable for it.
  2. The assistant needs context, and context is governance. The three different "conversions" of lesson 04-05 confuse an assistant as much as they confuse a person. The glossary, the dictionary and the semantic layer stop being bureaucracy: they are what allows the answer to be correct.
  3. Be careful what you send. Pasting a schema, a sample of data or an error log into an external service can take personal or confidential data out of the organisation. Only approved tools whose terms have been reviewed (Module 7).

There is a less obvious consequence: to spot a plausible error you have to know. Someone who does not understand a join cannot see that the generated query duplicates rows. These tools multiply the productivity of those who master the fundamentals; for those who do not, they multiply the mistakes. What that means for the data professions is covered in lesson 08-04.

Benefits and challenges

Benefits Technical challenges
Automates repetitive decisions at scale Compute cost: training, and above all serving, large models is expensive; it has to be budgeted as in lesson 05-03
Finds patterns that no rule captures Training data: scarcity of labels, biases, rights over the data
Makes use of unstructured data, previously inaccessible Explainability: the more powerful the model, the harder it is to justify a specific decision
Personalises products and services Maintenance: drift, retraining, monitoring; the MLOps of lesson 08-01
Frees people from mechanical work Dependency: on model providers who change prices, terms and versions

The ethical and legal considerations, that is, bias and fairness, privacy, transparency and the obligations of the EU AI Act according to the level of risk, are those of Module 7 and apply here in full: the more automated and opaque the decision, the more they weigh. Any AI system that affects people must go through the data ethics committee and the compliance review before it is deployed.

Fraud, revisited as an AI system in production

Fraud detection has accompanied the whole course, and it is a good example of how an AI system matures: through layers that add up, not through replacement.

Stage Lesson What it contributes What it lacks
Rules 03-05 Three purchases in ten minutes: immediate, explainable Rigid; fraudsters learn the rule
Model 04-03 Classification with imbalanced classes: patterns no rule captures A model in a notebook does not stop a single order
Operation 08-01 Registry, deployment, drift, retraining —
Safeguards 07-01 to 07-04 Security, legal basis, fairness, human review —
flowchart LR
    T[Shop: payment] --> K[Kafka]
    K --> C["Streaming features<br>(Structured Streaming)"]
    C --> R[(Redis: recent features<br>per customer)]
    T --> S[Scoring service]
    R --> S
    S --> RG{Rules}
    S --> M{Model}
    RG --> D[Decision]
    M --> D
    D -->|Low risk| OK[Accepted]
    D -->|Medium risk| H[Human review]
    D -->|High risk| B[Held]
    H --> E[(Lake: decisions<br>and labels)]
    B --> E
    OK --> E
    E --> EN[Batch training]
    EN --> RM[Model registry]
    RM --> S
    E --> MO[Monitoring:<br>drift, accuracy, fairness]

What the diagram teaches about any AI system in production:

  • The model is one box among twenty. Almost everything else is data engineering: streaming, low-latency storage, the lake, orchestration.
  • Two speeds. Scoring happens online, in milliseconds, with precomputed features; training happens in batch, with the history. It is the Lambda architecture of lesson 01-04, applied to a model.
  • Rules and model coexist. The rules cover the obvious and what regulation requires, and they are explainable; the model covers the subtle.
  • Labels arrive late. That an order was fraudulent is known weeks later, when the claim comes in. Until then only data drift can be monitored.
  • The feedback loop has to be broken. If only the flagged orders are reviewed, the model will never learn from the ones it let through; that is why a random sample is also reviewed (lesson 07-04).
  • The person decides in the grey zone, with the time, information and authority to contradict the model.

For NovaMarket this is, today, a design and not a built system: the rule from lesson 03-05 is still in production, and moving to the model first requires building up reliable labels.

Does this problem need AI?

Most data problems do not need AI, and using it where it is not needed adds cost, opacity and maintenance. A four-rung ladder, climbed only when the previous rung is not enough:

Rung Use it when… Example at NovaMarket
1. SQL query or aggregation The question is about what has already happened and the answer is a calculation Sales by category, funnel, KPIs
2. Written rule The logic can be stated, is stable and must be explainable Three purchases in ten minutes; an order above a certain amount
3. Classical ML You need to predict or group, the data is tabular, there is history (and labels, if it is supervised) and a margin of error is tolerable Segmentation, purchase propensity, demand forecasting
4. Deep learning / generative AI The data is text, image or audio, or the pattern is too complex, and suitable data or a suitable pre-trained model is available Understanding reviews with irony; searching by meaning

And five questions that must be answered "yes" before going beyond rung 2:

Question If the answer is "no"…
Is there a pattern to learn, and data that contains it? No model is possible (the case of the practice data)
Is there a baseline, and does the model beat it by a noticeable margin? Stick with the baseline
Is it acceptable for it to be wrong sometimes, and is it known what happens when it is? Use rules, or add human review
Can the decision be explained to the level required by the customer and by regulation? Choose a simpler model or drop the use case
Will there be someone to maintain it a year from now? Do not deploy it

Common Mistakes and Tips

  • Starting with the model instead of the problem. "We want to use AI" is not a use case. "We want to reduce stock-outs" is.
  • Not having a baseline. Without one, a MAPE of 17% means nothing: you cannot tell whether it is an achievement or what an average would give.
  • Splitting a time series at random. It produces splendid and false metrics.
  • Choosing deep learning for small tabular data. A classical model usually matches it at a fraction of the cost and with far more explainability.
  • Trusting generated SQL because it returns a number. Check it against a known figure, as you did when reconciling gold/monthly_sales with silver/orders_complete in lesson 05-05.
  • Forgetting the cost of serving. Training is paid for once; each prediction, every time.
  • Treating AI as exempt from governance. Predictions are data; models are assets that must be catalogued, versioned and audited.
  • Tip: when someone proposes AI, ask what a person would do with a spreadsheet. If the answer is "the same, only more slowly", a scheduled query may be enough.

Exercises

Exercise 1: which rung?

State the appropriate rung and why: a) finding out how many customers bought for the first time in May; b) blocking orders with a delivery address in a country NovaMarket does not ship to; c) estimating which customers in the "at risk" segment will respond to a coupon; d) automatically classifying the photos customers attach to a return (broken product, damaged packaging, wrong product); e) warning when the daily volume of events deviates from normal.

Exercise 2: another baseline

Add to demand_forecast.py a fourth, even simpler method: always predicting the category's mean units over the training period. Compare its error with the other three and interpret the result.

Exercise 3: reviewing a generated query

Marc asks an assistant for "total sales by channel" and receives this query, which runs without errors:

SELECT o.channel, ROUND(SUM(o.total_amount), 2) AS sales
FROM orders_complete o
JOIN order_lines l ON o.order_id = l.order_id
GROUP BY o.channel;

What error does it contain, how would you detect it without reading the SQL, and how is it corrected?

Solutions

Exercise 1

a) Rung 1: it is a count over the past; a query with MIN(order_date) per customer. b) Rung 2: the logic can be stated in one sentence, is stable and must be explainable. c) Rung 3: a prediction on tabular data; it needs a history of previous campaigns with their results and, since it affects people, a fairness audit. Without that history there is no model: an A/B test (lesson 04-05) would first have to be run to generate it. d) Rung 4: images; the sensible approach is to start from a pre-trained model and evaluate it with a hand-labelled sample. e) Rung 2 to begin with (a threshold on the mean of the last few days, like the rules in quality.py); rung 3 only if the volume has seasonal patterns that a fixed threshold does not capture.

Exercise 2

After calculating test["pred_regression"]:

means = training.groupby("category")["units"].mean()
test["pred_fixed_mean"] = test["category"].map(means)

and "pred_fixed_mean" is added to the list in the evaluation loop:

pred_naive         MAE = 12.32 units   MAPE =  24.0%
pred_moving_avg    MAE =  8.55 units   MAPE =  17.3%
pred_regression    MAE =  8.51 units   MAPE =  17.3%
pred_fixed_mean    MAE =  8.44 units   MAPE =  17.3%

The simplest method of all ties with the others, and even wins by a few hundredths. It is the definitive confirmation that the series is a constant level per category plus noise: there is nothing more to learn. With real data this would not happen (a five-month average would ignore seasonality and trend), but the lesson is general: always try the dumbest thing first. A frequent mistake is to calculate that mean with all the data, June included, which would once again be leakage.

Exercise 3

The join with order_lines multiplies each order by its number of lines, and total_amount is added once per line. An order has about 2.5 lines on average (50,107 lines for 20,000 orders), and the orders with more lines are also those with the highest amounts: the query returns €98.2 million, almost three times the real figure. The query is syntactically perfect and the result looks reasonable: a textbook plausible error.

It is detected by reconciling it with a known figure: the sum across channels must come to €33,550,768.43, the total of silver/orders_complete you calculated in lesson 03-03. If it comes to three times that, something is wrong. The fix is to remove the join, which is not needed:

SELECT channel, ROUND(SUM(total_amount), 2) AS sales
FROM orders_complete
GROUP BY channel;

The underlying defence is the semantic layer from lesson 04-05: if "sales" has a single official definition, neither Marc nor the assistant has to rebuild it every time.

Conclusion

Big Data and AI sustain each other: data is the raw material of models, predictions return to the lake as new data, and AI is beginning to help manage the platform itself. You have placed the machine learning of lesson 04-03 within the map AI ⊃ ML ⊃ deep learning, and you have seen why deep networks need massive data and GPUs, and why, with algorithms within everyone's reach, the advantage lies in data quality. You have built a demand forecast with the three pieces that cannot be missing (temporal split, baseline and an understandable metric) and you have reached an honest conclusion: on data without a pattern, an average is enough. You have examined coding assistants, text-to-SQL and automatic cataloguing with their plausible errors; you have seen fraud as a complete system in which the model is one piece among many; and you have a ladder for deciding when a query is enough, when a rule is, and when a model is needed.

The top rung of that ladder has been left unopened. Generative AI and large language models have appeared in this lesson only in passing, behind the assistants and text-to-SQL, and there is a promise outstanding since lesson 05-05: to handle NovaMarket's reviews with something better than a lexicon of isolated words. The next lesson, Generative AI and Big Data: Unstructured Data, Vectors and RAG, explains how those models work for someone from the data world, what embeddings and vector databases are, and how to build an assistant that answers questions by drawing on the data in the lake.

© Copyright 2026. All rights reserved