shapiq.game.Game¶
- class shapiq.game.Game(n_players=None, *, normalize=True, normalization_value=None, verbose=False, player_names=None, **kwargs)[source]¶
Bases:
objectBase class for games/benchmarks/imputers in the
shapiqpackage.This class implements some common methods and attributes that all games should have.
- Properties:
n_values_stored: The number of values stored in the game. precomputed: Indication whether the game has been precomputed. normalize: Indication whether the game values are normalized. game_name: The name of the game.
- Variables:
_precompute_flag – A flag to manually override the precomputed check. If set to
True, the game is considered precomputed and only uses the lookup.n_players – The number of players in the game.
normalization_value – The value to normalize and center the game values with.
empty_coalition – The empty coalition of the game.
grand_coalition – The grand coalition of the game.
verbose – Whether to show a progress bar for the evaluation.
- Parameters:
Note
- This class is a base class and all games should inherit from this class and implement the
value_function methods. Usually, this Game class is only directly used when dealing with precomputed / stored games.
Examples
>>> from shapiq.game import Game >>> from shapiq_games.synthetic import DummyGame >>> game = DummyGame(4, interaction=(1, 2)) >>> game.precomputed, game.n_values_stored False, 0 >>> game.precompute() >>> game.precomputed, game.n_values_stored True, 16 >>> # precompute only a subset of coalitions >>> game = DummyGame(4, interaction=(1, 2)) >>> coals = np.asarray([[True, False, False, False], [False, True, True, False]]) >>> game.precompute(coalitions=coals) >>> game.precomputed, game.n_values_stored True, 2 >>> # store values >>> game.save_values("dummy_game.npz") >>> # load values in other game >>> new_game = DummyGame(4, interaction=(1, 2)) >>> new_game.load_values("dummy_game.npz") >>> game.precomputed, game.n_values_stored True, 2 >>> # save and load the game >>> game.save("game.pkl") >>> new_game = DummyGame.load("game.pkl") >>> new_game.precomputed, new_game.n_values_stored True, 2
Initialize the Game class.
- Parameters:
n_players (
int|None) – The number of players in the game.normalize (
bool) – Whether the game values should be normalized / centered. Defaults toTrue. IfTrue, the game values are normalized such that the value for the empty coalition is zero. IfFalse, the game values are not normalized and the value for the empty coalition is not guaranteed to be zero. This is useful for algorithms that require the game values to be centered.normalization_value (
float|None) – The value to normalize and center the game values with such that the value for the empty coalition is zero. Defaults toNone. Ifnormalizationis set toFalsethis value is not required. Otherwise, the value is needed to normalize and center the game. If no value is provided, the game raises a warning.verbose (
bool) – Whether to show a progress bar for the evaluation. Defaults toFalse. Note that this only has an effect if the game is not precomputed and may slow down the evaluation.player_names (
list[str] |None) – An optional list of player names. If provided, the coalitions can be provided as strings instead of integers.kwargs (
Any) – Additional keyword arguments (not used).
- classmethod get_game_name()[source]¶
Return the name of the game and the first class in the inheritance hierarchy.
- Return type:
- __call__(coalitions, *, verbose=False)[source]¶
Calls the game with the given coalitions.
Calls the game’s value function with the given coalitions and returns the output of the value function. The call also checks if the coalitions are in the correct format and converts if necessary. If the game is precomputed, the values are looked up in internal storage without calling the value function.
- Parameters:
- Return type:
- Returns:
The values of the coalitions.
- compute(coalitions)[source]¶
Compute the game values for all or a given set of coalitions.
- Parameters:
coalitions (
ndarray[tuple[Any,...],dtype[bool]]) – The coalitions to evaluate.- Returns:
The computed game values in the same order of the coalitions.
A lookup dictionary mapping from coalitions to the indices in the array.
The normalization value used to center/normalize the game values.
- Return type:
Note
This method does not change the state of the game and does not normalize the values.
Examples
>>> from shapiq_games.synthetic import DummyGame >>> game = DummyGame(4, interaction=(1, 2)) >>> game.compute(np.array([[0, 1, 0, 0], [0, 1, 1, 0]], dtype=bool)) (array([0.25, 1.5]), {(1): 0, (1, 2): 1.5}, 0.0)
- exact_values(index, order)[source]¶
Uses the ExactComputer to compute the exact interaction values.
- Parameters:
index (
Literal['SII','BII','CHII','Co-Moebius','SGV','BGV','CHGV','IGV','EGV','k-SII','STII','FSII','kADD-SHAP','FBII','SV','BV','JointSV','Moebius','ELC']) – The index to compute the interaction values for. Choose from{"SII", "k-SII"}.order (
int) – The maximum order of the interaction values.
- Returns:
The exact interaction values.
- Return type:
- load_values(path, *, precomputed=False)[source]¶
Loads the game values from the given path.
- Parameters:
path (
Path|str) – The path to load the game values from.precomputed (
bool) – Whether the game should be set to precomputed after loading the values no matter how many values are loaded. This can be useful if a game is loaded for a subset of all coalitions and only this subset will be used. Defaults toFalse.
- Return type:
- precompute(coalitions=None)[source]¶
Precompute the game values for all or a given set of coalitions.
The pre-computation iterates over the powerset of all coalitions or a given set of coalitions and stores the values of the coalitions in a dictionary.
- Parameters:
coalitions (
ndarray[tuple[Any,...],dtype[bool]] |None) – The set of coalitions to precompute. If None, the powerset of all coalitions will be used.- Return type:
Examples
>>> from shapiq_games.synthetic import DummyGame >>> game = DummyGame(4, interaction=(1, 2)) >>> game.precomputed, game.n_values_stored False, 0 >>> game.precompute() >>> game.precomputed, game.n_values_stored True, 16 >>> # precompute only a subset of coalitions >>> game = DummyGame(4, interaction=(1, 2)) >>> coals = np.asarray([[True, False, False, False], [False, True, True, False]]) >>> game.precompute(coalitions=coals) >>> game.precomputed, game.n_values_stored True, 2 >>> # store values >>> game.save_values("dummy_game.npz") >>> # load values in other game >>> new_game = DummyGame(4, interaction=(1, 2)) >>> new_game.load_values("dummy_game.npz")
Note
The pre-computation can be slow for a large number of players since the powerset of all coalitions is evaluated. If the number of players is greater than 16 and no coalitions are given, a warning is raised to inform the user about the potential slow computation.
- save(path, **kwargs)[source]¶
Saves and serializes the game object to the given path.
- Parameters:
path (
Path|str) – The path to save the game. If the path does not end with.json, it will be automatically appended.**kwargs (
dict[str,str|int|float|bool|None|Sequence[str|int|float|bool|None|Sequence[JSONType] |Mapping[str, JSONType]] |Mapping[str,str|int|float|bool|None|Sequence[JSONType] |Mapping[str, JSONType]]]) – Additional keyword arguments to pass toto_json_file().
- Return type:
- save_values(path, *, as_npz=False, **kwargs)[source]¶
Saves the game values to the given path.
- Parameters:
as_npz (
bool) – Whether to save the game as a numpy array (True) or as a JSON file. Defaults toFalse(saves as JSON file).**kwargs (
dict[str,str|int|float|bool|None|Sequence[str|int|float|bool|None|Sequence[JSONType] |Mapping[str, JSONType]] |Mapping[str,str|int|float|bool|None|Sequence[JSONType] |Mapping[str, JSONType]]]) – Additional keyword arguments to pass toto_json_file().
- Return type:
- to_json_file(path, *, desc=None, created_from=None, **kwargs)[source]¶
Saves the game as a JSON file.
- Parameters:
path (
Path) – Path to the JSON file. If the path does not end with.json, it will be automatically appended.desc (
str|None) – A description of the game. Defaults toNone.created_from (
object|None) – An object from which the game was created. Defaults toNone.**kwargs (
str|int|float|bool|None|Sequence[JSONType] |Mapping[str, JSONType]) – Additional keyword arguments to pass to the metadata block.
- Return type:
- value_function(coalitions)[source]¶
Returns the value of the coalitions.
The value function of the game, which models the behavior of the game. The value function is the core of the game and should be implemented in the inheriting class. A value function should return the worth of a coalition of players.
- Parameters:
coalitions (
ndarray[tuple[Any,...],dtype[bool]]) – The coalitions to evaluate.- Returns:
The values of the coalitions.
- Return type:
Note
This method has to be implemented in the inheriting class.
- property game_name: str¶
Return the name of the game and the first class in the inheritance hierarchy.
- game_values: dict[tuple[int, ...], float]¶
The mapping for coalitions to game values without normalization applied.