# XAI Experiment 4: PDP-Based Feature Importance (numerical & categorical)  [exam version]
# Requires: exam: none (math) | lab: numpy, pandas
# ===========================================================================

import math

# Dataset: Age, Income, Category
X = [
    [20, 30000, "A"],
    [30, 40000, "B"],
    [40, 50000, "A"],
    [50, 60000, "C"]
]

# Model prediction
def model(x):
    return 0.01*x[0] + 0.0001*x[1] + {"A": 0.1, "B": 0.2, "C": 0.3}[x[2]]

names = ["Age", "Income", "Category"]
types = ["num", "num", "cat"]

importance = []

for j in range(len(names)):

    values = sorted(set(row[j] for row in X))
    pdp = []

    for v in values:
        total = 0

        for row in X:
            temp = row[:]
            temp[j] = v
            total += model(temp)

        pdp.append(total / len(X))

    print("\nFeature:", names[j])
    print("PDP values:", pdp)

    if types[j] == "num":
        if len(pdp) < 2:
            imp = 0
            print("Importance cannot be calculated (K=1)")
        else:
            mean = sum(pdp) / len(pdp)
            imp = math.sqrt(sum((v-mean)**2 for v in pdp) / (len(pdp)-1))
    else:
        imp = (max(pdp) - min(pdp)) / 4

    importance.append(imp)
    print("Importance:", round(imp, 4))

print("\nFEATURE IMPORTANCE RANKING")

for i in sorted(range(len(names)), key=lambda i: importance[i], reverse=True):
    print(names[i], round(importance[i], 4))
