ExactComputer¶

Exact computation of Shapley values and interaction indices for small games using ExactComputer.

from __future__ import annotations

import numpy as np

import shapiq

N_PLAYERS = 8
feature_names = [f"x{i}" for i in range(N_PLAYERS)]

weights = np.array([0.4, 0.3, 0.2, 0.1, 0.05, -0.1, -0.2, -0.3])


def game_fun(coalitions: np.ndarray) -> np.ndarray:
    coalitions = np.atleast_2d(coalitions)
    return (coalitions @ weights) + 0.5 * coalitions[:, 0] * coalitions[:, 1]

Compute exact Shapley values¶

computer = shapiq.ExactComputer(game_fun, n_players=N_PLAYERS)
sv = computer(index="SV", order=1)
print(sv)
InteractionValues(
    index=SV, max_order=1, min_order=0, estimated=False, estimation_budget=None,
    n_players=8, baseline_value=0.0,
    Top 10 interactions:
        (0,): 0.6499999999999996
        (1,): 0.5499999999999997
        (2,): 0.20000000000000007
        (3,): 0.1
        (4,): 0.04999999999999996
        (): 0.0
        (5,): -0.10000000000000006
        (6,): -0.2000000000000001
        (7,): -0.29999999999999993
)

Force plot of Shapley values¶

sv.plot_force(feature_names=feature_names)
plot exact computer

Compute exact k-SII values¶

ksii = computer(index="k-SII", order=2)
print(ksii)
InteractionValues(
    index=k-SII, max_order=2, min_order=0, estimated=False, estimation_budget=None,
    n_players=8, baseline_value=0.0,
    Top 10 interactions:
        (0, 1): 0.5
        (0,): 0.3999999999999996
        (1,): 0.2999999999999997
        (2,): 0.20000000000000018
        (3,): 0.10000000000000002
        (4,): 0.04999999999999999
        (1, 5): -1.1102230246251565e-16
        (5,): -0.09999999999999994
        (6,): -0.2
        (7,): -0.29999999999999993
)

Force plot of k-SII values¶

ksii.plot_force(feature_names=feature_names)
plot exact computer

Network plot of k-SII values¶

ksii.plot_network(feature_names=feature_names)
plot exact computer

Total running time of the script: (0 minutes 0.636 seconds)