pydvl.valuation.methods
¶
BetaShapleyValuation
¶
BetaShapleyValuation(
utility: UtilityBase,
sampler: IndexSampler,
is_done: StoppingCriterion,
alpha: float,
beta: float,
progress: bool = False,
skip_converged: bool = False,
)
Bases: SemivalueValuation
Computes Beta-Shapley values.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Object to compute utilities.
TYPE:
|
sampler
|
Sampling scheme to use.
TYPE:
|
is_done
|
Stopping criterion to use.
TYPE:
|
skip_converged
|
Whether to skip converged indices. Convergence is determined
by the stopping criterion's
TYPE:
|
alpha
|
The alpha parameter of the Beta distribution.
TYPE:
|
beta
|
The beta parameter of the Beta distribution.
TYPE:
|
progress
|
Whether to show a progress bar. If a dictionary, it is passed to
TYPE:
|
Source code in src/pydvl/valuation/methods/beta_shapley.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
ClasswiseShapleyValuation
¶
ClasswiseShapleyValuation(
utility: ClasswiseModelUtility,
sampler: ClasswiseSampler,
is_done: StoppingCriterion,
progress: dict[str, Any] | bool = False,
*,
normalize_values: bool = True,
)
Bases: Valuation
Class to compute Class-wise Shapley values.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Class-wise utility object with model and class-wise scoring function.
TYPE:
|
sampler
|
Class-wise sampling scheme to use.
TYPE:
|
is_done
|
Stopping criterion to use.
TYPE:
|
progress
|
Whether to show a progress bar. |
normalize_values
|
Whether to normalize values after valuation.
TYPE:
|
Source code in src/pydvl/valuation/methods/classwise_shapley.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
DataBanzhafValuation
¶
DataBanzhafValuation(
utility: UtilityBase,
sampler: IndexSampler,
is_done: StoppingCriterion,
skip_converged: bool = False,
show_warnings: bool = True,
progress: dict[str, Any] | bool = False,
)
Bases: SemivalueValuation
Computes Banzhaf values.
Source code in src/pydvl/valuation/methods/semivalue.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
BaggingModel
¶
Bases: Protocol
Any model with the attributes n_estimators
and max_samples
is considered a
bagging model.
fit
¶
DataOOBValuation
¶
DataOOBValuation(model: BaggingModel, score: PointwiseScore | None = None)
Bases: Valuation
Computes Data Out-Of-Bag values.
This class implements the method described in (Kwon and Zou, 2023)1.
PARAMETER | DESCRIPTION |
---|---|
model
|
A fitted bagging model. Bagging models in sklearn include
[[BaggingClassifier]], [[BaggingRegressor]], [[IsolationForest]], RandomForest,
ExtraTrees, or any model which defines an attribute
TYPE:
|
score
|
A callable for point-wise comparison of true values with the predictions.
If
TYPE:
|
Source code in src/pydvl/valuation/methods/data_oob.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
fit
¶
fit(data: Dataset) -> Self
Compute the Data-OOB values.
This requires the bagging model passed upon construction to be fitted.
PARAMETER | DESCRIPTION |
---|---|
data
|
Data for which to compute values
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The fitted object. |
Source code in src/pydvl/valuation/methods/data_oob.py
DeltaShapleyValuation
¶
DeltaShapleyValuation(
utility: UtilityBase,
is_done: StoppingCriterion,
lower_bound: int,
upper_bound: int,
seed: Seed | None = None,
skip_converged: bool = False,
progress: bool = False,
)
Bases: SemivalueValuation
Computes \(\delta\)-Shapley values.
\(\delta\)-Shapley does not accept custom samplers. Instead, it uses a StratifiedSampler with a lower and upper bound on the size of the sets to sample from.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Object to compute utilities.
TYPE:
|
is_done
|
Stopping criterion to use.
TYPE:
|
lower_bound
|
The lower bound of the size of the subsets to sample from.
TYPE:
|
upper_bound
|
The upper bound of the size of the subsets to sample from.
TYPE:
|
seed
|
The seed for the random number generator used by the sampler.
TYPE:
|
progress
|
Whether to show a progress bar. If a dictionary, it is passed to
TYPE:
|
skip_converged
|
Whether to skip converged indices, as determined by the
stopping criterion's
TYPE:
|
Source code in src/pydvl/valuation/methods/delta_shapley.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
GroupTestingShapleyValuation
¶
GroupTestingShapleyValuation(
utility: UtilityBase,
n_samples: int,
epsilon: float,
solver_options: dict | None = None,
progress: bool = True,
seed: Seed | None = None,
batch_size: int = 1,
)
Bases: Valuation
Class to calculate the group-testing approximation to shapley values.
See Data valuation for an overview.
Warning
This method is very inefficient. Potential improvements to the implementation notwithstanding, convergence seems to be very slow (in terms of evaluations of the utility required). We recommend other Monte Carlo methods instead.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Utility object with model, data and scoring function.
TYPE:
|
n_samples
|
The number of samples to use. A sample size with theoretical guarantees can be computed using compute_n_samples().
TYPE:
|
epsilon
|
The error tolerance.
TYPE:
|
solver_options
|
Optional dictionary containing a CVXPY solver and options to configure it. For valid values to the "solver" key see this tutorial. For additional options cvxpy's documentation.
TYPE:
|
progress
|
Whether to show a progress bar during the construction of the group-testing problem.
TYPE:
|
seed
|
Seed for the random number generator.
TYPE:
|
batch_size
|
The number of samples to draw in each batch. Can be used to reduce parallelization overhead for fast utilities. Defaults to 1.
TYPE:
|
Source code in src/pydvl/valuation/methods/gt_shapley.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
fit
¶
fit(data: Dataset) -> Self
Calculate the group-testing valuation on a dataset.
This method has to be called before calling values()
.
Calculating the least core valuation is a computationally expensive task that
can be parallelized. To do so, call the fit()
method inside a
joblib.parallel_config
context manager as follows:
Source code in src/pydvl/valuation/methods/gt_shapley.py
Valuation
¶
Bases: ABC
Source code in src/pydvl/valuation/base.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
Dataset
¶
Dataset(
x: NDArray,
y: NDArray,
feature_names: Sequence[str] | NDArray[str_] | None = None,
target_names: Sequence[str] | NDArray[str_] | None = None,
data_names: Sequence[str] | NDArray[str_] | None = None,
description: str | None = None,
multi_output: bool = False,
)
A convenience class to handle datasets.
It holds a dataset, together with info on feature names, target names, and data names. It is used to pass data around to valuation methods.
The underlying data arrays can be accessed via
Dataset.data(), which returns the tuple
(X, y)
as a read-only RawData object. The data
can be accessed by indexing the object directly, e.g. dataset[0]
will return the
data point corresponding to index 0 in dataset
. For this base class, this is the
same as dataset.data([0])
, which is the first point in the data array, but derived
classes can behave differently.
PARAMETER | DESCRIPTION |
---|---|
x
|
training data
TYPE:
|
y
|
labels for training data
TYPE:
|
feature_names
|
names of the features of x data |
target_names
|
names of the features of y data |
data_names
|
names assigned to data points. For example, if the dataset is a time series, each entry can be a timestamp which can be referenced directly instead of using a row number. |
description
|
A textual description of the dataset.
TYPE:
|
multi_output
|
set to
TYPE:
|
Changed in version 0.10.0
No longer holds split data, but only x, y.
Changed in version 0.10.0
Slicing now return a new Dataset
object, not raw data.
Source code in src/pydvl/valuation/dataset.py
indices
property
¶
Index of positions in data.x_train.
Contiguous integers from 0 to len(Dataset).
names
property
¶
Names of each individual datapoint.
Used for reporting Shapley values.
feature
¶
Returns a slice for the feature with the given name.
Source code in src/pydvl/valuation/dataset.py
data
¶
Given a set of indices, returns the training data that refer to those indices, as a read-only tuple-like structure.
This is used mainly by subclasses of UtilityBase to retrieve subsets of the data from indices.
PARAMETER | DESCRIPTION |
---|---|
indices
|
Optional indices that will be used to select points from
the training data. If
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
RawData
|
If |
Source code in src/pydvl/valuation/dataset.py
data_indices
¶
Returns a subset of indices.
This is equivalent to using Dataset.indices[logical_indices]
but allows
subclasses to define special behaviour, e.g. when indices in Dataset
do not
match the indices in the data.
For Dataset
, this is a simple pass-through.
PARAMETER | DESCRIPTION |
---|---|
indices
|
A set of indices held by this object |
RETURNS | DESCRIPTION |
---|---|
NDArray[int_]
|
The indices of the data points in the data array. |
Source code in src/pydvl/valuation/dataset.py
logical_indices
¶
Returns the indices in this Dataset
for the given indices in the data array.
This is equivalent to using Dataset.indices[data_indices]
but allows
subclasses to define special behaviour, e.g. when indices in Dataset
do not
match the indices in the data.
PARAMETER | DESCRIPTION |
---|---|
indices
|
A set of indices in the data array. |
RETURNS | DESCRIPTION |
---|---|
NDArray[int_]
|
The abstract indices for the given data indices. |
Source code in src/pydvl/valuation/dataset.py
from_sklearn
classmethod
¶
from_sklearn(
data: Bunch,
train_size: int | float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
**kwargs,
) -> tuple[Dataset, Dataset]
Constructs two Dataset objects from a
sklearn.utils.Bunch, as returned by the load_*
functions in scikit-learn toy datasets.
Example
PARAMETER | DESCRIPTION |
---|---|
data
|
scikit-learn Bunch object. The following attributes are supported:
TYPE:
|
train_size
|
size of the training dataset. Used in |
the value is automatically set to the complement of the test size.
random_state: seed for train / test split
stratify_by_target: If True
, data is split in a stratified
fashion, using the target variable as labels. Read more in
scikit-learn's user guide.
kwargs: Additional keyword arguments to pass to the
Dataset constructor. Use this to pass e.g. is_multi_output
.
RETURNS | DESCRIPTION |
---|---|
tuple[Dataset, Dataset]
|
Object with the sklearn dataset |
Changed in version 0.6.0
Added kwargs to pass to the Dataset constructor.
Changed in version 0.10.0
Returns a tuple of two Dataset objects.
Source code in src/pydvl/valuation/dataset.py
from_arrays
classmethod
¶
from_arrays(
X: NDArray,
y: NDArray,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
**kwargs: Any,
) -> tuple[Dataset, Dataset]
Constructs a Dataset object from X and y numpy arrays as
returned by the make_*
functions in sklearn generated datasets.
Example
PARAMETER | DESCRIPTION |
---|---|
X
|
numpy array of shape (n_samples, n_features)
TYPE:
|
y
|
numpy array of shape (n_samples,)
TYPE:
|
train_size
|
size of the training dataset. Used in
TYPE:
|
random_state
|
seed for train / test split
TYPE:
|
stratify_by_target
|
If
TYPE:
|
kwargs
|
Additional keyword arguments to pass to the
Dataset constructor. Use this to pass
e.g.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tuple[Dataset, Dataset]
|
Object with the passed X and y arrays split across training and test sets. |
New in version 0.4.0
Changed in version 0.6.0
Added kwargs to pass to the Dataset constructor.
Changed in version 0.10.0
Returns a tuple of two Dataset objects.
Source code in src/pydvl/valuation/dataset.py
ValuationResult
¶
ValuationResult(
*,
values: Sequence[float64] | NDArray[float64],
variances: Sequence[float64] | NDArray[float64] | None = None,
counts: Sequence[int_] | NDArray[int_] | None = None,
indices: Sequence[IndexT] | NDArray[IndexT] | None = None,
data_names: Sequence[NameT] | NDArray[NameT] | None = None,
algorithm: str = "",
status: Status = Pending,
sort: bool | None = None,
**extra_values: Any,
)
Bases: Sequence
, Iterable[ValueItem]
Objects of this class hold the results of valuation algorithms.
These include indices in the original Dataset,
any data names (e.g. group names in GroupedDataset),
the values themselves, and variance of the computation in the case of Monte
Carlo methods. ValuationResults
can be iterated over like any Sequence
:
iter(valuation_result)
returns a generator of
ValueItem in the order in which the object
is sorted.
Indexing¶
Indexing can be position-based, when accessing any of the attributes values, variances, counts and indices, as well as when iterating over the object, or using the item access operator, both getter and setter. The "position" is either the original sequence in which the data was passed to the constructor, or the sequence in which the object is sorted, see below. One can retrieve the position for a given data index using the method positions().
Some methods use data indices instead. This is the case for get() and update().
Sorting¶
Results can be sorted in-place with
sort(), or alternatively using
python's standard sorted()
and reversed()
Note that sorting values affects how
iterators and the object itself as Sequence
behave: values[0]
returns a
ValueItem with the highest or lowest ranking
point if this object is sorted by descending or ascending value, respectively.the methods If
unsorted, values[0]
returns the ValueItem
at position 0, which has data index
indices[0]
in the Dataset.
The same applies to direct indexing of the ValuationResult
: the index
is positional, according to the sorting. It does not refer to the "data
index". To sort according to data index, use
sort() with key="index"
.
In order to access ValueItem objects by their data index, use get(), or use positions() to convert data indices to positions.
Converting back and forth from data indices and positions
data_indices = result.indices[result.positions(data_indices)]
is a noop.
Operating on results¶
Results can be added to each other with the +
operator. Means and
variances are correctly updated, using the counts
attribute.
Results can also be updated with new values using update(). Means and variances are updated accordingly using the Welford algorithm.
Empty objects behave in a special way, see empty().
PARAMETER | DESCRIPTION |
---|---|
values
|
An array of values. If omitted, defaults to an empty array
or to an array of zeros if |
indices
|
An optional array of indices in the original dataset. If
omitted, defaults to
TYPE:
|
variances
|
An optional array of variances of the marginals from which the values are computed.
TYPE:
|
counts
|
An optional array with the number of updates for each value. Defaults to an array of ones. |
data_names
|
Names for the data points. Defaults to index numbers if not set. |
algorithm
|
The method used.
TYPE:
|
status
|
The end status of the algorithm.
TYPE:
|
sort
|
Whether to sort the indices. Defaults to
TYPE:
|
extra_values
|
Additional values that can be passed as keyword arguments. This can contain, for example, the least core value.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If input arrays have mismatching lengths. |
Changed in 0.10.0
Changed the behaviour of the sort
argument.
Source code in src/pydvl/valuation/result.py
variances
property
¶
Variances of the marginals from which values were computed, possibly sorted.
Note that this is not the variance of the value estimate, but the sample variance of the marginals used to compute it.
indices
property
¶
indices: NDArray[IndexT]
The indices for the values, possibly sorted.
If the object is unsorted, then these are the same as declared at
construction or np.arange(len(values))
if none were passed.
names
property
¶
names: NDArray[NameT]
The names for the values, possibly sorted.
If the object is unsorted, then these are the same as declared at
construction or np.arange(len(values))
if none were passed.
sort
¶
sort(
reverse: bool = False,
key: Literal["value", "variance", "index", "name"] = "value",
) -> None
Sorts the indices in place by key
.
Once sorted, iteration over the results, and indexing of all the properties ValuationResult.values, ValuationResult.variances, ValuationResult.stderr, ValuationResult.counts, ValuationResult.indices and ValuationResult.names will follow the same order.
PARAMETER | DESCRIPTION |
---|---|
reverse
|
Whether to sort in descending order by value.
TYPE:
|
key
|
The key to sort by. Defaults to ValueItem.value.
TYPE:
|
Source code in src/pydvl/valuation/result.py
positions
¶
positions(data_indices: IndexSetT | list[IndexT]) -> IndexSetT
Return the location (indices) within the ValuationResult
for the given
data indices.
Sorting is taken into account. This operation is the inverse of indexing the indices property:
Source code in src/pydvl/valuation/result.py
copy
¶
copy() -> ValuationResult
Returns a copy of the object.
Source code in src/pydvl/valuation/result.py
__getattr__
¶
Allows access to extra values as if they were properties of the instance.
Source code in src/pydvl/valuation/result.py
__iter__
¶
Iterate over the results returning ValueItem objects. To sort in place before iteration, use sort().
Source code in src/pydvl/valuation/result.py
__add__
¶
__add__(other: ValuationResult) -> ValuationResult
Adds two ValuationResults.
The values must have been computed with the same algorithm. An exception to this is if one argument has empty values, in which case the other argument is returned.
Warning
Abusing this will introduce numerical errors.
Means and standard errors are correctly handled. Statuses are added with
bit-wise &
, see Status.
data_names
are taken from the left summand, or if unavailable from
the right one. The algorithm
string is carried over if both terms
have the same one or concatenated.
It is possible to add ValuationResults of different lengths, and with different or overlapping indices. The result will have the union of indices, and the values.
Warning
FIXME: Arbitrary extra_values
aren't handled.
Source code in src/pydvl/valuation/result.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
update
¶
update(data_idx: int | IndexT, new_value: float) -> ValuationResult
Updates the result in place with a new value, using running mean and variance.
The variance computation uses Bessel's correction for sample estimates of the variance.
PARAMETER | DESCRIPTION |
---|---|
data_idx
|
Data index of the value to update.
TYPE:
|
new_value
|
New value to add to the result.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ValuationResult
|
A reference to the same, modified result. |
RAISES | DESCRIPTION |
---|---|
IndexError
|
If the index is not found. |
Source code in src/pydvl/valuation/result.py
scale
¶
Scales the values and variances of the result by a coefficient.
PARAMETER | DESCRIPTION |
---|---|
factor
|
Factor to scale by.
TYPE:
|
data_indices
|
Data indices to scale. If
TYPE:
|
Source code in src/pydvl/valuation/result.py
get
¶
Retrieves a ValueItem by data index, as opposed to sort index, like the indexing operator.
PARAMETER | DESCRIPTION |
---|---|
data_idx
|
Data index of the value to retrieve.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
IndexError
|
If the index is not found. |
Source code in src/pydvl/valuation/result.py
to_dataframe
¶
Returns values as a dataframe.
PARAMETER | DESCRIPTION |
---|---|
column
|
Name for the column holding the data value. Defaults to the name of the algorithm used.
TYPE:
|
use_names
|
Whether to use data names instead of indices for the DataFrame's index.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
A dataframe with three columns: |
Source code in src/pydvl/valuation/result.py
from_random
classmethod
¶
from_random(
size: int,
total: float | None = None,
seed: Seed | None = None,
**kwargs: dict[str, Any],
) -> "ValuationResult"
Creates a ValuationResult object and fills it with an array of random values from a uniform distribution in [-1,1]. The values can be made to sum up to a given total number (doing so will change their range).
PARAMETER | DESCRIPTION |
---|---|
size
|
Number of values to generate
TYPE:
|
total
|
If set, the values are normalized to sum to this number ("efficiency" property of Shapley values).
TYPE:
|
seed
|
Random seed to use
TYPE:
|
kwargs
|
Additional options to pass to the constructor of ValuationResult. Use to override status, names, etc. |
RETURNS | DESCRIPTION |
---|---|
'ValuationResult'
|
A valuation result with its status set to |
'ValuationResult'
|
Status.Converged by default. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
Changed in version 0.6.0
Added parameter total
. Check for zero size
Source code in src/pydvl/valuation/result.py
empty
classmethod
¶
empty(
algorithm: str = "",
indices: IndexSetT | None = None,
data_names: Sequence[NameT] | NDArray[NameT] | None = None,
n_samples: int = 0,
) -> ValuationResult
Creates an empty ValuationResult object.
Empty results are characterised by having an empty array of values. When another result is added to an empty one, the empty one is discarded.
PARAMETER | DESCRIPTION |
---|---|
algorithm
|
Name of the algorithm used to compute the values
TYPE:
|
indices
|
Optional sequence or array of indices.
TYPE:
|
data_names
|
Optional sequences or array of names for the data points. Defaults to index numbers if not set. |
n_samples
|
Number of valuation result entries.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ValuationResult
|
Object with the results. |
Source code in src/pydvl/valuation/result.py
zeros
classmethod
¶
zeros(
algorithm: str = "",
indices: IndexSetT | None = None,
data_names: Sequence[NameT] | NDArray[NameT] | None = None,
n_samples: int = 0,
) -> ValuationResult
Creates an empty ValuationResult object.
Empty results are characterised by having an empty array of values. When another result is added to an empty one, the empty one is ignored.
PARAMETER | DESCRIPTION |
---|---|
algorithm
|
Name of the algorithm used to compute the values
TYPE:
|
indices
|
Data indices to use. A copy will be made. If not given,
the indices will be set to the range
TYPE:
|
data_names
|
Data names to use. A copy will be made. If not given, the names will be set to the string representation of the indices. |
n_samples
|
Number of data points whose values are computed. If
not given, the length of
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ValuationResult
|
Object with the results. |
Source code in src/pydvl/valuation/result.py
Status
¶
Bases: Enum
Status of a computation.
Statuses can be combined using bitwise or (|
) and bitwise and (&
) to
get the status of a combined computation. For example, if we have two
computations, one that has converged and one that has failed, then the
combined status is Status.Converged | Status.Failed == Status.Converged
,
but Status.Converged & Status.Failed == Status.Failed
.
OR¶
The result of bitwise or-ing two valuation statuses with |
is given
by the following table:
P | C | F | |
---|---|---|---|
P | P | C | P |
C | C | C | C |
F | P | C | F |
where P = Pending, C = Converged, F = Failed.
AND¶
The result of bitwise and-ing two valuation statuses with &
is given
by the following table:
P | C | F | |
---|---|---|---|
P | P | P | F |
C | P | C | F |
F | F | F | F |
where P = Pending, C = Converged, F = Failed.
NOT¶
The result of bitwise negation of a Status with ~
is Failed
if
the status is Converged
, or Converged
otherwise:
Boolean casting¶
A Status evaluates to True
iff it's Converged
or Failed
:
Warning
These truth values are inconsistent with the usual boolean
operations. In particular the XOR of two instances of Status
is not
the same as the XOR of their boolean values.
GroupedDataset
¶
GroupedDataset(
x: NDArray,
y: NDArray,
data_groups: Sequence[int] | NDArray[int_],
feature_names: Sequence[str] | NDArray[str_] | None = None,
target_names: Sequence[str] | NDArray[str_] | None = None,
data_names: Sequence[str] | NDArray[str_] | None = None,
group_names: Sequence[str] | NDArray[str_] | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: Dataset
Used for calculating values of subsets of the data considered as logical units. For instance, one can group by value of a categorical feature, by bin into which a continuous feature falls, or by label.
PARAMETER | DESCRIPTION |
---|---|
x
|
training data
TYPE:
|
y
|
labels of training data
TYPE:
|
data_groups
|
Sequence of the same length as |
feature_names
|
names of the covariates' features. |
target_names
|
names of the labels or targets y |
data_names
|
names of the data points. For example, if the dataset is a time series, each entry can be a timestamp. |
group_names
|
names of the groups. If not provided, the numerical group ids
from |
description
|
A textual description of the dataset
TYPE:
|
kwargs
|
Additional keyword arguments to pass to the Dataset constructor.
TYPE:
|
Changed in version 0.6.0
Added group_names
and forwarding of kwargs
Changed in version 0.10.0
No longer holds split data, but only x, y and group information. Added methods to retrieve indices for groups and vice versa.
Source code in src/pydvl/valuation/dataset.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 |
|
feature
¶
Returns a slice for the feature with the given name.
Source code in src/pydvl/valuation/dataset.py
data
¶
Returns the data and labels of all samples in the given groups.
PARAMETER | DESCRIPTION |
---|---|
indices
|
group indices whose elements to return. If
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
RawData
|
Tuple of training data |
Source code in src/pydvl/valuation/dataset.py
data_indices
¶
data_indices(
indices: int | slice | Sequence[int] | NDArray[int_] | None = None,
) -> NDArray[int_]
Returns the indices of the samples in the given groups.
PARAMETER | DESCRIPTION |
---|---|
indices
|
group indices whose elements to return. If
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
NDArray[int_]
|
Indices of the samples in the given groups. |
Source code in src/pydvl/valuation/dataset.py
logical_indices
¶
Returns the group indices for the given data indices.
PARAMETER | DESCRIPTION |
---|---|
indices
|
indices of the data points in the data array. If |
RETURNS | DESCRIPTION |
---|---|
NDArray[int_]
|
Group indices for the given data indices. |
Source code in src/pydvl/valuation/dataset.py
from_sklearn
classmethod
¶
from_sklearn(
data: Bunch,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
**kwargs,
) -> tuple[GroupedDataset, GroupedDataset]
from_sklearn(
data: Bunch,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
data_groups: Sequence[int] | None = None,
**kwargs,
) -> tuple[GroupedDataset, GroupedDataset]
from_sklearn(
data: Bunch,
train_size: int | float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
data_groups: Sequence[int] | None = None,
**kwargs: dict[str, Any],
) -> tuple[GroupedDataset, GroupedDataset]
Constructs a GroupedDataset object, and an
ungrouped Dataset object from a
sklearn.utils.Bunch as returned by the load_*
functions in
scikit-learn toy datasets and groups
it.
Example
PARAMETER | DESCRIPTION |
---|---|
data
|
scikit-learn Bunch object. The following attributes are supported:
-
TYPE:
|
train_size
|
size of the training dataset. Used in |
random_state
|
seed for train / test split.
TYPE:
|
stratify_by_target
|
If
TYPE:
|
data_groups
|
an array holding the group index or name for each data point. The length of this array must be equal to the number of data points in the dataset. |
kwargs
|
Additional keyword arguments to pass to the Dataset constructor. |
RETURNS | DESCRIPTION |
---|---|
tuple[GroupedDataset, GroupedDataset]
|
Datasets with the selected sklearn data |
Changed in version 0.10.0
Returns a tuple of two GroupedDataset objects.
Source code in src/pydvl/valuation/dataset.py
from_arrays
classmethod
¶
from_arrays(
X: NDArray,
y: NDArray,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
**kwargs,
) -> tuple[GroupedDataset, GroupedDataset]
from_arrays(
X: NDArray,
y: NDArray,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
data_groups: Sequence[int] | None = None,
**kwargs,
) -> tuple[GroupedDataset, GroupedDataset]
from_arrays(
X: NDArray,
y: NDArray,
train_size: float = 0.8,
random_state: int | None = None,
stratify_by_target: bool = False,
data_groups: Sequence[int] | None = None,
**kwargs: Any,
) -> tuple[GroupedDataset, GroupedDataset]
Constructs a GroupedDataset object,
and an ungrouped Dataset object from X and y
numpy arrays as returned by the make_*
functions in
scikit-learn generated datasets.
Example
>>> from sklearn.datasets import make_classification
>>> from pydvl.valuation.dataset import GroupedDataset
>>> X, y = make_classification(
... n_samples=100,
... n_features=4,
... n_informative=2,
... n_redundant=0,
... random_state=0,
... shuffle=False
... )
>>> data_groups = X[:, 0] // 0.5
>>> train, test = GroupedDataset.from_arrays(X, y, data_groups=data_groups)
PARAMETER | DESCRIPTION |
---|---|
X
|
array of shape (n_samples, n_features)
TYPE:
|
y
|
array of shape (n_samples,)
TYPE:
|
train_size
|
size of the training dataset. Used in
TYPE:
|
random_state
|
seed for train / test split.
TYPE:
|
stratify_by_target
|
If
TYPE:
|
data_groups
|
an array holding the group index or name for each data point. The length of this array must be equal to the number of data points in the dataset. |
kwargs
|
Additional keyword arguments that will be passed to the GroupedDataset constructor.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tuple[GroupedDataset, GroupedDataset]
|
Dataset with the passed X and y arrays split across training and test sets. |
New in version 0.4.0
Changed in version 0.6.0
Added kwargs to pass to the GroupedDataset constructor.
Changed in version 0.10.0
Returns a tuple of two GroupedDataset objects.
Source code in src/pydvl/valuation/dataset.py
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
from_dataset
classmethod
¶
from_dataset(
data: Dataset,
data_groups: Sequence[int] | NDArray[int_],
group_names: Sequence[str] | NDArray[str_] | None = None,
**kwargs: Any,
) -> GroupedDataset
Creates a GroupedDataset object from a Dataset object and a mapping of data groups.
Example
PARAMETER | DESCRIPTION |
---|---|
data
|
The original data.
TYPE:
|
data_groups
|
An array holding the group index or name for each data point. The length of this array must be equal to the number of data points in the dataset. |
group_names
|
Names of the groups. If not provided, the numerical group ids
from |
kwargs
|
Additional arguments to be passed to the GroupedDataset constructor.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
GroupedDataset
|
A GroupedDataset with the initial
Dataset grouped by |
Source code in src/pydvl/valuation/dataset.py
KNNShapleyValuation
¶
KNNShapleyValuation(
model: KNeighborsClassifier,
test_data: Dataset,
progress: bool = True,
clone_before_fit: bool = True,
)
Bases: Valuation
Computes exact Shapley values for a KNN classifier.
This implements the method described in (Jia, R. et al., 2019)1. It exploits the local structure of K-Nearest Neighbours to reduce the number of calls to the utility function to a constant number per index, thus reducing computation time to \(O(n)\).
PARAMETER | DESCRIPTION |
---|---|
model
|
KNeighborsClassifier model to use for valuation
TYPE:
|
test_data
|
Dataset containing test data for valuation
TYPE:
|
progress
|
Whether to display a progress bar.
TYPE:
|
clone_before_fit
|
Whether to clone the model before fitting.
TYPE:
|
Source code in src/pydvl/valuation/methods/knn_shapley.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
fit
¶
fit(data: Dataset) -> Self
Calculate exact shapley values for a KNN model on a dataset.
This fit method bypasses direct evaluations of the utility function and calculates the Shapley values directly.
In contrast to other data valuation models, the runtime increases linearly with the size of the dataset.
Calculating the KNN valuation is a computationally expensive task that
can be parallelized. To do so, call the fit()
method inside a
joblib.parallel_config
context manager as follows:
Source code in src/pydvl/valuation/methods/knn_shapley.py
LeastCoreValuation
¶
LeastCoreValuation(
utility: UtilityBase,
sampler: PowersetSampler,
n_samples: int | None = None,
non_negative_subsidy: bool = False,
solver_options: dict | None = None,
progress: bool = True,
)
Bases: Valuation
Umbrella class to calculate least-core values with multiple sampling methods.
See Data valuation for an overview.
Different samplers correspond to different least-core methods from the literature. For those, we provide convenience subclasses of LeastCoreValuation. See
Other samplers allow you to create your own method and might yield computational gains over a standard Monte Carlo method.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Utility object with model, data and scoring function.
TYPE:
|
sampler
|
The sampler to use for the valuation.
TYPE:
|
n_samples
|
The number of samples to use for the valuation. If None, it will be
set to the sample limit of the chosen sampler (for finite samplers) or
TYPE:
|
non_negative_subsidy
|
If True, the least core subsidy \(e\) is constrained to be non-negative.
TYPE:
|
solver_options
|
Optional dictionary containing a CVXPY solver and options to configure it. For valid values to the "solver" key see here. For additional options see here.
TYPE:
|
progress
|
Whether to show a progress bar during the construction of the least-core problem.
TYPE:
|
Source code in src/pydvl/valuation/methods/least_core.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
fit
¶
fit(data: Dataset) -> Self
Calculate the least core valuation on a dataset.
This method has to be called before calling values()
.
Calculating the least core valuation is a computationally expensive task that
can be parallelized. To do so, call the fit()
method inside a
joblib.parallel_config
context manager as follows:
Source code in src/pydvl/valuation/methods/least_core.py
ExactLeastCoreValuation
¶
ExactLeastCoreValuation(
utility: UtilityBase,
non_negative_subsidy: bool = False,
solver_options: dict | None = None,
progress: bool = True,
batch_size: int = 1,
)
Bases: LeastCoreValuation
Class to calculate exact least-core values.
Equivalent to constructing a
LeastCoreValuation with a
DeterministicUniformSampler
and n_samples=None
.
The definition of the exact least-core valuation is:
Where \(N = \{1, 2, \dots, n\}\) are the training set's indices.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Utility object with model, data and scoring function.
TYPE:
|
non_negative_subsidy
|
If True, the least core subsidy \(e\) is constrained to be non-negative.
TYPE:
|
solver_options
|
Optional dictionary containing a CVXPY solver and options to configure it. For valid values to the "solver" key see here. For additional options see here.
TYPE:
|
progress
|
Whether to show a progress bar during the construction of the least-core problem.
TYPE:
|
Source code in src/pydvl/valuation/methods/least_core.py
fit
¶
fit(data: Dataset) -> Self
Calculate the least core valuation on a dataset.
This method has to be called before calling values()
.
Calculating the least core valuation is a computationally expensive task that
can be parallelized. To do so, call the fit()
method inside a
joblib.parallel_config
context manager as follows:
Source code in src/pydvl/valuation/methods/least_core.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
MonteCarloLeastCoreValuation
¶
MonteCarloLeastCoreValuation(
utility: UtilityBase,
n_samples: int,
non_negative_subsidy: bool = False,
solver_options: dict | None = None,
progress: bool = True,
seed: Seed | None = None,
batch_size: int = 1,
)
Bases: LeastCoreValuation
Class to calculate exact least-core values.
Equivalent to calling LeastCoreValuation
with a UniformSampler
.
The definition of the Monte Carlo least-core valuation is:
Where:
- \(U(2^N)\) is the uniform distribution over the powerset of \(N\).
- \(m\) is the number of subsets that will be sampled and whose utility will be computed and used to compute the data values.
PARAMETER | DESCRIPTION |
---|---|
utility
|
Utility object with model, data and scoring function.
TYPE:
|
n_samples
|
The number of samples to use for the valuation. If None, it will be
set to
TYPE:
|
non_negative_subsidy
|
If True, the least core subsidy \(e\) is constrained to be non-negative.
TYPE:
|
solver_options
|
Optional dictionary containing a CVXPY solver and options to configure it. For valid values to the "solver" key see here. For additional options see here.
TYPE:
|
progress
|
Whether to show a progress bar during the construction of the least-core problem.
TYPE:
|
Source code in src/pydvl/valuation/methods/least_core.py
fit
¶
fit(data: Dataset) -> Self
Calculate the least core valuation on a dataset.
This method has to be called before calling values()
.
Calculating the least core valuation is a computationally expensive task that
can be parallelized. To do so, call the fit()
method inside a
joblib.parallel_config
context manager as follows:
Source code in src/pydvl/valuation/methods/least_core.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
LOOValuation
¶
LOOValuation(utility: UtilityBase, progress: bool = False)
Bases: SemivalueValuation
Computes LOO values for a dataset.
Source code in src/pydvl/valuation/methods/loo.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
log_coefficient
¶
The LOOSampler returns only complements of {idx}, so the weight is either 1/n (the probability of a set of size n-1) or 0 if k != n-1. We cancel this out here so that the final coefficient is either 1 if k == n-1 or 0 otherwise.
Source code in src/pydvl/valuation/methods/loo.py
SemivalueValuation
¶
SemivalueValuation(
utility: UtilityBase,
sampler: IndexSampler,
is_done: StoppingCriterion,
skip_converged: bool = False,
show_warnings: bool = True,
progress: dict[str, Any] | bool = False,
)
Bases: Valuation
Abstract class to define semi-values.
Implementations must only provide the log_coefficient()
method, corresponding
to the semi-value coefficient.
Note
For implementation consistency, we slightly depart from the common definition of semi-values, which includes a factor \(1/n\) in the sum over subsets. Instead, we subsume this factor into the coefficient \(w(k)\).
PARAMETER | DESCRIPTION |
---|---|
utility
|
Object to compute utilities.
TYPE:
|
sampler
|
Sampling scheme to use.
TYPE:
|
is_done
|
Stopping criterion to use.
TYPE:
|
skip_converged
|
Whether to skip converged indices, as determined by the
stopping criterion's
TYPE:
|
show_warnings
|
Whether to show warnings.
TYPE:
|
progress
|
Whether to show a progress bar. If a dictionary, it is passed to
|
Source code in src/pydvl/valuation/methods/semivalue.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
log_coefficient
abstractmethod
¶
The semi-value coefficient in log-space.
The semi-value coefficient is a function of the number of elements in the set, and the size of the subset for which the coefficient is being computed. Because both coefficients and sampler weights can be very large or very small, we perform all computations in log-space to avoid numerical issues.
PARAMETER | DESCRIPTION |
---|---|
n
|
Total number of elements in the set.
TYPE:
|
k
|
Size of the subset for which the coefficient is being computed
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
float
|
The natural logarithm of the semi-value coefficient. |
Source code in src/pydvl/valuation/methods/semivalue.py
ShapleyValuation
¶
ShapleyValuation(
utility: UtilityBase,
sampler: IndexSampler,
is_done: StoppingCriterion,
skip_converged: bool = False,
show_warnings: bool = True,
progress: dict[str, Any] | bool = False,
)
Bases: SemivalueValuation
Computes Shapley values.
Source code in src/pydvl/valuation/methods/semivalue.py
values
¶
values(sort: bool = False) -> ValuationResult
Returns a copy of the valuation result.
The valuation must have been run with fit()
before calling this method.
PARAMETER | DESCRIPTION |
---|---|
sort
|
Whether to sort the valuation result by value before returning it.
TYPE:
|
Returns: The result of the valuation.
Source code in src/pydvl/valuation/base.py
point_wise_accuracy
¶
Point-wise accuracy, or 0-1 score between two arrays.
Higher is better.
PARAMETER | DESCRIPTION |
---|---|
y_true
|
Array of true values (e.g. labels)
TYPE:
|
y_pred
|
Array of estimated values (e.g. model predictions)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
NDArray[T]
|
Array with point-wise 0-1 accuracy between labels and model predictions |
Source code in src/pydvl/valuation/methods/data_oob.py
neg_l2_distance
¶
Point-wise negative \(l_2\) distance between two arrays.
Higher is better.
PARAMETER | DESCRIPTION |
---|---|
y_true
|
Array of true values (e.g. labels)
TYPE:
|
y_pred
|
Array of estimated values (e.g. model predictions)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
NDArray[T]
|
Array with point-wise negative \(l_2\) distances between labels and model |
NDArray[T]
|
predictions |
Source code in src/pydvl/valuation/methods/data_oob.py
compute_n_samples
¶
Compute the minimal sample size with epsilon-delta guarantees.
Based on the formula in Theorem 4 of (Jia, R. et al., 2023)2 which gives a lower bound on the number of samples required to obtain an (ε/√n,δ/(N(N-1))-approximation to all pair-wise differences of Shapley values, wrt. \(\ell_2\) norm.
The updated version refines the lower bound of the original paper. Note that the bound is tighter than earlier versions but might still overestimate the number of samples required.
PARAMETER | DESCRIPTION |
---|---|
epsilon
|
The error tolerance.
TYPE:
|
delta
|
The confidence level.
TYPE:
|
n_obs
|
Number of data points.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
int
|
The sample size. |