The ethics code NovaMarket wrote in the previous lesson contains a concrete promise: "we measure the fairness of our models before deploying them and while they are running". And the course has been carrying two pending warnings: that a model learns from historical data and can inherit and amplify its biases (lesson 04-03), and that it can perform worse for certain groups of people (lesson 05-04). This lesson delivers on all three.
The central idea is that the fairness of an automated decision can be measured, with the same per-group aggregations you have been using since Module 3. You will see where biases come from, what exactly "treating people equally" means, how a decision is audited with PySpark and what can be done when the audit comes back badly. You will also see that there is no purely technical solution: measuring is a matter of code; deciding what is fair is not.
Warning. This lesson is for training purposes; it is not legal advice or an audit. Discrimination is regulated by equality, data protection and consumer law and, for certain systems, by the EU AI Act. Which attributes are protected, which differences in treatment are permissible and which mitigation measures are lawful are questions that must be reviewed with legal counsel, the data protection officer (DPO) and the compliance department. The thresholds that appear here are indicative.
What algorithmic bias is and where it comes from
In this context, algorithmic bias is a systematic and unjustified difference in the outcomes an automated system produces for different groups of people. It should not be confused with other meanings of the word you already know: the statistical bias of an estimator, or the skew in the distribution of data in lesson 03-04.
It almost never stems from intent. A model has no prejudices; it has data, and it finds in it any regularity that helps it predict, whether legitimate or not. Biases come in through several doors:
| Type | What happens | Example |
|---|---|---|
| Historical | The data faithfully reflects an unfair past | A recruitment model learns from hiring rounds in which there were almost no women |
| Representation or sampling | A group is under-represented in the data | A model trained on customers from big cities performs worse in rural areas |
| Measurement | The variable is measured less well, or differently, for one group | "Recorded returns" are used as a measure of dissatisfaction, but in some provinces returning items is harder |
| Labelling | The label was assigned by people, with their own criteria | "Fraud" means the cases someone decided to investigate, not all the ones that happened |
| Proxy variables | An apparently neutral variable stands in for a protected attribute | The postcode acts as an indicator of origin or income level |
| Aggregation | A single model for populations that behave differently | The same "unusual spending" threshold for pensioners and for businesses |
| Feedback loop | The model's decisions generate the data it will be retrained on | Only the orders the model flags are reviewed; fraud is found only there; the model "confirms" it was right |
The last one is the most treacherous in a Big Data system that retrains itself: the bias does not merely persist, it is amplified with every cycle.
Protected attributes and proxy variables
Protected attributes are characteristics on which the law prohibits discrimination: among others, sex, racial or ethnic origin, age, disability, religion or sexual orientation. The exact list and its scope depend on the legislation and the area.
The instinctive reaction is to leave them out of the model. That strategy, known as fairness through unawareness, does not work, because of proxy variables: columns that are not a protected attribute but are correlated with one. NovaMarket does not even collect its customers' age or sex, and yet it has proxies in the lake:
| Column | Can act as a proxy for |
|---|---|
province (and a postcode even more so) |
Income level, origin, rural or urban setting |
device |
Income level (handset range), age |
name |
Sex, origin |
| Browsing time, categories purchased | Employment status, age, family situation |
This leads to a practical paradox: to check that you are not discriminating on an attribute, you have to be able to measure it. If you do not have it, the audit is done with the available proxies, as we will do with device and province, or with data collected expressly for that purpose, with the appropriate safeguards.
What "fairness" means: four definitions
Imagine a binary decision: whether or not to offer a customer financing for a purchase. Let D be the system's decision (1 = offered), Y the reality (1 = the customer would have paid on time) and G the group they belong to. There are several ways, all of them reasonable, of defining that the system is fair between groups a and b:
| Definition | Requires equality between groups in | Formula | Idea |
|---|---|---|---|
| Demographic parity | The selection rate | P(D=1 | G=a) = P(D=1 | G=b) |
The same proportion of each group is selected |
| Equal opportunity | The true positive rate (TPR) | P(D=1 | Y=1, G=a) = P(D=1 | Y=1, G=b) |
Those who deserve it have the same probability of being selected, whatever their group |
| Equalised odds | The TPR and the false positive rate (FPR) | The above and P(D=1 | Y=0, G=a) = P(D=1 | Y=0, G=b) |
The model makes mistakes equally, in both directions, for both groups |
| Calibration | The meaning of the score | P(Y=1 | score=s, G=a) = P(Y=1 | score=s, G=b) |
A 0.7 means the same for everyone |
Remember from lesson 04-03 that the TPR is the recall: of the actual positives, how many the model gets right. The FPR is its counterpart: of the actual negatives, how many it wrongly flags as positive.
They cannot all be met at once. It has been proved that, when the actual proportion of positives (the base rate) differs between groups, an imperfect model cannot be calibrated and at the same time have the same error rates in all of them; and demographic parity conflicts with both. Choosing the definition is therefore a value judgement, which depends on the context:
- If the main harm is denying something to someone who deserved it (a loan, a job), equal opportunity is usually prioritised.
- If the harm of false positives also matters (being flagged as fraud without being so), equalised odds.
- If the label is not trusted because it may be biased, demographic parity is the only one that does not depend on it.
That choice belongs to the ethics committee and the business owners, not just to the technical team; and it is put in writing.
Metrics: per-group rates and disparate impact
All the definitions are checked in the same way: calculate a rate per group and compare them. The most widely used comparison for demographic parity is the disparate impact ratio:
disparate impact ratio = selection rate of the least favoured group
───────────────────────────────────────────
selection rate of the most favoured groupIt equals 1 when the rates are equal. The 80% rule (or four-fifths rule), which comes from US recruitment practice, is often used as a reference: a ratio below 0.8 is considered an indication of adverse impact and calls for the case to be examined. It is a rule of thumb, not a legal threshold in the European Union nor proof of discrimination; nor does a ratio above 0.8 prove that all is well.
For the other definitions, the differences in TPR and FPR between groups are compared. And a statistical precaution that the hands-on part will make obvious: rates for small groups are very noisy.
Hands-on: auditing a NovaMarket decision
NovaMarket wants to offer interest-free financing to some of its customers. A supplier has delivered a model that scores each customer from 0 to 1; the offer will go to those scoring above 0.5. Before deploying it, Irene asks for an audit: as you saw in lesson 07-03, deciding on financing is a particularly sensitive use.
An honest note about the data. The course data is synthetic and random: it contains no real bias to find, and there is no financing history. That is why the script simulates three things, explicitly and reproducibly: a label (whether the customer repaid a previous financing on time), the score of a "clean" model and a deliberate bias in the legacy model, which takes 0.12 points off customers who mainly use their mobile. Nothing that comes out describes real customers; what you are learning is the procedure.
Create ~/novamarket/audit_fairness.py:
from pathlib import Path
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
SEED = 42
THRESHOLD = 0.50
spark = SparkSession.builder.master("local[*]").appName("audit_fairness").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
segments = spark.read.parquet(str(LAKE / "gold" / "customer_segments"))
customers = spark.read.parquet(str(LAKE / "silver" / "customers"))
events = spark.read.parquet(str(LAKE / "silver" / "web_events"))
# 1. Each customer's predominant device (the one with the most events)
ranking = Window.partitionBy("customer_id").orderBy(F.desc("count"), "device")
predominant = (
events.where(F.col("customer_id").isNotNull() & F.col("device").isNotNull())
.groupBy("customer_id", "device").count()
.withColumn("pos", F.row_number().over(ranking)).where("pos = 1")
.select(F.col("customer_id").cast("int").alias("customer_id"),
F.when(F.col("device") == "mobile", "mobile").otherwise("non_mobile").alias("device_group"))
)
def randomness(name):
"""Reproducible pseudo-random number in [0, 1): depends on customer_id and the seed."""
return (F.abs(F.xxhash64("customer_id", F.lit(name), F.lit(SEED))) % 10000) / 10000
everyone = Window.orderBy("monetary")
base = (
segments.join(customers.select("customer_id", "province"), "customer_id")
.join(predominant, "customer_id")
.withColumn("pct_monetary", F.percent_rank().over(everyone))
.withColumn("pct_frequency", F.percent_rank().over(Window.orderBy("frequency")))
.withColumn("is_mobile", (F.col("device_group") == "mobile").cast("int"))
# 2. SIMULATED DATA. Label: did they repay a previous financing on time?
# It depends mainly on spending and, slightly, on the group (-0.05 for mobile)
# ("etiqueta" and "ruido" are arbitrary seed literals: leave them unchanged)
.withColumn("label", (randomness("etiqueta") < 0.15 + 0.70 * F.col("pct_monetary")
- 0.05 * F.col("is_mobile")).cast("int"))
# 3. "Clean" score: only spending, frequency and noise
.withColumn("clean_score", 0.55 * F.col("pct_monetary") + 0.25 * F.col("pct_frequency")
+ 0.20 * randomness("ruido"))
# 4. SIMULATED, DELIBERATE BIAS: the legacy model takes 0.12 points off mobile users
.withColumn("legacy_score", F.col("clean_score") - 0.12 * F.col("is_mobile"))
.cache()
)
def rates(df, decision, by):
"""Selection rate, TPR and FPR of a (0/1) decision for each value of `by`."""
return (df.groupBy(by).agg(
F.count("*").alias("n"),
F.round(F.avg(decision), 3).alias("selection_rate"),
F.round(F.avg(F.when(F.col("label") == 1, F.col(decision))), 3).alias("tpr"),
F.round(F.avg(F.when(F.col("label") == 0, F.col(decision))), 3).alias("fpr"),
F.round(F.avg("label"), 3).alias("base_rate"),
F.round(F.avg("pct_monetary"), 3).alias("spend_pct"),
).orderBy(by))
def summary(df, decision, name):
f = {r["device_group"]: r for r in rates(df, decision, "device_group").collect()}
m, o = f["mobile"], f["non_mobile"]
accuracy = df.agg(F.avg((F.col(decision) == F.col("label")).cast("int"))).first()[0]
ratio = min(m["selection_rate"], o["selection_rate"]) / max(m["selection_rate"], o["selection_rate"])
print(f"{name:<26} sel. mobile={m['selection_rate']:.3f} non_mobile={o['selection_rate']:.3f} "
f"ratio={ratio:.2f} | TPR {m['tpr']:.3f}/{o['tpr']:.3f} | "
f"FPR {m['fpr']:.3f}/{o['fpr']:.3f} | accuracy={accuracy:.3f}")
# 5. Audit of the legacy model
audited = base.withColumn("decision", (F.col("legacy_score") >= THRESHOLD).cast("int"))
print("Rates by predominant device (legacy model):")
rates(audited, "decision", "device_group").show()
print("Selection rates by province (legacy model):")
by_prov = rates(audited, "decision", "province").select("province", "n", "selection_rate")
max_rate = by_prov.agg(F.max("selection_rate")).first()[0]
by_prov.withColumn("ratio_vs_max", F.round(F.col("selection_rate") / max_rate, 2)) \
.orderBy("selection_rate").show(20)
# 6. Mitigations
no_proxy = base.withColumn("decision", (F.col("clean_score") >= THRESHOLD).cast("int"))
# Separate threshold for the mobile group: the one that matches its selection rate to the other group's
target_rate = no_proxy.where("device_group = 'non_mobile'").agg(F.avg("decision")).first()[0]
mobile_threshold = base.where("device_group = 'mobile'").approxQuantile(
"clean_score", [1 - target_rate], 0.0)[0]
by_group = base.withColumn("decision", (F.col("clean_score") >= F.when(
F.col("device_group") == "mobile", mobile_threshold).otherwise(THRESHOLD)).cast("int"))
print(f"General threshold: {THRESHOLD:.2f} Adjusted threshold for mobile: {mobile_threshold:.3f}\n")
summary(audited, "decision", "A. Legacy model")
summary(no_proxy, "decision", "B. Without proxy variable")
summary(by_group, "decision", "C. B + per-group threshold")
spark.stop()- Step 1. A window (lesson 03-03) gives each customer's device with the most events. It is reduced to two groups,
mobileandnon_mobile, for a reason you will see in the output: very small groups do not allow any conclusions to be drawn. - The
randomnessfunction. Instead ofF.rand, whose result depends on how the data is spread across partitions, it uses a hash ofcustomer_idand the seed: the same customer always gets the same number. The string literals passed to it ("etiqueta","ruido") are just arbitrary seeds; changing them would change every figure in the output. - Steps 2 to 4.
percent_rankplaces each customer between 0 and 1 according to their spending and their frequency (columns ofgold/customer_segments). With that, the label, the clean score and the legacy score are simulated, the last being the clean score minus the mobile penalty. - The
ratesfunction. It is the core of any audit, and it is a simplegroupBy. Since the decision is 0 or 1, its mean is the selection rate.F.whenwithoutotherwisereturns null when the condition is not met, andavgignores nulls: that way the mean is calculated only over the actual positives (TPR) or only over the negatives (FPR). - Steps 5 and 6. The legacy model is audited by device and by province, and then three strategies are compared.
Run python audit_fairness.py. The first part of the output:
Rates by predominant device (legacy model): +------------+---+--------------+-----+-----+---------+---------+ |device_group| n|selection_rate| tpr| fpr|base_rate|spend_pct| +------------+---+--------------+-----+-----+---------+---------+ | mobile|883| 0.307|0.447|0.188| 0.459| 0.489| | non_mobile|117| 0.615|0.761|0.391| 0.607| 0.583| +------------+---+--------------+-----+-----+---------+---------+ Selection rates by province (legacy model): +-------------+---+--------------+------------+ | province| n|selection_rate|ratio_vs_max| +-------------+---+--------------+------------+ | Zaragoza| 26| 0.231| 0.51| | Las Palmas| 14| 0.286| 0.63| | Alicante| 80| 0.288| 0.63| | Asturias| 22| 0.318| 0.7| | Sevilla| 62| 0.323| 0.71| | Madrid|193| 0.326| 0.72| |Illes Balears| 24| 0.333| 0.73| | Barcelona|155| 0.342| 0.75| | Murcia| 52| 0.346| 0.76| | Castellon| 46| 0.348| 0.76| | NULL| 20| 0.35| 0.77| | Valencia|213| 0.366| 0.8| | Bizkaia| 29| 0.379| 0.83| | Malaga| 31| 0.452| 0.99| | A Coruna| 33| 0.455| 1.0| +-------------+---+--------------+------------+
Reading by device. The model offers financing to 30.7% of mobile customers and to 61.5% of the rest: a disparate impact ratio of 0.307 / 0.615 = 0.50, well below 0.8. It does not meet demographic parity. Nor does it meet equal opportunity: among the customers who would have paid, it selects 44.7% of mobile users compared with 76.1% of the others. The last two columns add a nuance: the groups do not start out equal. The base rate is lower for mobile (0.459 compared with 0.607), partly because that is how it was simulated and partly by pure chance: the 117 customers in the small group happen to spend somewhat more (mean percentile 0.583 compared with 0.489). So part of the difference has an explanation; the audit must establish how much.
Reading by province. No bias has been introduced here, and yet eleven rows fall below 0.8 and Zaragoza scores 0.51. It is noise: Zaragoza has 26 customers, and the reference, A Coruña, 33. With groups like these, a handful of people shift the rate by several points, and comparing everything against the maximum exaggerates the effect. If you compare against the largest group, Valencia, Madrid gets 0.326 / 0.366 = 0.89. Two rules: never interpret a ratio without looking at n, and with small groups you merge categories, calculate confidence intervals or wait until you have more data. It is the same reason why the device was reduced to two groups: only three customers mainly use a tablet.
Mitigation: before, during and after training
Once the problem has been detected, there are three points at which to act:
| Point | Techniques | Pros and cons |
|---|---|---|
| Before (on the data) | Collect more data from the under-represented group; rebalance or reweight (give more weight to the rows of scarce group-and-label combinations, using the weightCol weights column from lesson 04-03); remove or transform proxy variables; review the labels |
Tackles the cause; not always enough, because other variables can reconstruct the proxy |
| During (in training) | Add fairness constraints to the optimisation problem, or a regularisation term that penalises the difference between groups | Good balance between fairness and performance; requires specific algorithms |
| After (on the decisions) | Different thresholds per group; human review of cases close to the threshold | Simple, and applicable to a third-party model; uses the group explicitly in the decision, which can be legally sensitive |
The script has already tried a pre-processing technique (B: removing the proxy variable) and a post-processing one (C: additionally adjusting the disadvantaged group's threshold to equalise the selection rates). The second part of the output:
General threshold: 0.50 Adjusted threshold for mobile: 0.389 A. Legacy model sel. mobile=0.307 non_mobile=0.615 ratio=0.50 | TPR 0.447/0.761 | FPR 0.188/0.391 | accuracy=0.651 B. Without proxy variable sel. mobile=0.467 non_mobile=0.615 ratio=0.76 | TPR 0.617/0.761 | FPR 0.339/0.391 | accuracy=0.648 C. B + per-group threshold sel. mobile=0.616 non_mobile=0.615 ratio=1.00 | TPR 0.778/0.761 | FPR 0.479/0.391 | accuracy=0.646
| Strategy | Disparate impact ratio | TPR difference | FPR difference | Accuracy |
|---|---|---|---|---|
| A. Legacy model | 0.50 | 0.314 | 0.203 | 0.651 |
| B. Without proxy variable | 0.76 | 0.144 | 0.052 | 0.648 |
| C. B + per-group threshold | 1.00 | 0.017 | 0.088 | 0.646 |
Four conclusions:
- Removing the proxy fixes most of it. The ratio goes from 0.50 to 0.76 and accuracy barely changes (from 0.651 to 0.648: three customers in every thousand, within the noise). The remaining difference comes from the groups differing in spending.
- Forcing parity has a price, small in this case. With C the ratio reaches 1.00 and the TPR is almost equalised, in exchange for another two thousandths of accuracy. This is the fairness–performance trade-off: in this simulation it is minimal; in real cases it can be larger, and it has to be measured rather than assumed.
- Fixing one metric unsettles another. In C, the FPR of the mobile group (0.479) now exceeds that of the other group (0.391): financing is offered to more mobile customers who would not pay. This is the impossibility from the earlier section, seen in numbers.
- Bias can be "statistically useful". Model A is, by the narrowest of margins, the most accurate, because the simulated label is somewhat worse for mobile. A real model would do the same: exploit any correlation. The fact that a variable improves prediction does not make it legitimate; and you would have to ask whether the label itself carries a historical bias. That decision is not made by a metric.
NovaMarket adopts strategy B, requires the supplier to provide a model without the device, sends cases close to the threshold for human review and leaves option C to the judgement of the ethics committee and legal counsel.
Explainability
A per-group audit tells you that there is a difference; explainability helps you find out why. Two levels:
- Global: which variables carry weight in the model. Spark MLlib's tree models expose
featureImportances, and a logistic regression exposes its coefficients. Ifdeviceorprovinceappear among the most influential variables in a financing model, there is a question to be asked. - Local: why this decision for this customer. Techniques such as SHAP and LIME estimate how much each variable contributed to a specific prediction. They are what makes it possible to answer a customer who asks why they did not receive the offer, and what the human reviewer needs in order to do more than rubber-stamp the model.
When the decision seriously affects people, a simple, interpretable model that performs slightly worse is often a better choice than an opaque one. And a warning: explanations are approximations, not the truth of the model.
Documentation: model cards and datasheets
Two short documents have become common practice. The datasheet for a dataset describes how the data was collected, whom it represents and whom it does not, and its known limitations; it extends the data dictionary of lesson 05-02. The model card accompanies every deployed model. NovaMarket's, in summary:
| Section | Content |
|---|---|
| Model | Score for the interest-free financing offer, version 2 (without the device variable) |
| Intended use | Deciding which registered customers are shown the offer. It must not be used to refuse financing that has been applied for, to set prices or to assess new customers |
| Training data | Customers with at least one order between January and June 2026; label: on-time repayment of previous financing. Limitation: it does not represent customers with no history |
| Variables | Spending and frequency (RFM). Excluded: name, province, device |
| Performance | Accuracy 0.648 with a 0.5 threshold |
| Fairness | By predominant device: disparate impact ratio 0.76; TPR difference 0.144. By province: inconclusive with the current sample size |
| Chosen fairness criterion | Equal opportunity; maximum tolerated TPR difference: 0.10 (not yet met: deployed with human review) |
| Human oversight | Review of cases scoring between 0.40 and 0.60; complaints route |
| Owner and review | Owner: sales management. Metrics review: monthly. Approved by the data ethics committee |
The value of the card is that it forces you to write down the uncomfortable things: what the model is not for, and which criterion it does not yet meet.
Continuous auditing, human oversight and tools
Fairness is not checked once. Data changes, the customer population changes, and feedback loops work silently. What NovaMarket sets up:
- Fairness metrics are quality rules. Per-group rates are calculated on every run and stored as a series, just like
gold/daily_quality(lesson 05-02); a ratio below the agreed threshold raises an alert. - An audit before every deployment and every retraining, with the result documented in the card.
- Real human oversight. Reviewers need time, information (the explanation of the case) and the authority to overrule the model. A reviewer who always confirms what the system proposes is a well-known case, automation bias, and is not overseeing anything.
- A complaints route for the customer, and periodic analysis of complaints as a source of detection.
There is no need to code everything by hand. Fairlearn calculates per-group metrics and implements mitigation techniques (constraints during training and threshold optimisation); AIF360 (AI Fairness 360) brings together a broad catalogue of metrics and algorithms for all three phases, including reweighting. Both work on pandas and scikit-learn: with large data, apply the rule from lesson 04-01, "aggregate big, analyse small".
Common Mistakes and Tips
- "We don't use the attribute, so we don't discriminate." Proxies reconstruct it. You have to measure the outcome, not check the list of columns.
- Looking only at the overall metric. 90% accuracy can hide 95% for one group and 60% for another. Always disaggregate.
- Interpreting ratios for small groups. Look at
nbefore drawing conclusions, in either direction. - Trusting the label. If the historical label is biased, a model that reproduces it perfectly is perfectly unfair.
- Choosing the fairness definition after the fact. It is decided before seeing the results, or you will end up picking the one the model already meets.
- Treating it as a purely technical problem. Which difference is acceptable is a value judgement, with legal implications.
- Auditing once. Feedback loops erode fairness over time.
- Tip: add a
groupByover the relevant groups to every analysis of a model. It costs one line and it is the cheapest audit there is.
Exercises
Exercise 1: recognise the type of bias
Identify the main type of bias: a) a fraud detection model is retrained every month only on the orders the model itself sent for review; b) the recommender system was trained on data from the app, which is used mainly by young customers; c) a model for allocating promotions uses the postcode and ends up excluding entire neighbourhoods; d) "satisfaction" is predicted using as the label whether the customer wrote a positive review.
Exercise 2: calculate by hand
A model makes decisions about 300 customers. Group A: 200 customers, 120 of them good payers; it selects 100, of whom 80 are good payers. Group B: 100 customers, 50 good payers; it selects 30, of whom 25 are. Calculate the selection rates, the disparate impact ratio, and the TPR and FPR of each group, and say which fairness definitions are violated.
Exercise 3: equal opportunity
Strategy C equalises the selection rates. Add to the script a strategy D that, starting from the clean score, adjusts the threshold of the mobile group to match its TPR to that of the other group. Compare the result with C.
Solutions
Exercise 1
a) Feedback loop: the model only learns from what it chose to look at itself; it is corrected by also reviewing a random sample of unflagged orders. b) Representation: it will perform worse for those who shop on the website. c) Proxy variable (probably combined with historical bias). d) Measurement and labelling: writing reviews is not the same as being satisfied, and not all groups write them equally.
Exercise 2
- Selection rate: A = 100/200 = 0.50; B = 30/100 = 0.30. Disparate impact ratio = 0.30 / 0.50 = 0.60, below 0.8.
- TPR: A = 80/120 = 0.667; B = 25/50 = 0.50.
- FPR: in A there are 80 bad payers and 20 are selected → 0.25; in B there are 50 and 5 are selected → 0.10.
Demographic parity (0.50 versus 0.30), equal opportunity (0.667 versus 0.50) and, therefore, equalised odds are all violated. Notice that the model is stricter with B in both directions: it selects fewer good and fewer bad payers, as if it applied a higher threshold to it.
Exercise 3
Before spark.stop():
target_tpr = no_proxy.where("device_group = 'non_mobile' AND label = 1").agg(F.avg("decision")).first()[0]
eo_threshold = base.where("device_group = 'mobile' AND label = 1").approxQuantile(
"clean_score", [1 - target_tpr], 0.0)[0]
equal_opp = base.withColumn("decision", (F.col("clean_score") >= F.when(
F.col("device_group") == "mobile", eo_threshold).otherwise(THRESHOLD)).cast("int"))
print(f"Threshold for mobile that equalises the TPR: {eo_threshold:.3f}")
summary(equal_opp, "decision", "D. B + equal opportunity")Threshold for mobile that equalises the TPR: 0.406 D. B + equal opportunity sel. mobile=0.600 non_mobile=0.615 ratio=0.98 | TPR 0.763/0.761 | FPR 0.462/0.391 | accuracy=0.648
The difference from step 6 lies in over whom the quantile is calculated: now only over mobile customers who are good payers (label = 1), because it is their selection rate that you want to equalise. The resulting threshold (0.406) is slightly less generous than C's (0.389); the TPR is equalised (0.763 versus 0.761), the disparate impact ratio stands at 0.98 and accuracy at 0.648, the same as in B. Here the two definitions lead almost to the same place because the base rates do not differ much; the more they differ, the further apart they will drift. Remember that this strategy depends on the label: if the label is not reliable, neither is the adjustment.
Conclusion
Algorithmic bias is a systematic and unjustified difference between groups, and it is almost never born of intent: it comes in through historical data, lack of representation, the way things are measured and labelled, proxy variables and feedback loops. You have seen that not using an attribute does not prevent discrimination on it; that "fairness" has several definitions (demographic parity, equal opportunity, equalised odds, calibration) that cannot all be met at once; and that auditing them comes down to calculating per-group rates. With PySpark you have found a disparate impact ratio of 0.50 in a model with a planted bias, confirmed that small groups are misleading, and measured the effect of mitigating before and after: a lot of fairness gained, little accuracy lost and one metric that worsens when another improves. The technique is completed with explainability, model cards, continuous monitoring and human oversight that genuinely oversees. And the decision about what is fair remains a human one.
This lesson brings Module 7 to a close. It started with security: who can access the data, how it is encrypted and how an incident is detected. It continued with privacy: what it is legitimate to do with people's data, and how to analyse without identifying. It went up a step with ethics: what, while legal, perhaps should not be done. And it has ended by turning one of its principles, fairness, into something that is calculated and monitored. NovaMarket's platform does not just work: it can now explain to its customers what it does with their data and why they can trust it.
What remains is to look ahead. Everything you have learned describes Big Data as it is today, and this is a field that changes shape every few years: open lakehouses, self-managing platforms, the practices for taking models into production and keeping them there, which have been promised since lesson 04-03, and an artificial intelligence that is transforming both what is done with data and the way people work with it. Module 8, The Future of Big Data, closes the course with that perspective. Its first lesson, Emerging Trends, surveys the currents that are redefining data platforms and will help you tell the ones worth following closely from those that are just noise.
