Skip to main content

models.permutation_importance()

Permutation feature importance: how much a score worsens when a

Usage

Source

models.permutation_importance(
    model,
    frame,
    y,
    build,
    score,
    features,
    splits=None,
    n_repeats=1,
    seed=0,
    n_jobs=None
)

feature’s column is shuffled, which breaks its link to the response and leaves every other column in place (CAS Monograph 16, section 9.2).

It needs only predictions, so it works for any model. A list of names shuffles them together with one permutation (a group, such as the columns of one encoding). Shuffles come from permutation, so Python and R give the same values on the same data.

Parameters

model: object

A fitted model with predict(design); with splits, a model with fit(design, y) (as for cross_validate), fitted on each split’s training rows and explained on its test rows.

frame: dict

Column name to a list or NumPy array of raw values, all one length: the rows to explain (the whole data with splits).

y: list of float
build: callable

build(frame) -> Design, the design from raw columns (with any offset and weights). Shuffling a raw column moves every design column built from it.

score: callable

score(y, predicted, design) -> float, a loss (lower is better), such as deviance_score("poisson"); a gain such as a pseudo-R2 goes in as its negative.

features: list or dict

Names of columns, lists of names shuffled together, or a dict from a label to names. Never the response, exposure or weights.

splits: list of (list of int, list of int) = None

(train, test) rows, as k_fold returns.

n_repeats: int = 1

Shuffles per split, averaged.

seed: int = 0

Repeat r of split i shuffles with permutation(n, seed, i * n_repeats + r).

n_jobs: int = None
Threads with splits; one per split by default.

Returns

PermutationImportance

Examples

>>> from prospicio.models import Design, Glm, deviance_score, permutation_importance
>>> x = [i / 10 for i in range(40)]
>>> frame = {"x": x, "noise": [((7 * i) % 11) / 11 for i in range(40)]}
>>> y = [1.0 + 2.0 * v + (0.3 if i % 3 else -0.6) for i, v in enumerate(x)]
>>> build = lambda f: Design([[1.0] * len(f["x"]), list(f["x"])], ["(Intercept)", "x"])
>>> fit = Glm("gaussian").fit(build(frame), y)
>>> imp = permutation_importance(fit, frame, y, build, deviance_score("gaussian"), ["x", "noise"])
>>> imp.importance[0] > 1.0, imp.importance[1]

(True, 0.0)