Lab 15: Choosing with Several Criteria (AHP and TOPSIS)¶
In this lab you rank options on several criteria: you screen out dominated options, derive weights with AHP, rank with a weighted sum and with TOPSIS, and test how far the weights can move before the answer changes. Then you apply the responsible-analytics checklist to your own capstone.
The question. Qahwa House must choose one importer for the green coffee of its house blend (about 50 tonnes a year) for the next two years. Five importers are scored on cost, quality, reliability, sustainability and supply risk. Which one should the board sign with, and how sure can it be?
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part D, try the ★ challenges.
Part E prepares your capstone defence: complete it with your team.
This lab is not graded (lab marks count the best 12 of Labs 1 to 14), but its last part is what you will be asked about at your defence.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
suppliers = load("qahwa_supplier_criteria.csv")
suppliers| Column | Meaning | Better when |
|---|---|---|
supplier, origin | the importer and where its coffee comes from | |
cost_sar_kg | landed price of green coffee, SAR per kg | lower |
cupping_score | quality on the specialty-coffee cupping scale, 0–100 | higher |
on_time_pct | share of the last 24 months’ shipments that arrived on time (%) | higher |
sustainability_score | the purchasing team’s audit score, 0–100 | higher |
supply_risk | the purchasing team’s risk rating, 1 (low) to 10 (high) | lower |
The importers and their scores are invented for this course.
Part A: The decision matrix¶
The cell below builds the decision matrix X (one row per importer, one column per criterion, as floats) and the Series better, which says for each criterion whether a lower or a higher value is better.
crit = ["cost_sar_kg", "cupping_score", "on_time_pct", "sustainability_score", "supply_risk"]
better = pd.Series(["low", "high", "high", "high", "low"], index=crit)
X = suppliers.set_index("supplier")[crit].astype(float)
XA1. Cost alone¶
Store in cheapest the name of the cheapest importer, and in extra_red_sea how much more Red Sea Traders would cost per year than the cheapest, for 50 tonnes (50,000 kg), in SAR.
cheapest = ...
extra_red_sea = ...
cheapest, extra_red_seacheck("A1 cost alone picks Santos Bulk", cheapest == "Santos Bulk")
check("A1 Red Sea Traders costs 250,000 SAR a year more", round(extra_red_sea) == 250_000)A2. Dominated options¶
Option a dominates option b when a is at least as good as b on every criterion and strictly better on at least one. The table good flips the sign of the lower is better criteria, so that higher is better everywhere. Complete dominates(a, b), then store in dominated the list of importers dominated by at least one other.
good = X.copy()
good.loc[:, better == "low"] *= -1 # now higher is better on every criterion
def dominates(a, b):
"""True if importer a is at least as good as b on every criterion and better on at least one."""
return ...
dominated = [b for b in X.index if any(dominates(a, b) for a in X.index if a != b)]
dominatedcheck("A2 one importer is dominated: Sidamo Link", dominated == ["Sidamo Link"])
check("A2 Harar Direct dominates it", dominates("Harar Direct", "Sidamo Link"))
check("A2 Santos Bulk is not dominated (it is the cheapest)", "Santos Bulk" not in dominated)From here on we work with the four importers that remain, X4.
X4 = X.drop(index=dominated)
X4Part B: Weights with AHP¶
The board compared the criteria two at a time on Saaty’s 1–9 scale (row against column; for example, cost is 4 times as important as sustainability):
| cost | quality | reliability | sustainability | risk | |
|---|---|---|---|---|---|
| cost | 1 | 1 | 2 | 4 | 2 |
| quality | 1 | 1 | 2 | 3 | 2 |
| reliability | 1/2 | 1/2 | 1 | 2 | 2 |
| sustainability | 1/4 | 1/3 | 1/2 | 1 | 1/2 |
| risk | 1/2 | 1/2 | 1/2 | 2 | 1 |
B1. The priority vector¶
The weights are the eigenvector of the largest eigenvalue of this matrix, scaled to add up to 1. Use np.linalg.eig(board): it returns the eigenvalues and a matrix whose columns are the eigenvectors (keep the real parts). Store the weights as a Series weights indexed by crit, and the largest eigenvalue in lam.
board = np.array([
[1, 1, 2, 4, 2 ],
[1, 1, 2, 3, 2 ],
[1/2, 1/2, 1, 2, 2 ],
[1/4, 1/3, 1/2, 1, 1/2],
[1/2, 1/2, 1/2, 2, 1 ],
])
eigvals, eigvecs = np.linalg.eig(board)
k = ... # the position of the largest eigenvalue
lam = ...
v = ... # its eigenvector (real parts, made positive)
weights = pd.Series(v / v.sum(), index=crit)
weights.round(3)check("B1 the weights add up to 1", abs(weights.sum() - 1) < 1e-9)
check("B1 cost weighs 30.8%", round(weights["cost_sar_kg"], 3) == 0.308)
check("B1 sustainability weighs least: 8.2%", weights.idxmin() == "sustainability_score" and round(weights.min(), 3) == 0.082)B2. Consistency¶
Compute the consistency index and the consistency ratio , with the random index = 1.12 for = 5 criteria. Store them in CI and CR.
n = len(board)
CI = ...
CR = ...
print(f"lambda max = {lam:.3f}, CI = {CI:.4f}, CR = {CR:.3f}")check("B2 CR = 0.015", round(CR, 3) == 0.015)
check("B2 below 0.10: the board's judgments are consistent enough", CR < 0.10)B3. A second opinion¶
The finance manager filled in the same comparisons. Write a function ahp(matrix) that returns the weights (as a Series indexed by crit) and the CR, then apply it to finance. Store the results in w_fin and CR_fin.
finance = np.array([
[1, 3, 1/2, 5, 3 ],
[1/3, 1, 3, 2, 1 ],
[2, 1/3, 1, 3, 2 ],
[1/5, 1/2, 1/3, 1, 1/2],
[1/3, 1, 1/2, 2, 1 ],
])
def ahp(matrix):
"""The AHP weights (a Series indexed by crit) and the consistency ratio of a 5 x 5 comparison matrix."""
...
w_fin, CR_fin = ahp(finance)
print(w_fin.round(3), f"\nCR = {CR_fin:.3f}")check("B3 the function gives the board's weights back", np.allclose(ahp(board)[0], weights))
check("B3 the finance manager's CR is 0.173", round(CR_fin, 3) == 0.173)
check("B3 above 0.10: the judgments should be revisited", CR_fin > 0.10)B4. Find the three judgments in finance that go round in a circle (A more important than B, B more important than C, but C more important than A). What would you say to the finance manager?
Your answer here (double-click to edit).
Part C: Two ranking methods¶
C1. Min–max normalisation and the weighted sum¶
Complete minmax(X) so that every criterion is on a 0-to-1 scale among the importers, with 1 for the best and 0 for the worst: when higher is better, when lower is better. Then store the weighted-sum scores of X4 with the board’s weights in wsm.
def minmax(X):
lo, hi = X.min(), X.max()
R = (X - lo) / (hi - lo) # right for the "higher is better" criteria
low = better[better == "low"].index
R[low] = ... # fix the "lower is better" criteria
return R
wsm = ...
wsm.sort_values(ascending=False).round(3)R = minmax(X4)
check("C1 the best importer on each criterion scores 1, the worst 0", (R.max() == 1).all() and (R.min() == 0).all())
check("C1 Santos Bulk scores 1 on cost", R.loc["Santos Bulk", "cost_sar_kg"] == 1)
check("C1 Red Sea Traders wins with 0.655", wsm.idxmax() == "Red Sea Traders" and round(wsm.max(), 3) == 0.655)
check("C1 Jazan Highlands is second with 0.619", wsm.sort_values().index[-2] == "Jazan Highlands" and round(wsm["Jazan Highlands"], 3) == 0.619)C2. TOPSIS¶
Complete topsis(X, weights), which returns the closeness of each importer:
divide each column by its length, , and multiply by the weights:
V;the ideal takes the best value of each column of
V(the largest if higher is better, the smallest otherwise), the anti-ideal the worst (given);the distances to both, and the closeness .
Store the closeness of X4 with the board’s weights in closeness.
def topsis(X, weights):
V = ...
ideal = ...
anti = pd.Series({c: V[c].min() if better[c] == "high" else V[c].max() for c in crit})
d_ideal = np.sqrt(((V - ideal) ** 2).sum(axis=1))
d_anti = ...
return d_anti / (d_ideal + d_anti)
closeness = topsis(X4, weights)
closeness.sort_values(ascending=False).round(3)check("C2 closeness is between 0 and 1", closeness.between(0, 1).all())
check("C2 TOPSIS also picks Red Sea Traders (0.639)", closeness.idxmax() == "Red Sea Traders" and round(closeness.max(), 3) == 0.639)
check("C2 Harar Direct is last (0.293)", closeness.idxmin() == "Harar Direct" and round(closeness.min(), 3) == 0.293)Part D: How sure is the answer?¶
with_weight(weights, criterion, value) sets one weight to value and scales the other four in proportion, so that the total stays 1.
D1. When does the winner change?¶
Using the grid grid (weights from 0 to 1 in steps of 0.001), store in flip_wsm the smallest sustainability weight above the board’s at which the weighted-sum winner is no longer Red Sea Traders, and in flip_topsis the same for TOPSIS.
def with_weight(weights, criterion, value):
w = weights * (1 - value) / (1 - weights[criterion])
w[criterion] = value
return w
def wsm_scores(w):
return (minmax(X4) * w).sum(axis=1)
grid = np.round(np.arange(0, 1.0005, 0.001), 3)
s = "sustainability_score"
flip_wsm = ...
flip_topsis = ...
print(flip_wsm, flip_topsis)check("D1 the weighted sum flips at a sustainability weight of 13.2%", round(flip_wsm, 3) == 0.132)
check("D1 TOPSIS flips at 14.1%", round(flip_topsis, 3) == 0.141)
check("D1 and the new winner is Jazan Highlands", wsm_scores(with_weight(weights, s, flip_wsm)).idxmax() == "Jazan Highlands")D2. “Let’s keep it neutral: equal weights”¶
A board member proposes 20% for every criterion. Store the weighted-sum winner with equal weights in winner_equal.
equal = pd.Series(0.2, index=crit)
winner_equal = ...
winner_equalcheck("D2 equal weights pick Jazan Highlands", winner_equal == "Jazan Highlands")
check("D2 and so does TOPSIS", topsis(X4, equal).idxmax() == "Jazan Highlands")D3. Your recommendation¶
Write three sentences for the board: which importer to sign with (with its scores under both methods and the cost difference with the runner-up), how sure the answer is (the flip points), and why equal weights are not a neutral choice.
Write your recommendation here (double-click to edit).
Part E: Before your defence¶
Apply the responsible-analytics checklist of the reading to your capstone. Answer each line in one or two sentences, with a number where one fits; your team should be able to give the same answers at the oral defence.
| # | Question | Your answer |
|---|---|---|
| 1 | Which decision does your app support, and which manager makes it? | |
| 2 | What are the alternatives, and what does the manager care about (objective or criteria)? | |
| 3 | Where does the data come from, how did you clean it, and does it contain personal data? | |
| 4 | What does the predictive part predict, and how large is its error on data it has not seen? | |
| 5 | What does the decision model recommend? | |
| 6 | Which inputs or weights would change the recommendation, and by how much? | |
| 7 | What does the model leave out, and what could go wrong if it is wrong? | |
| 8 | Does the recommendation affect groups of people differently? How did you check? | |
| 9 | What did you use AI for, and how did you check it? | |
| 10 | In one sentence, with a number: what should the manager do? |
E1. Pick the input or weight your recommendation is most sensitive to, and write the sentence for your memo: “If ... were ... instead of ..., we would recommend ... instead.”
Your answer to E1 here (double-click to edit).
★ Extended challenges¶
★1. Who gets the voucher? Rebuild Week 7’s churn model (data qahwa_members_2025.csv; pd.get_dummies on branch with drop_first=True; train_test_split(..., test_size=0.3, random_state=631, stratify=y); LogisticRegression(max_iter=1000)) and the rule send a voucher when p > 1/6. For each branch, compute on the test set the share of members who get a voucher and the share of leavers who get one (recall). Then fit the model again without the branch columns. How do the gaps between branches and the test-set profit (+50 SAR per leaver reached, −10 SAR per voucher sent to a member who stays) change?
★2. Negotiate. The board likes Jazan Highlands’ sustainability. At what price per kg (in steps of 0.5 SAR) would Jazan Highlands become the board’s choice under both methods, with the board’s weights? How much would that cost per year compared with Red Sea Traders at 31 SAR/kg?
★3. Your own weights. Fill in your own pairwise comparisons of the five criteria. Is your CR below 0.10? Which importer wins with your weights, under each method?
# ★1# ★2# ★3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.