Skip to main content
Big Data Analytics

Spark Streaming Output Modes, Watermarking, and Machine Learning Fundamentals

Published: 2026-08-01
Level: postgraduate
Audience: Postgraduate students in Big Data Analytics

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

  • Batch vs. stream processing and data at rest vs. in motion - covered in Lecture 11
  • Apache Kafka and queuing buffers for streaming ingestion - covered in Lecture 11
  • Event time vs. processing time and out-of-order data - covered in Lecture 11
  • D-Streams vs. Structured Streaming evolution - covered in Lecture 11
  • The unbounded-table abstraction - covered in Lecture 11
  • Structured Streaming output modes (Complete, Update, Append) - covered in Lecture 11
  • Watermarking mechanics and state bounding - covered in Lecture 11
  • Spark DataFrames and the DataFrame API - covered in Lecture 10

12.1 Spark Streaming Architecture and Processing Models

Hook — why does "in motion" vs. "at rest" matter at all? Imagine a credit card fraud detector that only checks transactions once a day. The thief's purchase is approved in real time, and the system "catches" it hours later — too late to stop anything. Stream processing exists precisely to analyze each record while it is still moving through the system, before it settles into a database. This section builds the vocabulary (batch vs. stream, D-Streams vs. Structured Streaming, Kafka) that the rest of the lecture uses.

Stream processing is designed to analyze data while it is in motion, before it comes to rest in a persistent database or storage lake. In real-time data architectures, stream processing handles continuous, unbounded streams of incoming records across six major classification categories: sensor data monitoring, financial fraud detection, real-time metrics dashboards, online recommendation engines, traffic management, and security intrusion detection.

Intuition — a river, not a pond. Batch processing is a pond: the water (data) has already collected and stopped moving, so you can scoop up all of it at once and study it at leisure. Stream processing is a river: water flows past your measuring station continuously, and you must take your measurement while it flows. A river-monitoring gauge measures moving water in real time; a laboratory that tests a bottled sample measures resting water after the fact. The analogy breaks in one place: rivers are strictly one-way, but a stream can be replayed or reprocessed from its log, so stream data is recoverable rather than lost forever.

12.1.1 Batch Processing vs. Stream Processing

The fundamental distinction between batch processing and stream processing lies in the state of the data during execution:

  • Batch processing: Computes transformations on historical, bounded datasets that have already reached rest in disk-based storage engines (such as HDFS, S3, or distributed file systems).
  • Stream processing: Computes transformations dynamically on unbounded, real-time data streams in memory before the data arrives at rest.
Dimension Batch Processing Stream Processing
State of the data At rest (stored on disk) In motion (flowing through memory)
Dataset size Bounded — the data is complete and finite Unbounded — new records keep arriving
When results appear After the whole job finishes Continuously, per micro-batch or per event
Latency Minutes to hours Seconds to sub-seconds
Typical storage HDFS, S3, distributed file systems In-memory buffers, message brokers, then sinks
Use case fit Historical reporting, ETL over the full dataset Dashboards, fraud detection, live alerts

When to pick which: if you can wait for the answer and you need the entire dataset in the computation, batch; if the answer must be current and data never stops arriving, stream.

In complex enterprise pipelines, stream processing is rarely used in total isolation. Production systems frequently execute stream-to-static joins, where live event streams are joined against static dimension tables stored at rest (for example, joining a live stream of transaction user IDs with a static user profile database).

Assumptions & scope: Stream processing assumes events arrive continuously and fast enough to justify the machinery. If events trickle in once a day, a batch job is simpler and cheaper. It also assumes the processing engine can keep up with the arrival rate; if the stream outpaces the engine, records backlog and latency balloons. Stream-to-static joins assume the static table is genuinely static for the duration of the join — if the "static" profile table changes frequently, the join results become stale.

12.1.2 Evolution of Spark Streaming APIs

Apache Spark evolved its stream processing model across two distinct API paradigms:

  1. D-Streams (Discretized Streams API): The legacy low-level streaming API built on top of resilient distributed datasets (RDDs). D-Streams process continuous data streams as sequence chunks of mini-batches over small time intervals. However, D-Streams require complex RDD-level code, explicit state management, and separate codebases for batch and streaming pipelines.
  2. Structured Streaming API: The modern high-level streaming engine built directly on the Spark SQL and DataFrame framework. Structured Streaming treats a live data stream as an unbounded input table. As new data arrives, new rows are continuously appended to the unbounded table. Developers interact with stream data using standard DataFrame transformations and SQL queries.

The unbounded table is the mental model for Structured Streaming. A regular DataFrame is a table with a fixed number of rows. An unbounded table is the same idea with an open bottom: rows keep being appended forever as the stream delivers them. Every operation you already know from batch Spark — filter, groupBy, join, select — runs against this endlessly growing table, and the result of the query is itself a continuously updated table that gets written to a sink.

A key advantage of Structured Streaming is unified API parity: code written for batch processing can be converted into stream processing by simply altering the entry reader interface from spark.read to spark.readStream. The downstream transformation, aggregation, and filtering logic remain identical.

Dimension D-Streams (legacy) Structured Streaming (modern)
Programming model RDD-level, low-level DataFrame / SQL, high-level
Mental model Sequence of mini-batches Unbounded input table
State management Explicit, manual Automatic with watermarking
Batch vs. stream code Two separate codebases One codebase (spark.readspark.readStream)
API maturity Legacy, less active development Current recommended engine

Pitfalls:

  • Thinking D-Streams are still the default: D-Streams predate Structured Streaming; new work should use the DataFrame-based API unless a specific legacy integration forces D-Streams.
  • Forgetting that "stream" still means micro-batches internally: Structured Streaming processes in small increments of data, so a "real-time" result is really near-real-time, arriving within a trigger interval.
  • Assuming all DataFrame operations are stream-safe: a handful of operations (for example some kinds of joins and aggregations without watermarks) are restricted in streaming mode, and the engine rejects them at runtime rather than silently misbehaving.

Recap + bridge: Stream processing analyzes data while it moves; Spark's modern Structured Streaming API models the stream as an unbounded table and reuses the batch DataFrame API. Knowing how a streaming query writes its results — through output modes — is the next question, and that is exactly where the three output modes (Complete, Update, Append) come in.

12.1.3 Integration with Message Brokers

In modern big data architectures, Apache Kafka serves as the primary ingestion backbone for stream processing. Kafka clusters act as decoupled distributed message buffers, connecting hundreds of heterogeneous data sources to downstream compute engines. Spark Structured Streaming integrates seamlessly with Kafka, consuming partitions in parallel and enabling seamless end-to-end fault tolerance, exact-once processing semantics, and scalable stream ingestion.

Why a broker in the middle? Think of Kafka as the shared mailbox between producers and consumers. Hundreds of source systems (apps, sensors, databases) drop messages into the mailbox; downstream engines (Spark, Flink, and others) read from it at their own pace. The mailbox decouples the two sides: a producer does not need to know who is reading, and a slow consumer does not slow down a fast producer. Because Kafka retains messages on disk for a configured period, a consumer can even re-read them — which is what makes replay and fault tolerance possible.

Real-world: Apache Kafka is the de facto standard streaming ingestion buffer in industry, feeding live events into Spark Structured Streaming for fraud detection, metrics aggregation, and clickstream analytics. The exact-once semantics matter in finance: if a payment event is processed twice, money is double-counted; Kafka plus Structured Streaming's checkpointing is designed to prevent exactly that.

Recap: Spark consumes from Kafka (and other sources) and processes the data as an unbounded table. The next section answers the question: when a streaming aggregation produces results, which rows does the engine write out at each trigger — and that choice is made by selecting an output mode.


12.2 Structured Streaming Output Modes

Hook — the engine computed results, but which rows should it actually send out? A streaming word-count query keeps an internal result table that grows and changes with every micro-batch. When the engine writes that table to a sink (Kafka, a database, or files), it must decide how much to write and how often. That decision is the output mode — and picking the wrong one either floods your sink with redundant data or breaks your storage format entirely.

When writing the results of streaming aggregations or queries to external sinks (such as Kafka, databases, or file storage), Structured Streaming provides three distinct output modes. The output mode defines how much accumulated state and which result rows are written to the sink during each trigger execution.

12.2.1 Complete Output Mode

In Complete Mode, the entire updated result table is written to the sink at every trigger interval. The engine retains all historical aggregate state across all micro-batches and re-emits the full cumulative table state upon receiving new data.

Intuition — rewriting the whole whiteboard. Imagine a teacher keeping a running tally of how many times each student answered a question. In Complete Mode, after every new answer the teacher erases the entire board and rewrites every student's count, even the ones that did not change. Downstream readers always see the full, current picture — at the cost of re-sending everything, every time.

  • Use case: Complete mode is ideal for real-time summary dashboards or metrics counters where downstream clients require a full state refresh on every query execution (e.g., displaying the top 10 running counters on a web dashboard).
  • Resource implications: Because state accumulates continuously and the entire table is outputted repeatedly, complete mode requires sufficient memory to store all unique key states over time.

12.2.1.1 Worked Computation — Complete Mode Word Count Walkthrough

Consider a real-time word counting pipeline configured in Complete Mode across three consecutive micro-batch trigger timestamps \(t_1, t_2, t_3\):

  1. At Timestamp \(t_1\): Input micro-batch contains text records (cat: 1, dog: 3).
  • Engine maintains internal aggregate table state.
  • Output written to Sink:
Word Count
cat 1
dog 3
  1. At Timestamp \(t_2\): New input micro-batch arrives with records (owl: 1, cat: 1).
  • The engine updates the internal aggregate count for cat (\(1 + 1 = 2\)) and adds new entry owl: 1.
  • Output written to Sink (entire cumulative table state is re-written, including unchanged dog count):
Word Count
cat 2
dog 3
owl 1
  1. At Timestamp \(t_3\): New input micro-batch arrives with records (dog: 1, owl: 1).
  • The engine updates dog count (\(3 + 1 = 4\)) and owl count (\(1 + 1 = 2\)). cat receives no new occurrences in this micro-batch.
  • Output written to Sink (the full updated table is written once again):
Word Count
cat 2
dog 4
owl 2

Worked example — sense-checking Complete Mode. Run through the three triggers as a running tally:

  • At \(t_1\): the micro-batch contributes cat: 1 and dog: 3. Total so far: cat = 1, dog = 3. Output table has exactly these two rows.
  • At \(t_2\): add owl: 1 and cat: 1 to the tally. Totals: cat = 1 + 1 = 2, dog = 3, owl = 1. The output re-sends all three rows — including dog = 3, which did not change.
  • At \(t_3\): add dog: 1 and owl: 1. Totals: cat = 2, dog = 3 + 1 = 4, owl = 1 + 1 = 2. Output re-sends all three rows again.

Notice the signature of Complete Mode: dog appears in the output at every trigger even though it only changed at \(t_3\). Sense-check: every output table is exactly the full cumulative state, so a dashboard reading any single output sees the correct running totals with no merging needed.

12.2.2 Update Output Mode

In Update Mode, only the specific rows that have been modified or added since the previous trigger execution are written to the sink. Rows that remain unchanged across micro-batches are omitted from the output.

Intuition — telling your manager only what changed. Instead of re-sending the entire status report, you send only the lines that actually changed since the last report. Colleagues who already have yesterday's copy apply today's diff. This keeps bandwidth low, but only works if the reader keeps its own copy of the full state.

  • Use case: Update mode is optimal when transmitting full table updates is computationally expensive or bandwidth-prohibitive. For example, tracking user login/logout events across thousands of users where only active users updated during the last trigger window need to be published to a downstream database.
  • Behavioral distinction: If an existing key's aggregate value does not change during a trigger interval, that key is excluded from the current micro-batch output.

12.2.2.1 Worked Example — User Activity Tracking in Update Mode

Consider a streaming system maintaining user activity status (user_id, last_login_time):

  • At trigger \(t_1\), users Avinash and Tushar log in. Update mode outputs rows for Avinash and Tushar.
  • At trigger \(t_2\), user Avinash logs in again, while user Amar (who logged in yesterday) shows no activity.
  • Output written to Sink: Only the updated record for Avinash is written. Amar's unchanged state from yesterday is omitted from the sink output, conserving I/O overhead.

Worked example — the same scenario, traced. Maintain a state table with columns (user_id, last_login_time):

  • At \(t_1\): two login events arrive. Rows Avinash → 10:00 and Tushar → 10:02 are new, so Update Mode writes both to the sink. Sink now has 2 rows.
  • Between \(t_1\) and \(t_2\): nothing changes.
  • At \(t_2\): Avinash logs in again (Avinash → 11:15), so that one row is updated and written. Amar's row (from yesterday) has not changed, so it is not re-sent. Tushar's row has not changed either, so it is also skipped.
  • Sink receives: exactly one row — the updated Avinash record.

Sense-check: the sink now contains {Avinash: 11:15, Tushar: 10:02, Amar: yesterday} — a complete table assembled from the earlier full write plus today's diff. Update Mode saved two rows of network I/O at \(t_2\) compared to Complete Mode.

12.2.3 Append Output Mode

In Append Mode, only finalized new rows that will never be updated or modified by future data are written to the sink.

Intuition — printing a receipt you can never amend. Once a receipt is printed, it cannot be corrected in place; if you overcharged, you must issue a new receipt. Append Mode works the same way: a row is written to the sink only when the engine is sure no future data can change it, and from that moment the row is locked. This is why Append Mode is the only mode safe for file-based sinks — a file row, once written, cannot be updated in place.

  • Use case: Append mode is required for file-based sinks (such as Parquet, ORC, or JSON files) where existing files cannot be overwritten or updated in place.
  • Finalization constraint: Once a row is emitted in Append Mode, its contents are locked. To determine when a windowed aggregation is finalized and safe to emit, Append Mode relies on watermarking.
  • Latency impact: Append mode delays output emission until the engine confirms that late-arriving data for a given window threshold can no longer alter the aggregate result.

Q: If we extend the watermark threshold window in Append Mode to an arbitrarily long duration, does it become identical to Complete Mode? A: While the final aggregated data values will match, the key operational difference is latency and output emission frequency. Complete Mode emits an updated table output at every trigger interval continuously. Append Mode suppresses output completely until the watermark threshold passes and the batch window is officially finalized. Setting an excessively long watermark threshold in Append Mode causes long output delays and requires substantial driver/worker state memory to retain intermediate keys.

Pitfalls:

  • Complete Mode on a file sink: file sinks cannot be updated in place, so Complete and Update modes are rejected there — only Append works, and that requires a watermark.
  • Append Mode without a watermark on aggregations: the engine cannot tell when a window is finalized, so the query is rejected; Append without a watermark is only valid for plain non-aggregated filters/selects.
  • Update Mode on unbounded state with no key: a stateful aggregation with no watermark grows without bound in memory; the engine refuses it.
  • Mistaking "final values match" for "behaves identically": Complete and Append can converge on the same numbers but differ drastically in when output appears — a long watermark hides results for a long time.

Exam note: Expect a 4-to-5 mark comparison question on the exam asking to contrast Complete, Update, and Append modes regarding state memory requirements, output emission timing, and sink compatibility. A one-line memory hook: Complete = full table every time; Update = changed rows only; Append = finalized rows only, once.

Dimension Complete Mode Update Mode Append Mode
What is written The entire result table Only changed/new rows Only finalized (never-to-change) rows
Emission frequency Every trigger, full table Every trigger, changed rows Only when a window is finalized
State memory needed High — all keys retained High — all keys retained High — all keys retained until finalization, then purged
Sink compatibility Aggregation sinks (dashboards, DBs); not file sinks Aggregation sinks; not file sinks File sinks (Parquet, ORC, JSON) and others
Watermark required for aggregations? No No Yes
Typical use Live top-N dashboards, counters Session/user activity tracking Data-lake append pipelines

When to pick which: need a continuously refreshed full picture → Complete; need to minimize bandwidth on a key-value state → Update; need append-only storage or clean finalized windows → Append.

Recap + bridge: The three output modes differ in which rows reach the sink and when. Append Mode's "finalized" concept depends on knowing when late data can no longer change a window — which is precisely what event-time processing and watermarking provide, the topic of the next section.


12.3 Event Time Processing and Watermarking Protocol

Hook — the sensor's timestamp says 10:00, but it arrives at 10:12. Which time counts? If your windowing logic uses arrival time, a slightly late sensor reading lands in the wrong window and your averages go wrong. Real streaming data arrives out of order all the time, and this section explains how Spark keeps windowed results correct by using event time plus a watermark to decide how long to wait for stragglers.

Real-world streaming data frequently arrives out of order due to network latency, device connectivity drops, or distributed queue delays. Stream processing systems distinguish between two timelines:

  1. Ingestion Time: The timestamp recorded when the processing engine (Spark) receives the event.
  2. Event Time: The timestamp embedded directly inside the record payload when the event was originally generated at the source device.

Intuition — the postmark on the envelope, not the date it reaches you. An online store's order event carries the moment the customer clicked "Buy" (event time). The server may receive that click seconds later (ingestion time). For windowing, what matters is when the event actually happened, not when it happened to arrive — otherwise a slow network silently moves events between windows. The trade-off: trusting event time means you must tolerate late arrivals, which is exactly the problem the watermark solves.

Processing streams based on event time ensures accurate windowed aggregations regardless of arrival delays. To manage unbounded state and decide when late data must be discarded, Spark uses a mechanism called watermarking.

12.3.1 Mathematical Formulation of Watermarks

The verbal definition of a watermark is: the watermark value at any trigger execution is defined as the maximum event time observed by the engine across all processed data up to that point, minus a user-defined delay threshold.

Formalize — one equation, two numbers. Let \(T_{\text{max}}\) be the largest event timestamp the engine has seen so far (the "most recent thing that happened"), and let \(\Delta_{\text{watermark}}\) be the user's chosen grace period (how late we are willing to wait for stragglers). The watermark \(W\) is:

\[ W = T_{\text{max}} - \Delta_{\text{watermark}} \]

Every symbol:

  • \(T_{\text{max}} \in \mathbb{R}^+\) — maximum event time timestamp observed across all processed records so far;
  • \(\Delta_{\text{watermark}} \in \mathbb{R}^+\) — the fixed watermark threshold duration chosen by the user (for example 10 minutes);
  • \(W \in \mathbb{R}\) — the cutoff timestamp. Events older than \(W\) are considered too late.

Read it in words: the watermark is a line drawn \(\Delta_{\text{watermark}}\) behind the newest event we have seen. Anything that arrives earlier than that line is late enough that we no longer care about it.

In PySpark, watermarking is declared on a streaming DataFrame using the withWatermark transformation:

streaming_df.withWatermark("event_time", "10 minutes") \
            .groupBy(window("event_time", "10 minutes"), "word") \
            .count()

Scope & assumptions of the watermark equation:

  • Assumption — one event-time column: the watermark applies to a single event-time column named in withWatermark; the engine assumes that column is trustworthy and monotonically roughly increasing (some disorder is tolerated).
  • Assumption — bounded lateness: the watermark model assumes most events arrive within \(\Delta_{\text{watermark}}\) of their event time. If lateness regularly exceeds the threshold, correct data is silently dropped — the threshold must be sized to the real network behavior.
  • What breaks if violated: if the event-time column contains bad values (for example zeros or timestamps from the wrong timezone), \(T_{\text{max}}\) is corrupted and every watermark computation is wrong.
  • Scope: a watermark is per-query, not global — each streaming query sets its own threshold.

12.3.2 Watermark Execution Protocol

During streaming execution, the watermarking engine enforces two operational rules at each trigger point:

  1. Data Ingestion Filter: Any incoming event whose embedded event time \(t_{\text{event}} < W\) is classified as "too late" and is immediately discarded at the ingestion boundary. It is excluded from state aggregation.
  2. Window Finalization: A windowed aggregation covering the time interval \([t_{\text{window\_start}}, t_{\text{window\_end}}]\) is marked as finalized when the updated watermark boundary satisfies \(W \ge t_{\text{window\_end}}\). Once finalized in Append Mode, the aggregate result for that window is outputted to the sink, and its intermediate state is purged from memory.

Intuition — the professor's deadline with a grace period. Imagine coursework: the deadline is a window end, and the professor grants a \(\Delta_{\text{watermark}}\) grace period after the newest submission. Rule 1 (ingestion filter): any submission older than the current "cutoff" (watermark) is returned unread — too late to count. Rule 2 (finalization): once the cutoff has moved past a deadline, that assignment's grades are final; late work can no longer change them, and the grading sheet for it is archived (memory freed).

Visual intuition: draw a horizontal timeline with event time on the \(x\)-axis and the count of arriving events on the \(y\)-axis. As time passes, a vertical watermark line sits \(\Delta_{\text{watermark}}\) behind the rightmost (newest) event that has arrived. Events that arrive to the left of the watermark line are dropped at the door. Windowed buckets whose right edge has slid to the left of the watermark line turn from "open" (grey) to "finalized" (green) and are emitted. The takeaway: the watermark is the moving boundary that separates "still accepting" from "already closed."

Pitfalls:

  • Choosing the threshold by guesswork: a too-small \(\Delta_{\text{watermark}}\) drops legitimate late events; a too-large one delays output and hoards memory. Size it from observed arrival-latency distributions.
  • Watermarking on the wrong column: if the column passed to withWatermark is ingestion time rather than event time, the watermark gives false confidence and late data slips through.
  • Forgetting that discards are permanent: once the watermark passes an event's timestamp, that event is gone for this query — no later "recovery" within the same query.
  • Expecting a global cluster watermark: there is none; each query configures its own, because 5-minute dashboard metrics and 24-hour audit sessions have very different grace needs.

Recap + bridge: A watermark is the newest event time seen minus a chosen grace period, \(W = T_{\text{max}} - \Delta_{\text{watermark}}\); it both filters late records at ingestion and decides when windows finalize. The equation is easy — the tricky part is tracing it trigger by trigger, which is exactly what the next section's worked walkthrough does.

Real-world: Ad-click and sensor pipelines routinely use event-time watermarks so that a phone that was offline and reconnects late still contributes its events to the correct 10-minute window, while windows that are truly finished are flushed to data lakes without waiting forever. The same mechanism powers fraud-detection windows where a transaction's own timestamp — not the arrival time — must decide which alerting window it belongs to.


12.4 Step-by-Step Watermarking Walkthroughs

Hook — the formula is easy; the trace is the exam. \(W = T_{\text{max}} - \Delta_{\text{watermark}}\) takes one line. The hard part — and a favorite exam question — is tracking trigger by trigger what the watermark is, which records get discarded, and which windows finalize and emit. This section works one complete scenario through every trigger so the protocol becomes a mechanical skill rather than a vague idea.

To understand the interaction between system processing time, event time, trigger intervals, batch windows, and watermarking thresholds, consider the following comprehensive worked walkthroughs.

12.4.1 Comprehensive Worked Computation — Append Mode with Watermarking

Purpose of this trace: show, minute by minute, how the four clocks (system trigger time \(t_{\text{sys}}\), event time \(t_{\text{event}}\), batch windows, and the watermark) interact in Append Mode. Inputs & outputs: input is a stream of (event_time, word) tuples; parameters are the trigger interval (5 min), window duration (10 min), and watermark threshold (10 min); output is the set of finalized window aggregates written to the sink, plus the set of discarded late tuples.

Execution Setup Parameters:

  • Streaming Mode: Append Mode
  • System Trigger Interval: 5 minutes (engine evaluates output every 5 minutes of system time)
  • Batch Window Duration: 10 minutes (tumbling windows: [0, 10], [5, 15], [10, 20], etc.)
  • Watermark Threshold (\(\Delta_{\text{watermark}}\)): 10 minutes

The timeline is tracked across system processing time \(t_{\text{sys}}\) (horizontal axis) and event timestamps \(t_{\text{event}}\) embedded in data tuples (event_time, word).

System Processing Timeline (t_sys):
t_sys = 5 min  ---> Trigger 1: Engine starts; Watermark = None; Output = None
t_sys = 10 min ---> Trigger 2: Max Event Time = 8; Watermark = 8 - 10 = -2 min; Output = None
t_sys = 15 min ---> Trigger 3: Max Event Time = 14; Watermark = 14 - 10 = 4 min; Output = None
t_sys = 20 min ---> Trigger 4: Max Event Time = 21; Watermark = 21 - 10 = 11 min; Output = None
                    [Late event (3, "bat") arrives -> 3 < 11 -> DISCARDED]
t_sys = 25 min ---> Trigger 5: Max Event Time = 26; Watermark = 26 - 10 = 16 min;
                    [Watermark 16 > Window End 10 -> Finalizes Window [0, 10]]
                    OUTPUT: (cat: 1, dog: 2, owl: 1)
                    [Late event (9, "cat") arrives -> 9 < 16 -> DISCARDED]
t_sys = 30 min ---> Trigger 6: Max Event Time = 26; Watermark = 16 min (unchanged);
                    [Watermark 16 > Window End 15 -> Finalizes Window [5, 15]]
                    OUTPUT: (cat: 1, dog: 3, owl: 2)

Step-by-Step Execution Sequence:

  1. System Time \(t_{\text{sys}} = 5\) minutes (Trigger 1):
  • Current Watermark \(W\): None (initialization phase).
  • Batch to Finalize: None.
  • Output: None.
  1. Events arrive between \(t_{\text{sys}} = 5\) and \(t_{\text{sys}} = 10\):
  • Data received: (7, "dog"), (8, "owl").
  1. System Time \(t_{\text{sys}} = 10\) minutes (Trigger 2):
  • Current Watermark \(W\): None (no prior watermark exists).
  • Batch to Finalize: None (cannot finalize window [0, 10] without an established watermark).
  • Max Event Time observed so far \(T_{\text{max}}\): 8 minutes.
  • Update Watermark: \(W = T_{\text{max}} - \Delta_{\text{watermark}} = 8 - 10 = -2\) minutes. (Negative boundary indicates pipeline warmup).
  • Output: None.
  1. Events arrive between \(t_{\text{sys}} = 10\) and \(t_{\text{sys}} = 15\):
  • Data received: (9, "cat"), (14, "dog").
  1. System Time \(t_{\text{sys}} = 15\) minutes (Trigger 3):
  • Current Watermark \(W\): \(-2\) minutes.
  • Batch to Finalize: None (watermark \(-2 < 10\)).
  • Max Event Time observed so far \(T_{\text{max}}\): 14 minutes.
  • Update Watermark: \(W = 14 - 10 = 4\) minutes. (Watermark line advances to 4 minutes).
  • Output: None.
  1. Events arrive between \(t_{\text{sys}} = 15\) and \(t_{\text{sys}} = 20\):
  • Data received: (8, "dog"), (13, "owl"), (15, "cat"), (21, "dog").
  1. System Time \(t_{\text{sys}} = 20\) minutes (Trigger 4):
  • Current Watermark \(W\): 4 minutes.
  • Batch to Finalize: None (watermark \(4 < 10\); window [0, 10] remains open for potential late arrivals with \(t_{\text{event}} > 4\)).
  • Max Event Time observed so far \(T_{\text{max}}\): 21 minutes.
  • Update Watermark: \(W = 21 - 10 = 11\) minutes. (Watermark line advances to 11 minutes).
  • Output: None.
  1. Events arrive between \(t_{\text{sys}} = 20\) and \(t_{\text{sys}} = 25\):
  • Data received: (26, "owl"), (17, "owl"), (3, "bat").
  • Late Data Filter Audit: Event (3, "bat") has embedded event time \(t_{\text{event}} = 3\). The current watermark is \(W = 11\) minutes. Because \(3 < 11\), event (3, "bat") is discarded at ingestion and purged immediately.
  1. System Time \(t_{\text{sys}} = 25\) minutes (Trigger 5):
  • Current Watermark \(W\): 11 minutes.
  • Batch Finalization Evaluation: The engine checks window [0, 10]. Because watermark \(W = 11 \ge 10\), window [0, 10] is officially finalized.
  • Finalized Window [0, 10] Data Aggregation:
  • Included events: (7, "dog"), (8, "owl"), (9, "cat"), (8, "dog").
  • Word counts: cat: 1, dog: 2, owl: 1.
  • Output written to Sink:
Window Word Count
[0, 10] cat 1
[0, 10] dog 2
[0, 10] owl 1
  • Max Event Time observed so far \(T_{\text{max}}\): 26 minutes.
  • Update Watermark: \(W = 26 - 10 = 16\) minutes. (Watermark advances to 16 minutes).
  1. Events arrive between \(t_{\text{sys}} = 25\) and \(t_{\text{sys}} = 30\):
  • Data received: Late arriving record (9, "cat").
  • Late Data Filter Audit: Event (9, "cat") has \(t_{\text{event}} = 9\). Current watermark \(W = 16\) minutes. Because \(9 < 16\), this record is discarded at ingestion as a late arrival.
  1. System Time \(t_{\text{sys}} = 30\) minutes (Trigger 6):
  • Current Watermark \(W\): 16 minutes.
  • Batch Finalization Evaluation: The engine checks window [5, 15]. Because watermark \(W = 16 \ge 15\), window [5, 15] is officially finalized.
  • Finalized Window [5, 15] Data Aggregation:
  • Included valid events with \(t_{\text{event}} \in [5, 15]\): (7, "dog"), (8, "owl"), (9, "cat"), (8, "dog"), (13, "owl"), (14, "dog").
  • Word counts: cat: 1, dog: 3, owl: 2.
  • Output written to Sink:
Window Word Count
[5, 15] cat 1
[5, 15] dog 3
[5, 15] owl 2
  • Max Event Time \(T_{\text{max}}\): 26 minutes (unchanged).
  • Update Watermark: \(W = 26 - 10 = 16\) minutes (remains 16 minutes).

Trace summary — the whole run in one table. Each row is one trigger; the "discarded" column lists tuples dropped at ingestion, and "output" lists the finalized windows emitted.

\(t_{\text{sys}}\) (trigger) New tuples \(T_{\text{max}}\) New \(W = T_{\text{max}} - 10\) Discarded Finalized window (output)
5 (1) None None
10 (2) (7,dog), (8,owl) 8 \(-2\) None
15 (3) (9,cat), (14,dog) 14 4 None
20 (4) (8,dog), (13,owl), (15,cat), (21,dog) 21 11 None
25 (5) (26,owl), (17,owl), (3,bat) 26 16 (3,bat): \(3 < 11\) [0,10]: cat 1, dog 2, owl 1
30 (6) (9,cat) 26 16 (9,cat): \(9 < 16\) [5,15]: cat 1, dog 3, owl 2

Sense-checks:

  • Window [0, 10] aggregates only the four tuples with \(0 \le t_{\text{event}} \le 10\): (7,dog), (8,owl), (9,cat), (8,dog) → cat 1, dog 2, owl 1. ✔
  • Window [5, 15] aggregates the six tuples with \(5 \le t_{\text{event}} \le 15\): adds (13,owl) and (14,dog) to the previous four → cat 1, dog 3, owl 2. ✔
  • The watermark only ever moves forward: \(-2 \to 4 \to 11 \to 16\), never backward — it is driven by the maximum event time, which is monotonic. ✔
  • (3, "bat") and (9, "cat") are discarded because their event times are below the watermark at the moment they arrive; neither appears in any emitted window. ✔

Complexity & cost — when this trace gets expensive. The engine keeps one running aggregate per open window. Because windows are 10 minutes wide and the watermark lags by 10 minutes, the number of simultaneously open windows stays bounded as long as \(\Delta_{\text{watermark}}\) is bounded — but a huge threshold means many open windows and their partial counts held in driver/worker memory for a long time. The discarded tuples cost nothing to state, but a threshold that is far too large delays every output by hours while retaining every intermediate key.

Pitfalls in trace problems:

  • Using the new watermark to judge the previous window: finalization at trigger 5 uses \(W = 11\) (from trigger 4), not the \(W = 16\) computed afterwards. Evaluate windows with the watermark that is current at that trigger.
  • Forgetting that \(T_{\text{max}}\) is the max over all past events: it never decreases, so the watermark never moves backward — a single very new event (26) can jump the watermark past several windows at once.
  • Counting discarded tuples in window aggregates: once a tuple is dropped at ingestion it can never appear in any output row.
  • Missing that windows overlap: with 10-minute windows on a 5-minute cadence, an event can belong to two windows (for example (13,owl) belongs to both [5,15] and [10,20]), so a single tuple may be counted in more than one emitted window.

Exam note: Expect an exam problem providing system trigger times, event tuples, and watermark parameters, requiring you to trace the exact watermark values, identify discarded tuples, and list the final emitted output rows for each trigger step. Practice the table form above — it maps directly onto the marks.

12.4.2 Comparative Analysis — Update Mode with Watermarking

If the exact same scenario above is executed in Update Mode instead of Append Mode:

  • At system time \(t_{\text{sys}} = 10\), Update Mode immediately emits intermediate aggregate counts for unfinalized window [0, 10] (dog: 1, owl: 1).
  • At system time \(t_{\text{sys}} = 15\), Update Mode emits updated counts for window [0, 10] (cat: 1, dog: 2, owl: 1) and initial counts for window [5, 15].
  • Once the watermark boundary advances past a window's end time (e.g., \(W = 11 \ge 10\) at \(t_{\text{sys}} = 25\)), window [0, 10] is finalized. The engine stops accepting changes for window [0, 10] and suppresses future emissions for that window.

Intuition — the same engine, different reporter. In Append Mode the reporter stays silent until a window is finished, then publishes the final numbers once. In Update Mode the same reporter publishes partial numbers after every trigger and quietly stops publishing a window once it is final. The underlying watermark and finalization logic is identical — only the output discipline differs. That is why the two modes share the same trace but produce very different sink contents.

Trigger \(t_{\text{sys}}\) Append Mode sink Update Mode sink
10 nothing [0,10]: dog 1, owl 1 (partial)
15 nothing [0,10]: cat 1, dog 2, owl 1 (updated) + [5,15] initial counts
20 nothing further partial updates
25 [0,10]: cat 1, dog 2, owl 1 (final, first and only emission) [0,10] finalized — updates stop for it
30 [5,15]: cat 1, dog 3, owl 2 (final) [5,15] nearing finalization

When to pick which: if downstream consumers can tolerate (and want) incremental updates, Update Mode gives lower latency; if the sink must contain only final, immutable results — typical for data lakes — Append Mode is the only correct choice.

12.4.3 Student Q&A Exchanges on Watermarking Mechanics

Q: Can watermark settings be configured globally across an entire Spark cluster, or are they defined per streaming job? A: Watermarks are configured per individual streaming DataFrame transformation query inside application code using withWatermark(). There is no global cluster-level watermark override because different streaming workflows have distinct business latencies (e.g., a 5-minute dashboard metric vs. a 24-hour user login audit session).

Q: What happens if a critical late record arrives after the watermark has passed? Can we dynamically adjust the watermark to recover discarded data? A: Once a watermark boundary advances past an event time, any arriving records prior to that watermark are permanently discarded at ingestion for that specific streaming aggregation query. Watermark thresholds cannot be altered retroactively for an active aggregation state. To retain late data for alternative auditing, developers can instantiate a parallel streaming pipeline branch with a larger watermark threshold or store raw un-aggregated stream events directly to persistent lake storage.

Recap + bridge: Tracing Append Mode trigger by trigger, the watermark is recomputed as \(T_{\text{max}} - \Delta_{\text{watermark}}\), late tuples with \(t_{\text{event}} < W\) are dropped at ingestion, and windows finalize once \(W \ge t_{\text{window\_end}}\). Update Mode runs the same machinery but emits partial results. Streaming and batch together produce the historical and real-time data that machine learning consumes — the lecture now turns from how data flows to how machines learn from it.

Real-world: Event-time watermarks with Append Mode are what let clickstream and IoT pipelines land clean, deduplicated, finalized windows into Parquet/ORC data lakes — every emitted row is guaranteed not to change later, so lake readers never see corrected or duplicated records.


12.5 Machine Learning Fundamentals and Tool Ecosystem

Hook — how do you tell a computer to do something you cannot write rules for? Nobody can hand-write the rules for recognizing a handwritten "7" or deciding a credit card charge is fraudulent — the pattern is too complex to describe explicitly. Machine learning flips the approach: instead of programming the answer, you give the computer examples and let it find the pattern itself. This section gives the two classic definitions of that idea and the tool landscape used to implement it.

The accumulated historical datasets stored via batch processing engines and real-time streams processed by Spark serve as the core input data for Machine Learning (ML) algorithms. Machine learning provides automated computational models capable of discovering underlying patterns, predicting future outcomes, and making intelligent decisions from data.

12.5.1 Formal Definitions of Machine Learning

12.5.1.1 Qualitative Definition — Arthur Samuel (1959)

Arthur Samuel, a pioneer in computer gaming and artificial intelligence, defined machine learning as:

"The field of study that gives computers the ability to learn without being explicitly programmed."

Samuel demonstrated this concept by building a self-learning Checkers program. By having two instances of the computer program play thousands of games against each other, the program accumulated experience, learned winning position strategies, and eventually outperformed Samuel himself.

Intuition — the self-teaching checkers player. Samuel's program never received a rulebook like "control the center" or "jump when you can." It played itself thousands of times, kept the board states that led to wins, and gradually got better. That is the essence of the qualitative definition: no explicit rules are written, yet the program improves — it learns from experience rather than from instructions.

12.5.1.2 Quantitative Definition — Tom Mitchell (1997)

Tom Mitchell formulated a precise, engineering-oriented definition based on three core components: Experience (\(E\)), Task (\(T\)), and Performance Measure (\(P\)):

"A computer program is said to learn from experience \(E\) with respect to some class of tasks \(T\) and performance measure \(P\), if its performance at tasks in \(T\), as measured by \(P\), improves with experience \(E\)."

where:

  • \(E\) represents the experience (training dataset or historical environment interactions).
  • \(T\) represents the target task (e.g., classifying email as spam vs. non-spam, or controlling a self-driving vehicle).
  • \(P\) represents the quantitative performance metric (e.g., classification accuracy percentage, or mean squared error).

Why Mitchell's definition is "quantitative" and testable. Samuel's definition tells you the spirit of ML; Mitchell's tells you how to check whether learning happened. A program learns only if its score \(P\) on the task \(T\) actually improves as you feed it more experience \(E\). You can measure that: run the program with a little experience, measure \(P\); run it with more experience, measure \(P\) again; if the second is better, learning occurred. This converts a philosophical statement into an experiment.

Worked example — filling in \(E\), \(T\), and \(P\) for real applications. For each application, identify the three components:

Application Task \(T\) Experience \(E\) Performance \(P\)
Email spam filter Classify each email as spam or not-spam A labeled corpus of emails marked spam/not-spam Percentage of emails correctly classified
Self-driving vehicle Steer/accelerate/brake to drive safely Millions of recorded driving hours and sensor logs Number of miles driven between human interventions (or collision rate)
House-price predictor Predict the sale price of a house Historical sales records with features and prices Mean squared error between predicted and actual price

Sense-check: in every row, more experience (a bigger labeled dataset, more driving data, more sales records) is expected to raise \(P\) (accuracy, safe miles, lower error). If feeding more \(E\) never changes \(P\), the program is not learning under Mitchell's definition.

Pitfalls:

  • Swapping \(T\) and \(P\): \(T\) is the task the program performs; \(P\) is the score used to judge it. "Classify email" is the task; "accuracy" is the measure.
  • Thinking experience is only labeled data: \(E\) can also be environment interaction (a robot's trial-and-error, a checkers program's self-play) — it is any source from which the program can improve.
  • Confusing the two definitions: Samuel's is the one-liner often quoted in interviews; Mitchell's is the one with the \(E\), \(T\), \(P\) triple that exam questions ask you to fill in.

Exam note: Be prepared to state Tom Mitchell's quantitative ML definition on the exam and identify \(E\), \(T\), and \(P\) for a given real-world application scenario. A reliable strategy: first ask "what is the program supposed to do?" (\(T\)), then "what input lets it improve?" (\(E\)), then "what number tells us it got better?" (\(P\)).

12.5.2 Industry Tool Ecosystem for Big Data Machine Learning

The machine learning tool ecosystem spans low-code UI platforms, desktop/single-node scripting libraries, and distributed big data processing engines:

Category Platforms / Tools Primary Characteristics & Scope
Low-Code / Graphical UI Tools H2O.ai, RapidMiner, Azure Machine Learning Studio Interactive graphical user interfaces. Users upload datasets, configure preprocessing pipelines via drag-and-drop workflows, and run automated ML (AutoML) in cloud environments.
Single-Node Scripting Tools Python scikit-learn (sklearn), statsmodels Industry-standard libraries for standard machine learning workflows on memory-bounded, single-node architectures.
Distributed Big Data ML Engines Apache Spark MLlib, Apache Mahout Distributed computation engines built for multi-terabyte ML workloads. Spark MLlib provides scalable algorithms executing directly across Spark clusters.

Intuition — three workshop sizes. Low-code tools are like a craft shop with ready-made kits: anyone can assemble a model by dragging pieces, but you are limited to the kit's parts. scikit-learn is a fully stocked personal toolbox: every standard tool is there, but one person can only carry so much — it trains on data that fits in a single machine's memory. Spark MLlib is the factory floor: the same algorithms run across many machines in parallel, so models train on multi-terabyte datasets that no single laptop could hold.

In this course, primary emphasis is placed on Apache Spark MLlib to leverage distributed parallel execution over large-scale big data infrastructure.

When to pick which: if the dataset fits in memory and you need a fast experiment, scikit-learn is simpler and quicker to set up. If the dataset spans hundreds of gigabytes or terabytes, or the pipeline must run inside an existing Spark cluster, MLlib is the practical choice. Low-code tools win when the user is not writing code at all — business analysts assembling AutoML workflows.

Recap + bridge: Machine learning means improvement with experience — Samuel's qualitative slogan and Mitchell's measurable \(E\), \(T\), \(P\) triple — and is implemented across low-code, single-node, and distributed tools, with Spark MLlib central to this course. The next section lays out what the learning process actually looks like: the six-stage pipeline and the three paradigms (supervised, unsupervised, reinforcement).

Real-world: The same MLlib pipelines that run on Spark clusters power real-time fraud scoring and recommendation engines, consuming the very streaming data that Sections 12.1–12.4 showed being ingested from Kafka.


12.6 Machine Learning Taxonomy and End-to-End Pipeline

Hook — what does "doing machine learning" actually look like? Between "collect data" and "deploy a model" lie several distinct stages, and the kind of model you build depends on the kind of feedback your data provides: labeled answers, hidden structure, or trial-and-error rewards. This section lays out the six-stage pipeline every real ML project follows, then the three learning paradigms (supervised, unsupervised, reinforcement) with the formulas behind their most famous algorithms.

12.6.1 The End-to-End Machine Learning Pipeline

Purpose of the pipeline: an enterprise ML solution is not "train a model and done" — it is a structured, six-stage workflow in which each stage's output feeds the next, and failures usually come from skipping or underweighting an early stage rather than from the model itself.

Building an enterprise machine learning solution requires executing a structured, six-stage pipeline:

[1. Data Collection] ---> [2. Data Cleaning] ---> [3. Feature Engineering]
                                                          |
[6. Deployment]     <--- [5. Model Evaluation] <--- [4. Model Training]
  1. Data Collection & Ingestion: Gathering raw unstructured or structured records from databases, streaming brokers (Kafka), logs, or file storage.
  2. Data Preprocessing & Cleaning: Handling missing values, filtering noise, deduplicating records, and resolving data type mismatches.
  3. Feature Engineering & Selection: Transforming raw inputs into informative numerical vectors. Redundant or collinear features must be pruned. For example, if a dataset contains patient height in both centimeters and meters, keeping both features introduces numerical redundancy; one representation should be removed.
  4. Model Selection & Training: Selecting appropriate candidate algorithms (e.g., Linear Regression, Decision Trees) and fitting model parameters on historical training data.
  5. Model Evaluation & Validation: Measuring model generalization performance on unseen test data using statistical metrics.
  6. Deployment & Monitoring: Publishing trained models to production microservices or streaming engines for real-time inference.

Worked example — the redundant-feature trap (Feature Engineering). Suppose a medical dataset stores each patient's height in two columns: height_cm (e.g., 180) and height_m (e.g., 1.80). These two features are perfectly collinear — one is exactly 100× the other — so they carry the same information twice. Keeping both does not add signal; it adds redundancy that can destabilize the model's fitted weights (multicollinearity) and waste training time. The fix: keep exactly one representation, say height_m, and drop height_cm. Sense-check: no information is lost, because any value in one column is exactly recoverable from the other.

Pitfalls in the pipeline:

  • Cleaning is not optional: models trained on noisy, duplicated, or missing-laden data learn the noise; garbage in, garbage out.
  • Feature leakage between training and test: engineering features using statistics computed over the whole dataset (including the test split) makes evaluation look unrealistically good — features must be built from training data only.
  • Skipping evaluation: deploying a model that was never tested on unseen data is how production models surprise you.
  • Thinking deployment is the end: models drift as real-world patterns change; monitoring is part of the pipeline, not an afterthought.

12.6.2 Taxonomy of Machine Learning Paradigms

Machine learning algorithms are categorized into three major learning paradigms based on the nature of feedback provided during training:

                          Machine Learning
                                 |
      +--------------------------+--------------------------+
      |                          |                          |
Supervised Learning     Unsupervised Learning    Reinforcement Learning
      |                          |                          |
  +---+---+                  +---+---+                  +---+---+
  |       |                  |       |                  |       |
Reg.    Class.           Clust.   Assoc.             Agent   Reward

Intuition — the three ways a student can learn. Supervised learning is like studying with a full answer key: every practice question has the correct answer attached, and you learn to map questions to answers. Unsupervised learning is like being handed a pile of unlabeled photos and asked to sort them into piles yourself — no one tells you the categories, you find the structure. Reinforcement learning is like learning to ride a bike: no one hands you a rulebook, you just try actions, get praised or fall down (reward or penalty), and adjust.

12.6.2.1 Supervised Learning

In Supervised Learning, the model is trained on a labeled dataset consisting of input-output pairs \(\mathcal{D} = \{(\mathbf{x}_i, y_i)\}_{i=1}^{N}\), where \(\mathbf{x}_i \in \mathbb{R}^d\) represents the independent feature vector and \(y_i\) represents the target dependent variable.

Supervised learning is divided into two sub-branches based on the data type of the target variable \(y\):

  1. Regression: The target variable \(y \in \mathbb{R}\) is continuous.
  • Formulation: Modeling the functional mapping \(y = f(\mathbf{x}) + \epsilon\).
  • Linear Regression Equation:

\[ y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_d x_d + \epsilon \] where \(y \in \mathbb{R}\) is the scalar dependent variable, \(\beta_0 \in \mathbb{R}\) is the intercept term, \(\beta_j \in \mathbb{R}\) are feature weights, \(x_j \in \mathbb{R}\) are independent feature inputs, and \(\epsilon \sim \mathcal{N}(0, \sigma^2)\) represents unobserved random error.

  • Real-world applications: Predicting house prices based on land area and room count, stock index forecasting, temperature estimation.
  1. Classification: The target variable \(y\) is categorical (discrete classes).
  • Binary Classification: Target \(y \in \{0, 1\}\) (e.g., Email Spam vs. Non-Spam, Credit Card Fraud vs. Legitimate, Disease Positive vs. Negative).
  • Multiclass Classification: Target \(y \in \{1, 2, \dots, K\}\) where \(K > 2\) (e.g., Handwritten digit recognition \(0\text{--}9\), news article topic categorizations).

Worked example — regression vs. classification by target type. If your target is a number on a continuous scale — house price in ₹ (e.g., predicting ₹42.5 lakh from 1,200 sq ft and 3 rooms) — that is regression; the output can be any real value. If your target is a category — "spam" or "not spam", digit "3" vs. digit "7" — that is classification; the output is one of a finite set of labels. Sense-check: ask "can the answer be 42.7?" — if yes, regression; if the answer must be exactly one of a fixed list, classification.

Assumptions & scope: Linear regression assumes a roughly linear relationship between features and target, and that the error \(\epsilon\) has mean zero. If the true relationship is curved, a linear model underfits and the residuals reveal the miss. Classification assumes the classes are reasonably separable by the chosen model; if classes overlap heavily, no classifier will reach perfect accuracy and the confusion-matrix metrics (Section 12.7) tell you which errors matter more.

12.6.2.2 Unsupervised Learning

In Unsupervised Learning, the model is provided with an unlabeled dataset \(\mathcal{D} = \{\mathbf{x}_i\}_{i=1}^{N}\) containing feature vectors without corresponding ground-truth target outputs \(y\). The objective is to uncover intrinsic patterns, structural groupings, or underlying probability densities.

Main sub-branches include:

  1. Clustering: Partitioning data points into homogeneous groups such that points within a cluster are highly similar, while points across clusters are distinct.
  • Primary Algorithm: K-Means Clustering.
  • Real-world applications: Customer market segmentation, grouping documents by topic, anomaly detection.
  1. Association Rule Mining (Market Basket Analysis): Discovering co-occurrence relationships and conditional purchase dependencies between items in transactional databases.
  • Primary Algorithm: Apriori Algorithm.
  • Core Mathematical Metrics for a rule \(A \rightarrow B\):
  • Support: The joint probability of finding both itemsets \(A\) and \(B\) in a transaction:

\[ \text{Support}(A \rightarrow B) = P(A \cap B) = \frac{\text{Count}(A \cup B)}{N} \] where \(\text{Count}(A \cup B)\) is the number of transactions containing both \(A\) and \(B\), and \(N\) is total transactions.

  • Confidence: The conditional probability that a transaction contains \(B\), given that it contains \(A\):

\[ \text{Confidence}(A \rightarrow B) = P(B \mid A) = \frac{P(A \cap B)}{P(A)} = \frac{\text{Count}(A \cup B)}{\text{Count}(A)} \]

  • Lift: The ratio of observed joint occurrence to expected independent occurrence:

\[ \text{Lift}(A \rightarrow B) = \frac{P(A \cap B)}{P(A) \cdot P(B)} = \frac{\text{Confidence}(A \rightarrow B)}{P(B)} \] where a \(\text{Lift} > 1\) indicates a strong positive inferential association between itemset purchase behaviors.

Formalize — reading the three metrics in words. Support asks "how common is the co-occurrence overall?" (a high-support rule involves frequent items). Confidence asks "when \(A\) is bought, how often is \(B\) bought too?" (a high-confidence rule is a reliable implication). Lift asks "is the co-occurrence more likely than pure chance?" — it divides what actually happens by what would happen if \(A\) and \(B\) were independent. Lift \(> 1\): buying \(A\) makes buying \(B\) more likely. Lift \(= 1\): independent. Lift \(< 1\): buying \(A\) makes buying \(B\) less likely.

Worked example — computing Support, Confidence, and Lift with real numbers. Consider a store with \(N = 1000\) transactions. Item \(A\) appears in 300 transactions, item \(B\) appears in 250, and both appear together in 150. First compute the three probabilities:

\[ P(A) = \frac{300}{1000} = 0.30, \qquad P(B) = \frac{250}{1000} = 0.25, \qquad P(A \cap B) = \frac{150}{1000} = 0.15 \]

Then the rule \(A \rightarrow B\):

\[ \text{Support} = P(A \cap B) = 0.15 \;(15\%) \]

\[ \text{Confidence} = \frac{P(A \cap B)}{P(A)} = \frac{0.15}{0.30} = 0.50 \;(50\%) = \frac{\text{Count}(A \cup B)}{\text{Count}(A)} = \frac{150}{300} \]

\[ \text{Lift} = \frac{P(A \cap B)}{P(A) \cdot P(B)} = \frac{0.15}{0.30 \times 0.25} = \frac{0.15}{0.075} = 2.0 \]

Interpretation: customers who buy \(A\) buy \(B\) 50% of the time, but \(B\)'s overall rate is only 25% — so knowing \(A\) doubles the chance of \(B\) (Lift \(= 2.0 > 1\)). This is a strong positive association worth acting on (e.g., placing \(A\) and \(B\) on the same aisle). Sense-check: Lift \(= \text{Confidence} / P(B) = 0.50 / 0.25 = 2.0\), consistent; and since \(P(A \cap B) = 0.15 > P(A)P(B) = 0.075\), the observed joint rate exceeds the independence baseline, which is exactly what Lift \(> 1\) detects.

Worked example — the classic beer-and-diapers basket. A retailer mines its sales and finds that among \(N = 1000\) weekend transactions, beer appears in 200, diapers in 150, and both in 60. For the rule Beer \(\rightarrow\) Diaper:

\[ \text{Support} = \frac{60}{1000} = 0.06 \;(6\%), \qquad \text{Confidence} = \frac{60}{200} = 0.30 \;(30\%), \qquad \text{Lift} = \frac{0.06}{0.20 \times 0.15} = \frac{0.06}{0.03} = 2.0 \]

Sense-check: diaper purchases are 15% overall, but 30% among beer buyers — twice the baseline, so Lift \(= 2.0\) confirms a real (if non-obvious) co-purchase pattern rather than coincidence.

  • Real-world retail examples:
  • The classic retail finding where diaper purchases strongly correlate with Friday evening beer purchases.
  • Predictive analytics revealing an unexpected surge in customer demand for strawberry Pop-Tarts in retail stores immediately preceding major hurricane landfall events.

Pitfalls in market basket analysis:

  • High support is not required for interesting rules: a rule can be very rare (low support) yet strongly predictive (high lift) — filter by minimum support to control noise, then rank survivors by lift.
  • Confidence can mislead on frequent items: if \(B\) is bought in 80% of all transactions, any rule with \(A\) on the left will have high confidence even when \(A\) and \(B\) are independent — that is exactly why Lift exists.
  • Correlation is not causation: beer-diapers co-occurrence does not mean buying beer causes diaper purchases; both may share a hidden cause (a parent shopping on Friday evening).

12.6.2.3 Reinforcement Learning

In Reinforcement Learning (RL), an autonomous agent learns optimal behavior strategies by interacting directly with a dynamic environment through trial and error over discrete time steps.

The agent observes the current environmental state \(s_t \in \mathcal{S}\), selects an action \(a_t \in \mathcal{A}\) based on a policy \(\pi(a \mid s)\), transitions to a new state \(s_{t+1}\), and receives a scalar reward signal \(r_t \in \mathbb{R}\) (or penalty). The goal is to maximize cumulative long-term discounted rewards \(\sum_{t=0}^{\infty} \gamma^t r_t\).

Formalize — the pieces of the RL loop. At each step \(t\): the agent reads the state \(s_t\) from the state space \(\mathcal{S}\); the policy \(\pi(a \mid s)\) gives the probability of choosing action \(a_t \in \mathcal{A}\) in that state; acting moves the environment to \(s_{t+1}\) and returns reward \(r_t\). The objective is the discounted sum \(\sum_{t=0}^{\infty} \gamma^t r_t\), where the discount factor \(\gamma \in [0, 1)\) makes a rupee now worth more than a rupee later — that is what makes the agent prefer quick rewards without entirely ignoring distant ones.

  • Real-world applications: Autonomous vehicle navigation, chess/Go game engines (DeepMind AlphaGo), robotic arm manipulation, algorithmic trading strategies.

Q: How is machine learning applied to biological audio diagnostics like human hearing capability tests? A: Human decibel perception thresholds vary non-linearly across frequency spectrums and individual age profiles. Machine learning models train on audiometric frequency response data to dynamic adapt test decibel sweeps, calibrating precise individualized hearing acuity profiles faster and more accurately than fixed static decibel testing protocols.

Pitfalls:

  • Unsupervised ≠ unlabeled only: no ground-truth labels exist, so "correctness" is judged by structure (compact clusters, frequent itemsets) — there is no accuracy score to tune against.
  • RL is not supervised: there is no labeled "correct action"; the agent only receives a reward signal, which is delayed and sparse, making credit assignment (which action caused the reward) the hard part.
  • K-means needs \(K\) chosen up front: the algorithm partitions into exactly \(K\) clusters; choosing \(K\) wrong produces forced groupings, and the result depends on the initial centers.

Recap + bridge: ML projects follow a six-stage pipeline from collection to deployment; paradigms split by feedback type — supervised (labeled answers; regression vs. classification), unsupervised (hidden structure; clustering and association rules with Support/Confidence/Lift), and reinforcement (trial-and-error rewards). Whatever the paradigm, you need numbers to say whether a model is good — and that is the topic of the final section, evaluation metrics.

Real-world: Retailers deploy the Apriori algorithm to optimize shelf layouts and inventory — pairing beer near diaper aisles for weekend shoppers or stocking strawberry Pop-Tarts before forecasted hurricanes — while streaming platforms feed the same event data into supervised fraud classifiers, showing how Sections 12.1–12.6 connect end to end.


12.7 Model Evaluation Metrics

Hook — a model that is "right 98.5% of the time" can still be useless. In fraud detection that 98.5% might mean the model catches only 75% of actual fraud while firing alerts on innocent customers. Accuracy alone hides this. This section builds the four classification metrics (Accuracy, Precision, Recall, F1) from the confusion matrix, then the four regression metrics (MSE, RMSE, MAE, \(R^2\)).

Evaluating model quality requires distinct quantitative performance metrics for classification and regression tasks.

12.7.1 Classification Evaluation Metrics — The Confusion Matrix

For binary classification problems, model predictions are evaluated against actual ground-truth labels using a \(2 \times 2\) Confusion Matrix:

Predicted Positive (\(\hat{y} = 1\)) Predicted Negative (\(\hat{y} = 0\))
Actual Positive (\(y = 1\)) True Positive (TP) False Negative (FN)
Actual Negative (\(y = 0\)) False Positive (FP) True Negative (TN)

Intuition — the four outcomes of a yes/no test. A true positive is a real positive correctly flagged; a false negative is a real positive the model missed; a false positive is a false alarm (a healthy patient told they are sick); a true negative is a real negative correctly cleared. The matrix rows are the truth and columns are the prediction — so the diagonal (TP, TN) is where the model agrees with reality.

From these four fundamental counts, four primary summary metrics are derived:

  1. Accuracy: The proportion of total predictions that were correctly classified:

\[ \text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN} \] where \(TP, TN, FP, FN \in \mathbb{N}\). Accuracy can be misleading on imbalanced datasets (e.g., 99% non-fraud, 1% fraud).

  1. Precision: The proportion of positive model predictions that are truly positive:

\[ \text{Precision} = \frac{TP}{TP + FP} \] Precision measures prediction quality and controls False Positive alarms.

  1. Recall (Sensitivity / True Positive Rate): The proportion of actual positive cases that were correctly identified by the model:

\[ \text{Recall} = \frac{TP}{TP + FN} \] Recall measures prediction coverage and controls False Negatives (critical in medical diagnostics and fraud detection).

  1. F1-Score: The harmonic mean of Precision and Recall, balancing both metrics into a single scalar value:

\[ F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} = \frac{2 \cdot TP}{2 \cdot TP + FP + FN} \]

Worked example — fraud detection with real numbers. A model screens \(N = 1000\) transactions: 20 are actually fraudulent (positive) and 980 are legitimate (negative). The model predicts: 15 frauds correctly (TP = 15), misses 5 frauds (FN = 5), flags 10 legitimate transactions as fraud (FP = 10), and correctly clears 970 (TN = 970).

Predicted Fraud Predicted Legit
Actually Fraud TP = 15 FN = 5
Actually Legit FP = 10 TN = 970

\[ \text{Accuracy} = \frac{15 + 970}{15 + 970 + 10 + 5} = \frac{985}{1000} = 0.985 \;(98.5\%) \]

\[ \text{Precision} = \frac{15}{15 + 10} = \frac{15}{25} = 0.60 \;(60\%) \]

\[ \text{Recall} = \frac{15}{15 + 5} = \frac{15}{20} = 0.75 \;(75\%) \]

\[ F_1 = 2 \cdot \frac{0.60 \times 0.75}{0.60 + 0.75} = 2 \cdot \frac{0.45}{1.35} = \frac{0.90}{1.35} \approx 0.667 \]

Why accuracy is dangerously misleading here: 98.5% sounds excellent, but the model misses 5 of 20 frauds — one in four frauds slips through — and wastes effort on 10 false alarms. Precision 60% says 40% of alerts are wrong; Recall 75% says a quarter of real fraud is missed. Sense-check: with only 2% fraud in the data, a model that "predicts legitimate for everything" would score 98% accuracy while catching zero fraud — which is why fraud and disease detection rely on Recall and F1 rather than Accuracy.

Assumptions & scope: all four metrics assume a binary target and a single operating threshold. On imbalanced data (rare positives), Accuracy is dominated by the majority class and becomes near-useless; Precision and Recall are threshold-dependent — raising the alarm threshold raises Precision but lowers Recall. There is a trade-off: you cannot have both perfect Precision and perfect Recall, which is exactly what F1 (the harmonic mean, penalizing imbalance between the two) summarizes.

Pitfalls:

  • Precision vs. Recall when it matters: in medical diagnostics and fraud detection, a missed positive (FN) can be catastrophic, so high Recall is prioritized; in spam filtering or legal screening, a false accusation (FP) is worse, so high Precision is prioritized.
  • Harmonic, not arithmetic, mean: F1 uses the harmonic mean because the arithmetic mean would let a high Precision hide a low Recall (e.g., 1.0 and 0.1 average to 0.55, but \(F_1 = 0.18\) — a genuinely poor balance).
  • Reporting Accuracy alone: on a 99:1 dataset, an Accuracy of 99% may be achieved by a model that predicts the majority class for everything.

12.7.2 Regression Evaluation Metrics

For regression tasks predicting continuous target values \(\hat{y}_i\) against ground truth values \(y_i\) over \(N\) evaluation samples:

  1. Mean Squared Error (MSE): Average squared difference between actual and predicted values:

\[ \text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2 \] MSE heavily penalizes large outlier errors due to the squaring operation.

  1. Root Mean Squared Error (RMSE): The square root of MSE, restoring error metrics back to the original physical units of the target variable \(y\):

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

  1. Mean Absolute Error (MAE): Average absolute magnitude of errors:

\[ \text{MAE} = \frac{1}{N} \sum_{i=1}^{N} |y_i - \hat{y}_i| \] MAE provides a linear error score robust to extreme outliers.

  1. R-Squared (\(R^2\) Coefficient of Determination): The proportion of variance in the dependent target variable explained by the regression model:

\[ R^2 = 1 - \frac{\sum_{i=1}^{N} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{N} (y_i - \bar{y})^2} \] where \(\bar{y} = \frac{1}{N}\sum_{i=1}^{N} y_i\) is the empirical mean of actual target values. An \(R^2 = 1.0\) indicates perfect model fit, while \(R^2 = 0.0\) indicates the model performs no better than predicting the mean value \(\bar{y}\).

Worked example — regression metrics with real numbers. A model predicts house prices for \(N = 3\) houses. Actual prices \(y = [2, 4, 6]\) (in lakhs); predictions \(\hat{y} = [3, 4, 5]\). Errors \(y_i - \hat{y}_i = [-1, 0, 1]\).

\[ \text{MSE} = \frac{(-1)^2 + 0^2 + 1^2}{3} = \frac{1 + 0 + 1}{3} = \frac{2}{3} \approx 0.667 \]

\[ \text{RMSE} = \sqrt{\frac{2}{3}} \approx 0.816 \text{ lakhs} \]

\[ \text{MAE} = \frac{|{-1}| + |0| + |1|}{3} = \frac{1 + 0 + 1}{3} = \frac{2}{3} \approx 0.667 \text{ lakhs} \]

For \(R^2\), the mean of actuals is \(\bar{y} = (2 + 4 + 6)/3 = 4\). The total sum of squares (variance the model must explain) is \(\text{SST} = (2-4)^2 + (4-4)^2 + (6-4)^2 = 4 + 0 + 4 = 8\). The residual sum of squares (unexplained error) is \(\text{SSE} = 2\). Therefore:

\[ R^2 = 1 - \frac{\text{SSE}}{\text{SST}} = 1 - \frac{2}{8} = 0.75 \]

Interpretation: the model explains 75% of the variance in house prices; a mean-only baseline would score \(R^2 = 0\). Sense-check: RMSE (0.816 lakhs) is back in the same units as the prices, so "about ₹82,000 average error" is directly interpretable, and \(R^2 = 0.75\) matches the intuition that the predictions are close but not exact.

Assumptions & scope: MSE/RMSE assume symmetric squared losses and therefore punish big outliers disproportionately — a single wild prediction can dominate the error. MAE treats all errors linearly and is robust to outliers but does not tell you about worst-case misses. \(R^2\) assumes the mean \(\bar{y}\) is a sensible baseline and can even go negative when the model is worse than predicting the mean. RMSE and MAE carry units; \(R^2\) is unitless, so it can be compared across different datasets.

Pitfalls:

  • Choosing MSE to hide outliers, or MAE to hide a few huge misses: pick by what the application punishes — safety-critical predictions care about the worst case (RMSE), routine estimates about typical error (MAE).
  • Reading \(R^2 = 1\) as "the model is always right": \(R^2 = 1\) means on this data predictions match perfectly; it says nothing about unseen data (overfitting can inflate \(R^2\)).
  • Comparing RMSE across differently scaled targets: RMSE is unit-dependent; compare \(R^2\) (unitless) or normalize instead.

Exam note: Construct a \(2 \times 2\) confusion matrix from problem statements; compute Accuracy, Precision, Recall, and F1-Score; explain why high recall is critical in fraud/disease detection. State regression metrics (MSE, RMSE, MAE, \(R^2\)) and explain their physical interpretations.

Recap + bridge: Classification models are judged through the confusion matrix — Accuracy (overall correctness), Precision (alarm quality), Recall (coverage of positives), and F1 (their balance) — while regression models are judged by error magnitudes (MSE, RMSE, MAE) and explained variance (\(R^2\)). With streaming ingestion, the ML pipeline, and evaluation metrics covered, this lecture's arc — from data in motion to judging the models trained on it — is complete.

Real-world: Fraud-detection and medical-screening systems deliberately optimize Recall, accepting more false alarms so that almost no real fraud or disease is missed; pricing and demand-forecasting systems report RMSE in the same currency as their forecasts so business users can read "average error per prediction" directly.


Exam Guidance Summary

Exam note: Review the following key exam topics and question patterns derived from this lecture:

  1. Spark Structured Streaming Output Modes:
  • Be prepared to compare Complete Mode, Update Mode, and Append Mode across memory resource usage, output emission frequency, and sink compatibility (4--5 marks).
  • Remember: Append Mode emits output only when a batch window is finalized by the watermark boundary.
  1. Watermarking Calculation & Trace Problems:
  • Practice multi-step numerical trace questions given trigger interval, batch window size, watermark delay threshold, and event tuples (event_time, key).
  • Calculate updated watermark boundaries using \(W = T_{\text{max}} - \Delta_{\text{watermark}}\).
  • Identify discarded late records (\(t_{\text{event}} < W\)) and state final window aggregate outputs.
  1. Definitions of Machine Learning:
  • Memorize Tom Mitchell's quantitative ML definition: Experience \(E\), Task \(T\), Performance Measure \(P\).
  • Given a application problem (e.g., self-driving car or email spam filter), identify the specific \(E\), \(T\), and \(P\).
  1. Supervised vs. Unsupervised Learning & Market Basket Analysis:
  • Distinguish between Regression (continuous target) and Classification (categorical target).
  • State formulas and calculate Support \(P(A \cap B)\), Confidence \(P(B \mid A)\), and Lift \(\frac{P(A \cap B)}{P(A)P(B)}\) for Association Rule Mining problems.
  1. Evaluation Metrics & Confusion Matrix Computations:
  • Construct a \(2 \times 2\) confusion matrix from problem statements.
  • Compute Accuracy, Precision, Recall, and F1-Score. Explain why high recall is critical in fraud/disease detection.
  • State regression metrics (MSE, RMSE, MAE, \(R^2\)) and explain their physical interpretations.

How to prepare for each pattern:

  • Output modes (4--5 marks): rehearse the three-way comparison table — what is written, when, and to which sinks — plus the one-line "finalized rows only" rule for Append.
  • Watermark traces: practice the trigger-by-trigger table format (new tuples → \(T_{\text{max}}\) → \(W\) → discarded → finalized windows) until the four columns are mechanical.
  • \(E\), \(T\), \(P\): for any given application, answer in the order "what is the task?", "what improves it?", "what number measures it?".
  • Support/Confidence/Lift: always write the three probabilities \(P(A)\), \(P(B)\), \(P(A \cap B)\) first, then plug them into the three formulas — and state the Lift interpretation (\(>1\), \(=1\), \(<1\)).
  • Confusion matrix: read the problem's numbers into the four cells before computing anything, then apply the four formulas and comment on why Accuracy alone is not enough on imbalanced data.

Key Industry Applications

Real-world: Apache Kafka serves as the standard streaming ingestion buffer, feeding live events into Spark Structured Streaming for fraud detection, metrics aggregation, and clickstream analytics.

Real-world: Complete Output Mode powers live web dashboards and metrics counters requiring a continuous full refresh of top-N key counters at every trigger boundary.

Real-world: Update Output Mode powers enterprise session state tables and user activity trackers (such as last login/logout events), minimizing network I/O by outputting only changed user records.

Real-world: Append Output Mode with event-time watermarking ensures append-only storage formats (such as Parquet or ORC data lakes) receive clean, deduplicated, finalized window outputs without data duplication or late-data corruption.

Real-world: Predictive feature engineering in big data pipelines prunes redundant features (such as height in centimeters vs. meters) to eliminate multicollinearity and improve model stability.

Real-world: Retail chains deploy Association Rule Mining (Apriori algorithm) to optimize store shelf layouts and inventory management—such as pairing beer near diaper aisles for weekend shoppers or stocking strawberry Pop-Tarts prior to forecasted hurricane events.

Real-world: Healthcare diagnostics employ machine learning classification models trained on audiometric decibel frequencies to deliver personalized hearing test calibrations.

The thread that ties them together: every application in this lecture is a slice of one end-to-end architecture — Kafka and Spark Streaming (Sections 12.1–12.4) move data while it is in motion, the ML pipeline (Sections 12.5–12.6) turns the accumulated data into predictive models, and evaluation metrics (Section 12.7) decide whether those models are safe to deploy. Choosing the right output mode and watermark is what keeps the data feeding those models clean.


BDA Lecture 12 notes

Big Data Analytics· postgraduate· 2026-08-01

Sections Breakdown

1Spark Streaming Architecture and Processing Models

Defines stream processing as analyzing data in motion before it rests in storage, contrasts batch vs stream processing, traces Spark's evolution from D-Streams (RDD-based) to Structured Streaming (unbounded input table on the DataFrame API), and positions Kafka as the decoupled ingestion broker enabling parallel consumption, fault tolerance, and exact-once semantics.

2Structured Streaming Output Modes

Explains the three Structured Streaming output modes: Complete Mode writes the entire result table every trigger, Update Mode writes only changed/new rows, and Append Mode writes only finalized rows (requiring a watermark). Includes fully worked Complete Mode word-count and Update Mode user-activity traces, a comparison table across memory, emission timing and sink compatibility, and the Q&A on why a long watermark does not make Append identical to Complete.

3Event Time Processing and Watermarking Protocol

Distinguishes ingestion time (when Spark receives an event) from event time (embedded in the record), and formalizes the watermark as W = T_max - Delta_watermark, where the watermark both discards late records at ingestion and finalizes windows whose end time the watermark has passed. Includes the PySpark withWatermark declaration and the two operational rules of the execution protocol.

4Step-by-Step Watermarking Walkthroughs

Works a complete Append-Mode watermarking scenario through six triggers (5-min trigger, 10-min windows, 10-min watermark), tracing the watermark W = T_max - 10 across -2 -> 4 -> 11 -> 16, discarding late tuples (3,bat) and (9,cat), and finalizing windows [0,10] then [5,15] with their emitted aggregates. Compares the same scenario in Update Mode, and answers Q&As on per-query watermark configuration and permanent discarding of late records.

5Machine Learning Fundamentals and Tool Ecosystem

Presents Arthur Samuel's qualitative ML definition (learning without explicit programming, demonstrated by self-playing checkers) and Tom Mitchell's quantitative definition with the Experience (E), Task (T), Performance (P) triple, with a worked table mapping E/T/P for spam filtering, self-driving, and house-price prediction. Surveys the tool ecosystem from low-code UI platforms (H2O.ai, RapidMiner, Azure ML Studio) through single-node scikit-learn/statsmodels to distributed Spark MLlib and Mahout.

6Machine Learning Taxonomy and End-to-End Pipeline

Describes the six-stage ML pipeline (collection, cleaning, feature engineering, training, evaluation, deployment) with a worked redundant-feature example, then the three learning paradigms: supervised (regression with the linear equation y = beta0 + beta1x1 + ... + eps, and classification), unsupervised (clustering via K-Means and association rule mining with fully worked Support/Confidence/Lift computations and the beer-diapers example), and reinforcement learning (agent, state, action, policy, reward, discounted return).

7Model Evaluation Metrics

Builds the 2x2 confusion matrix and derives Accuracy, Precision, Recall, and F1-Score with a fully worked fraud-detection example (N=1000, TP=15, FN=5, FP=10, TN=970) showing why Accuracy (98.5%) hides weak fraud coverage (Recall 75%, F1 0.667). Presents regression metrics MSE, RMSE, MAE, and R^2 with a worked three-house example (MSE=2/3, RMSE~0.816, MAE=2/3, R^2=0.75) and their physical interpretations.

8Exam Guidance Summary

Compiled exam revision guide covering the five examinable areas of Lecture 12: output-mode comparisons (Complete/Update/Append), watermark trace problems, the E/T/P ML definitions, Support/Confidence/Lift computations, and confusion-matrix and regression metrics, with a study-strategy callout for each pattern.

9Key Industry Applications

Collects the real-world deployments of the lecture: Kafka feeding Spark Structured Streaming for fraud and clickstream analytics, Complete Mode dashboards, Update Mode activity tracking, Append Mode data-lake pipelines, feature pruning for multicollinearity, retail Apriori shelf-layout optimization, and audiometric ML for personalized hearing tests.

Postgraduate students in Big Data Analytics

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.

Spark Streaming Architecture and Processing Models

Must-know: Batch = bounded data at rest on disk, results after the whole job; Stream = unbounded data in motion, results continuously. Structured Streaming models a stream as an unbounded input table and reuses the batch DataFrame API (spark.read -> spark.readStream); Kafka decouples producers and consumers and enables replay, fault tolerance, and exact-once semantics.

exactly-once semantics via a replayable Kafka log

⚑ Top pitfall: Assuming D-Streams are the current API; assuming stream results are instantly real-time (they arrive per trigger interval); assuming every DataFrame operation is stream-safe.

Self-check: What single change converts a batch DataFrame reader into a streaming one, and what stays identical downstream?

Connects to: Structured Streaming Output Modes.

Structured Streaming Output Modes

Must-know: Complete Mode re-emits the full result table every trigger (dashboard counters); Update Mode emits only changed/new rows (activity tracking); Append Mode emits only finalized rows, requires a watermark, and is the only mode valid for file sinks. Long watermarks delay Append output but do not turn it into Complete Mode.

Append Mode = only finalized rows, requires a watermark

⚑ Top pitfall: Using Complete or Update Mode on a file sink (files cannot be updated in place); running Append aggregations without a watermark (rejected); confusing 'final values match' with 'behaves identically'.

Self-check: In Complete Mode, is the 'dog' row rewritten at every trigger even when its count did not change, and why?

Connects to: Spark Streaming Architecture and Processing Models, Event Time Processing and Watermarking Protocol, Step-by-Step Watermarking Walkthroughs.

Event Time Processing and Watermarking Protocol

Must-know: W = T_max - Delta_watermark: the watermark is the maximum observed event time minus the user grace period. Rule 1: events with t_event < W are discarded at ingestion. Rule 2: a window [t_start, t_end] finalizes when W >= t_end, after which Append Mode emits it and purges its state. Watermarks are per-query via withWatermark, never global.

\[ W = T_{\text{max}} - \Delta_{\text{watermark}} \]

⚑ Top pitfall: Sizing the watermark threshold by guesswork (too small drops valid late data, too large delays output); watermarking the ingestion-time column instead of the event-time column.

Self-check: If the newest event seen has event time 26 and the threshold is 10 minutes, what is the watermark, and may a record with event time 9 still be processed?

Connects to: Structured Streaming Output Modes, Step-by-Step Watermarking Walkthroughs.

Step-by-Step Watermarking Walkthroughs

Must-know: Trace protocol: at each trigger recompute W = T_max - Delta; discard any arriving tuple with t_event < W; finalize a window [t_start, t_end] when the current watermark W >= t_end and emit it (Append). Watermark never moves backward. T_max is the max over all past events. Update Mode emits partial counts before finalization and stops emitting a window once finalized.

\[ W = T_{\text{max}} - \Delta_{\text{watermark}} \]

⚑ Top pitfall: Judging finalization with the newly computed watermark instead of the watermark current at that trigger; forgetting T_max never decreases; counting discarded tuples in window aggregates; missing that overlapping windows count a tuple in more than one window.

Self-check: At t_sys=25 the watermark is 11: which window finalizes, and why is the just-arrived tuple (3,'bat') discarded?

Connects to: Structured Streaming Output Modes, Event Time Processing and Watermarking Protocol.

Machine Learning Fundamentals and Tool Ecosystem

Must-know: Samuel (1959): learning without being explicitly programmed. Mitchell (1997): a program learns from experience E with respect to task T and performance measure P if its performance on T measured by P improves with E. To answer E/T/P problems: T = what it does, E = what it improves from, P = the measured score.

performance on task T, measured by P, improves with experience E

⚑ Top pitfall: Swapping Task (what the program does) with Performance (the score); assuming experience must be labeled data rather than environment interaction.

Self-check: For a spam filter, what are E, T, and P under Mitchell's definition?

Connects to: Machine Learning Taxonomy and End-to-End Pipeline, Model Evaluation Metrics.

Machine Learning Taxonomy and End-to-End Pipeline

Must-know: Regression target is continuous (y = beta0 + beta1x1 + ... + beta_d x_d + eps); classification target is categorical. For rule A->B: Support = Count(AUB)/N, Confidence = Count(AUB)/Count(A), Lift = Confidence/P(B) = P(A cap B)/(P(A)P(B)); Lift > 1 = positive association. RL maximizes the discounted return sum gamma^t r_t.

\[ \text{Confidence}(A \rightarrow B) = \frac{P(A \cap B)}{P(A)} = \frac{\text{Count}(A \cup B)}{\text{Count}(A)}, \qquad \text{Lift}(A \rightarrow B) = \frac{P(A \cap B)}{P(A) \cdot P(B)} \]

⚑ Top pitfall: High confidence on frequent B items can be meaningless (use Lift); correlation is not causation (beer and diapers); confidence and support are different questions (frequency vs reliability).

Self-check: If Count(A)=300, Count(B)=250, Count(A and B)=150 out of N=1000, compute Support, Confidence, and Lift for A->B.

Connects to: Machine Learning Fundamentals and Tool Ecosystem, Model Evaluation Metrics.

Model Evaluation Metrics

Must-know: Accuracy = (TP+TN)/(TP+TN+FP+FN); Precision = TP/(TP+FP); Recall = TP/(TP+FN); F1 = 2PR/(P+R). MSE = (1/N)sum(y-y_hat)^2; RMSE = sqrt(MSE); MAE = (1/N)sum|y-y_hat|; R^2 = 1 - SSE/SST. High Recall is critical in fraud/disease detection because missed positives are catastrophic; Accuracy misleads on imbalanced data.

\[ \text{Recall} = \frac{TP}{TP + FN}, \qquad F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}, \qquad R^2 = 1 - \frac{\sum_{i=1}^{N} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{N} (y_i - \bar{y})^2} \]

⚑ Top pitfall: Reporting Accuracy alone on imbalanced data (a model predicting the majority class can score 98%); using the arithmetic mean instead of the harmonic mean for F1; reading R^2 = 1 as generalization guarantee.

Self-check: With TP=15, FN=5, FP=10, TN=970, compute Accuracy, Precision, Recall, and F1, and explain why Accuracy alone hides the fraud-coverage problem.

Connects to: Machine Learning Taxonomy and End-to-End Pipeline, Machine Learning Fundamentals and Tool Ecosystem.

Exam Guidance Summary

Must-know: Compare output modes across memory/emission/sink; trace watermarks with W = T_max - Delta and discard t_event < W; state Mitchell's E/T/P definition; compute Support/Confidence/Lift; construct a 2x2 confusion matrix and compute Accuracy/Precision/Recall/F1 plus MSE/RMSE/MAE/R^2.

W = T_{\max} - \Delta_{\text{watermark}};\ \ \text{Recall} = \tfrac{TP}{TP+FN},\ F_1 = \tfrac{2PR}{P+R}

⚑ Top pitfall: Treating the exam guidance as optional reading — every pattern listed here maps to a likely exam question.

Self-check: Which output mode is the only one valid for file sinks, and what does it require?

Connects to: Structured Streaming Output Modes, Event Time Processing and Watermarking Protocol, Step-by-Step Watermarking Walkthroughs, Machine Learning Fundamentals and Tool Ecosystem, Machine Learning Taxonomy and End-to-End Pipeline, Model Evaluation Metrics.

Key Industry Applications

Must-know: Each concept maps to a named industry use: Kafka+Structured Streaming (fraud/clickstream), Complete (dashboards), Update (activity tracking), Append+watermark (data lakes), Apriori (retail layout), audiometric ML (personalized hearing tests).

Append + watermark → immutable data lake; Kafka + Structured Streaming → fraud detection

⚑ Top pitfall: Learning the concepts without a real-world anchor; the applications section shows why each design choice exists.

Self-check: Why is Append Mode with watermarking the right choice for a Parquet data lake?

Connects to: Spark Streaming Architecture and Processing Models, Structured Streaming Output Modes, Event Time Processing and Watermarking Protocol, Step-by-Step Watermarking Walkthroughs, Machine Learning Taxonomy and End-to-End Pipeline, Model Evaluation Metrics.

Was this lecture useful?

Loading comments…