So far, everything you have done with NovaMarket's data describes what has already happened: how much was sold, how many sessions bought something, how the amounts are distributed. Machine learning (ML) takes the next step, that of the predictive and prescriptive analytics introduced in lesson 01-02: using past data to anticipate what will happen, or to discover structures that nobody has defined in advance.
Three of NovaMarket's four use cases are machine learning problems: demand forecasting, recommendations and fraud detection. In this lesson you will understand what ML contributes and why massive data changes it, you will get to know the types of learning and the workflow of a project, and you will build two complete models with Spark MLlib: a customer segmentation and a classifier that tries to predict which sessions end in a purchase. The second will teach you something more valuable than a good result: to distrust a result that is too good and to read the metrics honestly.
What machine learning contributes and what massive data changes
In traditional programming, a person writes the rules: "if a customer makes three purchases in ten minutes, raise a fraud alert" (the rule from lesson 03-05). In machine learning, the rules are learnt from examples: an algorithm is given a history of cases, and it fits a model, a function that generalises to new cases. It is worthwhile when the rules are too many, too subtle or change too quickly to be written by hand.
The minimum vocabulary:
| Term | Meaning | Example at NovaMarket |
|---|---|---|
| Feature | Each input variable of the model | Number of products viewed in the session |
| Label | What you want to predict | Whether the session ended in a purchase |
| Training | The process of fitting the model with examples | Learning from June's sessions |
| Model | The result of training | The function that scores a new session |
| Inference or prediction | Applying the model to new data | Scoring today's sessions |
What changes when the data is massive?
- More data tends to beat a better algorithm. This is a classic observation in the industry: a simple algorithm trained on a huge number of examples often outperforms a sophisticated one trained on few. With caveats: the data must be relevant and of good quality, and the benefit levels off. Ten times more data with no signal still has no signal, as you are about to see.
- Data preparation becomes the bottleneck. Building the features from billions of events is a distributed processing problem: joins, aggregations and windows, what you learnt in Module 3. In practice, it is most of the work.
- Training may not fit on one machine. There are two strategies, and choosing well between them saves a lot of money:
| Training on one machine | Distributed training | |
|---|---|---|
| Typical tool | scikit-learn | Spark MLlib |
| Data | Must fit in memory | Spread across the cluster |
| Range of algorithms | Very wide | Narrower: only those that parallelise well |
| Speed with small data | Very fast | Slow, because of the overhead of the distributed system |
| When | The training set, once aggregated or sampled, is manageable | The training set is huge even after aggregation |
Types of learning
| Type | What it learns | Does it need labels? | NovaMarket case |
|---|---|---|---|
| Supervised: classification | To assign a category | Yes | Is this order fraudulent? Will this session end in a purchase? |
| Supervised: regression | To predict a number | Yes | Demand forecasting: units of each product that will be sold next week |
| Unsupervised: clustering | To form groups of similar items | No | Customer segmentation by purchasing behaviour |
| Recommendation | To estimate the affinity between users and products | Uses the interactions | "You might also be interested in..." |
In supervised learning you have examples with the correct answer, and the model learns to reproduce it. In unsupervised learning there is no answer: the algorithm looks for structure on its own, and it is the analyst who afterwards interprets what it has found. Recommendation is a family of its own, with specific algorithms, which you will see at the end.
The workflow of an ML project
Training the model is one step among many, and not the longest:
flowchart LR
A["1. Problem<br>definition"] --> B["2. Feature<br>engineering"]
B --> C["3. Split<br>training / test"]
C --> D["4. Training"]
D --> E["5. Evaluation"]
E -->|"not good enough"| B
E -->|"acceptable"| F["6. Deployment<br>and monitoring"]
F -.->|"the data changes"| A
- Definition. What you want to predict, in order to make which decision, and with what metric you will know whether it works. A model with no associated decision is an academic exercise.
- Feature engineering. Turning the raw data into a table with one row per example and one column per feature. This is where business knowledge counts, and where the most serious mistakes live.
- Split. Part of the data, the test set, is set aside and the model does not see it while it learns. It is the only honest way of knowing how it will behave with new data: a model evaluated on its own training data is a pupil sitting an exam with questions they had already worked out.
- Training. The algorithm fits the model with the training set.
- Evaluation. It is measured on the test set. If the result is not good enough, you go back, almost always to the features.
- Deployment and monitoring. The model is put to work and checked to make sure it keeps getting things right.
The risk that the split lets you detect is called overfitting: a model that memorises the training examples, noise included, instead of learning the general pattern. It is extremely accurate with what it has already seen and fails with anything new.
Spark MLlib: transformers, estimators and pipelines
MLlib is Spark's machine learning library. Its current API, the one that works on DataFrames, is in the pyspark.ml package (there is an older one, pyspark.mllib, based on RDDs, which should not be used in new projects). It comes included in PySpark and only needs numpy, which you already installed along with pandas. It rests on three concepts:
| Concept | What it is | Main method | Examples |
|---|---|---|---|
| Transformer | Converts one DataFrame into another, adding columns | transform(df) |
VectorAssembler, a model that has already been trained |
| Estimator | Something that learns from the data and produces a transformer | fit(df) |
KMeans, LogisticRegression, StringIndexer, StandardScaler |
| Pipeline | An ordered chain of transformers and estimators, trained and applied as a single piece | fit(df) and then transform(df) |
Preparation + model |
The distinction between the first two is the key: an estimator needs to see the data in order to fit itself (fit) and returns a model, which is a transformer. KMeans is an estimator; the KMeansModel returned by its fit is a transformer that adds each row's group to it.
MLlib's algorithms have a peculiar requirement: they expect all the features gathered into a single vector-type column. These pieces take care of preparing it:
VectorAssembler: combines several numeric columns into one vector column. It is a pure transformer.StringIndexer: converts a text column into numeric indices (mobile→ 0,desktop→ 1...). It is an estimator: it must first learn which values exist.OneHotEncoder: converts each index into a vector of zeros with a single one. This stops the model from interpreting the indices as a magnitude, as iftablet(2) were "twice"desktop(1).StandardScaler: rescales each feature so that it has a mean of 0 and a standard deviation of 1.
The Pipeline chains these pieces together with the algorithm. Its advantage is not just convenience: it guarantees that the test data, and later the production data, undergo exactly the same preparation that was learnt from the training data.
Example 1: customer segmentation with K-Means
Problem. Marketing wants to treat different customers differently, but nobody has defined the groups. It is a clustering problem. The EDA in the previous lesson ended with the open question of what sets the highest-spending customers apart; here it is answered.
Features. The classic RFM model is used, which sums up each customer with three numbers:
- Recency: days elapsed since their last purchase.
- Frequency: number of orders.
- Monetary: total spend.
Algorithm. K-Means splits the items into k groups. It places k centres, assigns each customer to the nearest centre, moves each centre to the mean of its customers and repeats until nothing changes. Because it measures distances, the features must be on the same scale: without rescaling, the monetary value (tens of thousands of euros) would crush the recency (a few days).
Create ~/novamarket/segment_customers.py:
from pathlib import Path
from pyspark.ml import Pipeline
from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import ClusteringEvaluator
from pyspark.ml.feature import StandardScaler, VectorAssembler
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("segment_customers").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.parquet(str(LAKE / "silver" / "orders_complete"))
# 1. Feature engineering: one row per customer with their RFM variables
REF_DATE = "2026-07-01"
rfm = (
orders.where(F.col("status") != "returned")
.groupBy("customer_id")
.agg(
F.datediff(F.lit(REF_DATE), F.max("order_date")).alias("recency"),
F.count("*").alias("frequency"),
F.round(F.sum("total_amount"), 2).alias("monetary"),
)
)
rfm.orderBy("customer_id").show(3)
# 2. Pipeline pieces: feature vector -> scaling -> K-Means
assembler = VectorAssembler(inputCols=["recency", "frequency", "monetary"],
outputCol="vector")
scaler = StandardScaler(inputCol="vector", outputCol="features",
withMean=True, withStd=True)
evaluator = ClusteringEvaluator(featuresCol="features", predictionCol="segment")
# 3. How many groups? Several values of k are tried
for k in range(2, 7):
kmeans = KMeans(k=k, seed=42, featuresCol="features", predictionCol="segment")
model = Pipeline(stages=[assembler, scaler, kmeans]).fit(rfm)
silhouette = evaluator.evaluate(model.transform(rfm))
print(f"k={k} silhouette={silhouette:.3f}")
# 4. Final model with k=3 and a profile of each segment
kmeans = KMeans(k=3, seed=42, featuresCol="features", predictionCol="segment")
model = Pipeline(stages=[assembler, scaler, kmeans]).fit(rfm)
segmented = model.transform(rfm)
(segmented.groupBy("segment")
.agg(F.count("*").alias("customers"),
F.round(F.avg("recency"), 1).alias("avg_recency"),
F.round(F.avg("frequency"), 1).alias("avg_frequency"),
F.round(F.avg("monetary"), 0).alias("avg_monetary"),
F.round(F.sum("monetary") / 1e6, 2).alias("sales_millions"))
.orderBy(F.desc("avg_monetary")).show())
# 5. The result is saved in the gold zone
(segmented.select("customer_id", "recency", "frequency", "monetary", "segment")
.coalesce(1).write.mode("overwrite").parquet(str(LAKE / "gold" / "customer_segments")))
spark.stop()- Step 1. The feature engineering is ordinary Spark: a
groupByby customer.F.datediffgives the days between the reference date (the day after the last day of the period) and the last order. Returns are excluded. - Step 2.
VectorAssemblergathers the three columns intovector;StandardScalerrescales them intofeatures.ClusteringEvaluatorcalculates the silhouette coefficient, which measures from −1 to 1 how compact and well separated the groups are: the higher, the better. - Step 3. K-Means does not decide how many groups there are: you give it k. The usual approach is to try several values and compare.
seed=42fixes the initial position of the centres so that the result is reproducible. - Step 4.
Pipeline(...).fit(rfm)trains the whole chain and returns a model; itstransformadds thesegmentcolumn. Then agroupBydescribes each group: a clustering is only useful if its groups can be described. - Step 5. The assignments are saved in a new table,
gold/customer_segments.
+-----------+-------+---------+--------+ |customer_id|recency|frequency|monetary| +-----------+-------+---------+--------+ | 1| 3| 24|34366.52| | 2| 13| 21|33302.52| | 3| 7| 16|21261.34| +-----------+-------+---------+--------+ only showing top 3 rows k=2 silhouette=0.521 k=3 silhouette=0.558 k=4 silhouette=0.481 k=5 silhouette=0.461 k=6 silhouette=0.447 +-------+---------+-----------+-------------+------------+--------------+ |segment|customers|avg_recency|avg_frequency|avg_monetary|sales_millions| +-------+---------+-----------+-------------+------------+--------------+ | 2| 407| 7.3| 22.9| 39868.0| 16.23| | 0| 137| 31.1| 16.6| 28311.0| 3.88| | 1| 456| 7.5| 16.2| 25863.0| 11.79| +-------+---------+-----------+-------------+------------+--------------+
The silhouette is highest with k = 3, and all three groups have a business interpretation (the segment numbers are arbitrary and may change on your machine; what matters is the profile):
| Segment | Profile | Name for marketing | Possible action |
|---|---|---|---|
| 2 | 407 customers; bought a week ago; 23 orders; almost €40,000 each | The best customers: 41% of the base contributes 51% of sales | Look after them: loyalty programme, early access |
| 1 | 456 customers; just as recent, but with fewer orders and less spend | Regulars with moderate spend | Increase their basket: cross-selling |
| 0 | 137 customers; their last purchase was a month ago, on average | At risk of churning | Reactivation campaign before they are lost |
Two honest caveats. The practice customers buy far more than those of any real shop (some 20 orders in six months), so the absolute figures are not realistic. And K-Means always returns k groups, whether or not they exist in the data: a silhouette of 0.56 indicates a reasonable structure, not sharp boundaries. The at-risk segment, however, is real: it is separated by recency, which the EDA had not looked at.
Example 2: predicting which sessions end in a purchase
Problem. If NovaMarket knew which sessions were most likely to buy, it could offer help or an incentive to the undecided ones. It is a binary classification: the label is 1 if the session contains a purchase event and 0 if not.
It is also the promise outstanding since lesson 03-05. Fraud detection is the same kind of problem: a binary classification in which the class of interest is the minority. There you solved it with a fixed rule; ML makes it possible to learn patterns that no rule captures. What you learn here about imbalanced classes and metrics applies, with even greater force, to fraud, where the positive class is not 23% but often less than 0.1%.
A warning before you start. The practice events are random, and the EDA put it on record: the purchase rate does not depend on the device, the time of day or whether the visitor is identified. Do not expect a good model. What you are going to learn is how to evaluate it.
Create ~/novamarket/predict_purchase.py:
from pathlib import Path
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("predict_purchase").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
events = spark.read.parquet(str(LAKE / "silver" / "web_events"))
def count_of(event_type):
return F.sum((F.col("event_type") == event_type).cast("int"))
# 1. Feature engineering: one row per session, with its label
not_purchase = F.col("event_type") != "purchase"
sessions = (
events.groupBy("session_id")
.agg(
count_of("product_view").alias("num_views"),
count_of("search").alias("num_searches"),
count_of("add_to_cart").alias("num_cart"),
count_of("purchase").alias("num_purchases"),
F.countDistinct("product_id").alias("products_all"),
F.countDistinct(F.when(not_purchase, F.col("product_id"))).alias("products_viewed"),
F.hour(F.min("event_time")).alias("start_hour"),
F.max(F.col("customer_id").isNull()).cast("int").alias("anonymous"),
F.coalesce(F.first("device", ignorenulls=True),
F.lit("unknown")).alias("device"),
)
.withColumn("label", (F.col("num_purchases") > 0).cast("double"))
).cache()
sessions.groupBy("label").count().orderBy("label").show()
# 2. Split: 80% for training, 20% for testing
training, test = sessions.randomSplit([0.8, 0.2], seed=42)
print("Training:", training.count(), " Test:", test.count())
def build_pipeline(numeric, classifier):
indexer = StringIndexer(inputCol="device", outputCol="device_idx",
handleInvalid="keep")
encoder = OneHotEncoder(inputCol="device_idx", outputCol="device_vec")
assembler = VectorAssembler(inputCols=numeric + ["device_vec"],
outputCol="features")
return Pipeline(stages=[indexer, encoder, assembler, classifier])
def evaluate(name, predictions):
auc = BinaryClassificationEvaluator(metricName="areaUnderROC").evaluate(predictions)
m = {(int(r["label"]), int(r["prediction"])): r["count"]
for r in predictions.groupBy("label", "prediction").count().collect()}
tp, fp = m.get((1, 1), 0), m.get((0, 1), 0)
fn, tn = m.get((1, 0), 0), m.get((0, 0), 0)
accuracy = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
print(f"{name}: TP={tp} FP={fp} FN={fn} TN={tn} | accuracy={accuracy:.3f} "
f"precision={precision:.3f} recall={recall:.3f} AUC={auc:.3f}")
BASE = ["num_views", "num_searches", "num_cart", "start_hour", "anonymous"]
# 3. First attempt
lr = LogisticRegression(maxIter=50)
attempt = build_pipeline(BASE + ["products_all"], lr).fit(training)
evaluate("First attempt", attempt.transform(test))
spark.stop()- Step 1. Each session is summarised in one row: counts by event type, distinct products, start time, whether it is anonymous and the device (the first non-null one;
unknownif there is none). The label, which MLlib expects by default in alabelcolumn of typedouble, is 1 if there was any purchase.cache()avoids recalculating the aggregation for every training run. - Step 2.
randomSplitdivides the rows at random; the seed makes the split reproducible (even so, the exact number of rows may vary slightly from one machine to another). build_pipelineassembles the chain:StringIndexerandOneHotEncoderfor the device,VectorAssemblerto gather everything intofeatures(the name the algorithms look for by default) and, at the end, the classifier.handleInvalid="keep"avoids an error if a never-before-seen device turns up in production.evaluatecalculates the metrics in the next section from thelabelandpredictioncolumns.- Step 3. A logistic regression, the simplest classifier: it calculates a score as a weighted sum of the features and converts it into a probability between 0 and 1.
+-----+-----+ |label|count| +-----+-----+ | 0.0|23777| | 1.0| 6982| +-----+-----+ Training: 24517 Test: 6242 First attempt: TP=1305 FP=0 FN=129 TN=4808 | accuracy=0.979 precision=1.000 recall=0.910 AUC=0.976
22.7% of sessions contain a purchase. And the model is right 97.9% of the time. Did we not agree that the data was random?
Data leakage
A result that is too good is a warning sign. There is data leakage here: a feature that contains, openly or in disguise, the answer you are trying to predict.
The obvious form would have been to include num_purchases among the features: the model would "predict" that there is a purchase when there is a purchase, with 100% accuracy and no usefulness whatsoever. That one has not been used. The leak is in products_all, which counts the distinct products of all the events in the session, including the purchase event itself. The purchased product adds one to the count, and the model has learnt the trick: if there are more distinct products than the views and carts explain, there must have been a purchase. It is not predicting: it is doing a subtraction.
The rule for avoiding it: every feature must be calculated using only information available at the moment the prediction would be made. The script already had the correct version ready, products_viewed, which excludes the purchase events. Replace step 3 with:
# 3. Honest model: no information about the purchase
HONEST = BASE + ["products_viewed"]
model = build_pipeline(HONEST, LogisticRegression(maxIter=50)).fit(training)
evaluate("Logistic", model.transform(test))
# 4. The same model, giving more weight to the minority class
proportion = training.where("label = 1").count() / training.count()
weight = F.when(F.col("label") == 1, 1 - proportion).otherwise(proportion)
lr_weights = LogisticRegression(maxIter=50, weightCol="weight")
model_weights = build_pipeline(HONEST, lr_weights).fit(training.withColumn("weight", weight))
evaluate("With weights", model_weights.transform(test))Logistic: TP=0 FP=0 FN=1434 TN=4808 | accuracy=0.770 precision=0.000 recall=0.000 AUC=0.588 With weights: TP=851 FP=2108 FN=583 TN=2700 | accuracy=0.569 precision=0.288 recall=0.593 AUC=0.588
Reading the metrics
The first four figures make up the confusion matrix: TP (true positives: predicted purchases that really were purchases), FP (false positives: a purchase was predicted and there was none), FN (false negatives: purchases the model did not see) and TN (true negatives). The metrics are derived from them:
| Metric | Question it answers | Formula |
|---|---|---|
| Accuracy | What fraction of the predictions is correct? | (TP + TN) / total |
| Precision | Of those I predicted as a purchase, how many were? | TP / (TP + FP) |
| Recall | Of the actual purchases, how many did I detect? | TP / (TP + FN) |
| AUC | Taking at random one session with a purchase and one without, how likely is the first to score higher? | Area under the ROC curve |
With them, the two results read as follows:
- The first model has 77% accuracy and is completely useless. It predicts "no purchase" for every session (TP = 0). It is right 77% of the time because 77% of sessions do not buy. This is the trap of accuracy with imbalanced classes: a fraud detector that never detects anything would have an accuracy of 99.9%. Always compare with the dumbest possible baseline, which here is "always say no".
- The weighted model does predict purchases, at a price.
weightColmakes getting a purchase wrong cost more during training. Recall rises to 59%, but precision is 29%: of every ten sessions flagged, seven do not buy. And since 23% of sessions buy anyway, flagging at random would give a precision of 23%. The improvement is minimal. - Precision and recall pull in opposite directions, and which error is more expensive is for the business to decide. In fraud, a false negative is a completed fraud and a false positive, an honest customer blocked. There is no universal optimum.
- AUC summarises the ability to rank, regardless of the threshold: 0.5 is equivalent to tossing a coin and 1 to a perfect model. A value of 0.588 is very close to chance. And notice that it is identical in both models: the weights have not added any information, they have only moved the decision threshold.
Where does that small advantage over chance come from? From a mechanical effect: in this data every event has the same probability of being a purchase, so sessions with more events have more tickets in the draw. It is not a behavioural pattern. What is more, it hides a subtler, temporal leak: the total number of views in a session is only known once the session has ended, and by then there is nothing left to predict. A model meant to act live should use only what happened in the first few minutes.
The conclusion is the one the EDA foretold: no algorithm extracts signal from where there is none. With real data, where purchasing does depend on what the visitor looks at, how long they take and their history, this same code would produce a useful model. And the method for evaluating it would be exactly the same.
Recommendation with ALS
The fourth use case, recommendations, is tackled with collaborative filtering: recommending to each customer what customers with similar tastes liked, without needing to know anything about the products.
The starting point is an enormous matrix, with one row per customer and one column per product, where each cell indicates how much that customer has interacted with that product. Almost all of it is empty: nobody has seen more than a tiny fraction of the catalogue. The ALS algorithm (Alternating Least Squares) factorises it: it describes each customer and each product with a short vector of numbers, the latent factors, so that the affinity between a customer and a product is the product of their vectors. The factors have no names, but they end up capturing tastes ("interested in high-end audio"). With them you can estimate any empty cell and recommend those with the highest value. ALS parallelises very well, and that is why it is MLlib's recommendation algorithm.
The following snippet is illustrative. It uses the interactions of identified customers as its signal (implicit feedback: there are no star ratings, only behaviour):
from pyspark.ml.recommendation import ALS
interactions = (
events.where("customer_id IS NOT NULL AND product_id IS NOT NULL")
.groupBy("customer_id", "product_id")
.agg(F.count("*").alias("interactions"))
)
als = ALS(userCol="customer_id", itemCol="product_id", ratingCol="interactions",
implicitPrefs=True, # behaviour, not explicit ratings
rank=10, # number of latent factors
regParam=0.1, maxIter=10,
coldStartStrategy="drop", # ignores customers or products with no history
seed=42)
als_model = als.fit(interactions)
als_model.recommendForAllUsers(3).show(3, truncate=False) # 3 products per customerThe code works with the practice data, but its recommendations mean nothing: customers view products at random, and there are no tastes to discover. Two limits that are real: the cold start (a new customer or product has no interactions, and you have to fall back on the best sellers or the product's attributes) and the 30% of anonymous sessions, which can only be given recommendations based on what they do in the session itself.
When a single machine is enough, and what happens after training
Aggregate big, train small
Look at the first example again. The RFM table has 1,000 rows. Even at the real NovaMarket it would have 2 million rows and three columns: a few tens of megabytes. You do not need a cluster to train on that. The rule from lesson 04-01 applies here too:
# pip install scikit-learn
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
data = rfm.toPandas() # the aggregate, not the orders
X = StandardScaler().fit_transform(data[["recency", "frequency", "monetary"]])
data["segment"] = KMeans(n_clusters=3, random_state=42, n_init=10).fit_predict(X)
print(data.groupby("segment")[["recency", "frequency", "monetary"]].mean().round(1))Spark calculates the features over all the orders, and scikit-learn trains on the driver, in a fraction of a second. The result is the same three groups, of 407, 456 and 137 customers. This pattern, Spark for the features and a single-machine library for the model, solves a large share of real projects, and gives access to a much wider catalogue of algorithms.
MLlib is reserved for when the training table is still huge after aggregation: billions of interactions for ALS, or hundreds of millions of examples for a classifier. Another legitimate option is to train on a sample (lesson 04-02), if the model does not improve with more data; it is worth checking this by training with increasing sizes.
After training
A model in a notebook does not change any decision. Putting it into production raises new questions:
- How are the predictions served? In batches (every night all customers are scored and the result is saved in a table, such as
gold/customer_segments) or online (each session or each payment is scored in milliseconds, as fraud requires). - How is it saved and versioned? An MLlib pipeline is persisted with
model.write().overwrite().save(path)and recovered withPipelineModel.load(path), preparation included. - When does it stop being valid? Customer behaviour changes and the model ages (drift). Its metrics need to be monitored and it must be retrained periodically, with an orchestrated pipeline like those in lesson 03-06.
The set of practices that deals with all this is called MLOps, and you will find it in lesson 08-01. And there is a question that comes before any deployment: a model learns from historical data and can inherit and amplify its biases; lesson 07-04 is devoted to detecting and mitigating them.
Common Mistakes and Tips
- Evaluating with the training data. It measures the model's memory, not its ability to generalise.
- Celebrating a spectacular result. An AUC of 0.98 at the first attempt is almost always data leakage. Look for the feature that "knows too much".
- Calculating features with information from the future. Ask yourself, column by column: would I have this at the moment of predicting?
- Trusting accuracy with imbalanced classes. Look at the confusion matrix, precision, recall and AUC, and compare with the trivial baseline.
- Forgetting to scale in distance-based algorithms, such as K-Means: the feature with the largest magnitude would dominate.
- Treating a category as a number. Without
OneHotEncoder, a linear model would believe that theStringIndexerindices have order and magnitude. - Preparing the data outside the pipeline. If the scaling is fitted on all the data before splitting, the test set leaks into training. Inside the
Pipeline, the preparation is learnt from the training data alone. - Taking the groups of a clustering as real. K-Means always returns k groups. If you cannot describe them or associate an action with them, they are no use.
- Using a cluster to train on a thousand rows. Aggregate with Spark and train on one machine.
- Tip: before training anything, build the simplest possible baseline (always predicting the majority class, or the mean). If your model does not clearly beat it, the problem lies in the data or the features, not the algorithm.
Exercises
Exercise 1: identifying the type of problem
For each NovaMarket need, state the type of learning, what the label would be (if there is one) and a reasonable metric or success criterion:
- Estimating how many units of each television will be sold next week.
- Deciding, at the moment of payment, whether an order should go to manual review for possible fraud.
- Grouping the 200 products according to how they sell, without predefined categories.
- Showing, on a product's page, others that might interest that customer.
Exercise 2: another algorithm, same data
In predict_purchase.py, train a random forest (RandomForestClassifier(numTrees=50, maxDepth=5, seed=42), from the pyspark.ml.classification module) with the honest features and evaluate it. Does it beat the logistic regression? Interpret the result.
Exercise 3: four segments
Marketing asks for four segments instead of three. Change k in segment_customers.py, describe the groups and reason out what is gained and what is lost.
Solutions
Exercise 1
- Regression (supervised). Label: units sold per product and week. Metric: the average forecasting error, in units, compared with a simple baseline such as "the same as last week". With the practice data, which has no seasonality, there would be no point in trying.
- Binary classification, highly imbalanced. Label: whether the order turned out to be fraudulent, which becomes known weeks later, with the chargebacks. Metric: recall with an agreed minimum precision (how many frauds are detected without swamping the review team); never accuracy.
- Clustering (unsupervised). There is no label. Criterion: the silhouette and, above all, that the groups can be described and used.
- Recommendation (collaborative filtering, for example with ALS). It uses the interactions as its signal. Real success criterion: customers clicking on or buying what is recommended, measured with an A/B test (lesson 04-05).
Exercise 2
from pyspark.ml.classification import RandomForestClassifier
forest = RandomForestClassifier(numTrees=50, maxDepth=5, seed=42)
model_rf = build_pipeline(HONEST, forest).fit(training)
evaluate("Forest", model_rf.transform(test))A random forest combines many decision trees and captures relationships that are not linear. The AUC rises from 0.588 to 0.623: a marginal improvement, still very close to chance. It detects 17 purchases out of 1,434 (recall of 1.2%), all of them correct; they are an artefact of the data: sessions made up solely of purchase events, with no views or carts, something that does not exist in a real shop.
The correct reading: changing the algorithm does not fix the lack of signal. When a simple model and a complex one perform almost equally badly, the way forward is not to try a third, but to go back to the features and the data.
Exercise 3
With k=4 (silhouette 0.481, lower than for k=3), the profile becomes:
| Customers | Average recency | Average frequency | Average spend |
|---|---|---|---|
| 164 | 7.4 days | 25.4 | €45,276 |
| 409 | 7.4 days | 20.2 | €33,939 |
| 302 | 7.9 days | 14.9 | €23,232 |
| 125 | 32.0 days | 16.6 | €28,607 |
The at-risk group stays almost the same (125 customers, recency of 32 days), and the recent customers are now split into three spending tiers instead of two. You gain granularity: an elite of 164 customers emerges, each spending more than €45,000. You lose clarity: the three recent groups are bands on the same continuous scale, not natural groups, which is why the silhouette falls. It is a legitimate business decision if marketing is going to treat that elite differently; if not, the three segments are more robust and easier to explain.
Conclusion
Machine learning learns from examples the rules that nobody would know how to write. With massive data, most of the work goes into feature engineering, which is ordinary distributed processing, and you have to decide whether training needs a cluster or whether, once the data has been aggregated, one machine is enough. You have distinguished the types of learning (classification, regression, clustering, recommendation), walked through the workflow of a project and used Spark MLlib with its transformers, estimators and pipelines. With K-Means on RFM variables you have obtained three customer segments with a business interpretation, saved in gold/customer_segments. And with the purchase classifier you have learnt the lessons that prevent the most mistakes: data leakage produces miraculous models, accuracy is misleading with imbalanced classes, precision and recall are bought at each other's expense, and no algorithm gets signal out of data that has none.
A model, just like a table of statistics, convinces very few people on its own. The three customer segments are much easier to understand when drawn than when described, and the text histogram from the previous lesson was crying out for a proper chart. In the next lesson, Data Visualisation, you will learn to turn NovaMarket's aggregates into clear, honest charts: which chart to choose depending on the question, how to plot millions of rows without plotting millions of points and which design mistakes turn a chart into a deception.
