<jupyter_start><jupyter_text>Estimating local and global feature importance scores using DiCESummaries of counterfactual examples can be used to estimate importance of features. Intuitively, a feature that is changed more often to generate a proximal counterfactual is an important feature. We use this intuition to build a feature importance score. This score can be interpreted as a measure of the **necessity** of a feature to cause a particular model output. That is, if the feature's value changes, then it is likely that the model's output class will also change (or the model's output will significantly change in case of regression model).  Below we show how counterfactuals can be used to provide local feature importance scores for any input, and how those scores can be combined to yield a global importance score for each feature.<jupyter_code>from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import RandomForestClassifier

import dice_ml
from dice_ml import Dice
from dice_ml.utils import helpers  # helper functions
%load_ext autoreload
%autoreload 2<jupyter_output><empty_output><jupyter_text>Preliminaries: Loading the data and ML model<jupyter_code>dataset = helpers.load_adult_income_dataset().sample(5000)  # downsampling to reduce ML model fitting time
helpers.get_adult_data_info()
target = dataset["income"]

# Split data into train and test
datasetX = dataset.drop("income", axis=1)
x_train, x_test, y_train, y_test = train_test_split(datasetX,
                                                    target,
                                                    test_size=0.2,
                                                    random_state=0,
                                                    stratify=target)

numerical = ["age", "hours_per_week"]
categorical = x_train.columns.difference(numerical)

# We create the preprocessing pipelines for both numeric and categorical data.
numeric_transformer = Pipeline(steps=[
    ('scaler', StandardScaler())])

categorical_transformer = Pipeline(steps=[
    ('onehot', OneHotEncoder(handle_unknown='ignore'))])

transformations = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, numerical),
        ('cat', categorical_transformer, categorical)])

# Append classifier to preprocessing pipeline.
# Now we have a full prediction pipeline.
clf = Pipeline(steps=[('preprocessor', transformations),
                      ('classifier', RandomForestClassifier())])
model = clf.fit(x_train, y_train)
d = dice_ml.Data(dataframe=dataset, continuous_features=['age', 'hours_per_week'], outcome_name='income')
m = dice_ml.Model(model=model, backend="sklearn")<jupyter_output><empty_output><jupyter_text>Local feature importanceWe first generate counterfactuals for a given input point.<jupyter_code>exp = Dice(d, m, method="random")
query_instance = x_train[1:2]
e1 = exp.generate_counterfactuals(query_instance, total_CFs=10, desired_range=None,
                                  desired_class="opposite",
                                  permitted_range=None, features_to_vary="all")
e1.visualize_as_dataframe(show_only_changes=True)<jupyter_output><empty_output><jupyter_text>These can now be used to calculate the feature importance scores.<jupyter_code>imp = exp.local_feature_importance(query_instance, cf_examples_list=e1.cf_examples_list)
print(imp.local_importance)<jupyter_output><empty_output><jupyter_text>Feature importance can also be estimated directly, by leaving the `cf_examples_list` argument blank.<jupyter_code>imp = exp.local_feature_importance(query_instance, posthoc_sparsity_param=None)
print(imp.local_importance)<jupyter_output><empty_output><jupyter_text>Global importanceFor global importance, we need to generate counterfactuals for a representative sample of the dataset.<jupyter_code>cobj = exp.global_feature_importance(x_train[0:10], total_CFs=10, posthoc_sparsity_param=None)
print(cobj.summary_importance)<jupyter_output><empty_output><jupyter_text>Convert the counterfactual output to json<jupyter_code>json_str = cobj.to_json()
print(json_str)<jupyter_output><empty_output><jupyter_text>Convert the json output to a counterfactual object<jupyter_code>imp_r = imp.from_json(json_str)
print([o.visualize_as_dataframe(show_only_changes=True) for o in imp_r.cf_examples_list])
print(imp_r.local_importance)
print(imp_r.summary_importance)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07742926080280764, 'fraction_numerical': 0.004606273305549463, 'mean_word_length': 4.984251968503937, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '257004', 'license': 'MIT', 'n_tokens_mistral': 1323, 'n_tokens_neox': 1274, 'n_words': 355, 'path': 'docs/source/notebooks/DiCE_feature_importances.ipynb', 'repo_name': 'OKRATechnologies/DiCE', 'size': '4559'}