Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Verification of dtypes of columns of X_row* is same that self.X #300

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions explainerdashboard/explainer_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,7 @@ def _permutation_importance(
if pass_nparray:
scores.append(scorer(model, X.values, y.values))
else:
check_dtype_of(col_list, X, old_cols)
scores.append(scorer(model, X, y))

X[col_list] = old_cols
Expand Down Expand Up @@ -925,14 +926,18 @@ def get_pdp_df(
for grid_value in grid_values:
dtemp = X_sample.copy()
if isinstance(feature, list):
tmp_feats = feature.copy()
if grid_value in X_sample.columns:
assert set(X_sample[grid_value].unique()).issubset({0, 1}), (
f"{grid_values} When passing a list of features these have to be onehotencoded!"
f"But X_sample['{grid_value}'].unique()=={list(set(X_sample[grid_value].unique()))}"
)
dtemp.loc[:, feature] = [1 if col == grid_value else 0 for col in feature]
else:
tmp_feats = [feature]
dtemp[[feature]] = grid_value

check_dtype_of(tmp_feats, dtemp, X_sample)
if is_classifier:
if cast_to_float32:
dtemp = dtemp.values.astype("float32")
Expand Down Expand Up @@ -1791,3 +1796,25 @@ def get_xgboost_preds_df(xgbmodel, X_row, pos_label=1):
0, "pred_proba"
]
return xgboost_preds_df


def check_dtype_of(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you add some tests for this? How flexible is it? (e.g. will it break over float32 vs float64? int vs float? etc)

features: List[str],
df_target: pd.DataFrame,
df_origin: pd.DataFrame
):
"""
Check if the features in the df_target has the same dtype in df_origin,
if not, it fixes the dtype in df_target
:param features:
:param df_target:
:param df_origin:
"""
# Verify if the features has the same dtype as the X sample
if (
df_target is not None and
not df_target[features].dtypes.eq(df_origin[features].dtypes).all()
):
df_target[features] = df_target[features].astype(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in general not a fan of these functions that modify in place. Could you rewrite it such that it returns the transformed df instead? Then maybe call it adjust_dtypes_to_match_df(...) or something?

Calling something check_dtype_of when it actually modifies one of the arguments is confusing.

df_origin[features].dtypes
)
9 changes: 8 additions & 1 deletion explainerdashboard/explainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@


from .explainer_methods import *
from .explainer_methods import check_dtype_of
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can add check_dtype_of to the __all__ at the start in explainer_methods.py then it is covered by the import * (generally import * is frowned upon, but it's okay as long as you define a restrictive __all__)

from .explainer_plots import *


Expand Down Expand Up @@ -241,7 +242,9 @@ def __init__(
col for col in self.regular_cols if not is_numeric_dtype(self.X[col])
]
self.categorical_dict = {
col: sorted(self.X[col].unique().tolist()) for col in self.categorical_cols
col: sorted(
v for v in self.X[col].unique().tolist() if not pd.isna(v)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not an expert on lightgbm, but wouldn't there be usecases where na would be a category? Or is that handled differently? How about by catboost or other libraries?

) for col in self.categorical_cols
}
self.cat_cols = self.onehot_cols + self.categorical_cols
self.original_cols = self.X.columns
Expand Down Expand Up @@ -1675,6 +1678,7 @@ def get_contrib_summary_df(
Returns:
pd.DataFrame
"""
check_dtype_of(self.X.columns, X_row, self.X)
contrib_df = self.get_contrib_df(index, X_row, topx, cutoff, sort, pos_label)
return get_contrib_summary_df(
contrib_df,
Expand Down Expand Up @@ -1974,6 +1978,7 @@ def plot_contributions(

"""
assert orientation in ["vertical", "horizontal"]
check_dtype_of(self.X.columns, X_row, self.X)
contrib_df = self.get_contrib_df(
index=index,
X_row=X_row,
Expand Down Expand Up @@ -2308,6 +2313,7 @@ def plot_pdp(
plotly.Fig: fig

"""
check_dtype_of(self.X.columns, X_row, self.X)
pdp_df = self.pdp_df(
col,
index,
Expand Down Expand Up @@ -4207,6 +4213,7 @@ def prediction_result_df(self, index=None, X_row=None, round=3):
if index is not None:
X_row = self.get_X_row(index)
if X_row is not None:
check_dtype_of(self.X.columns, X_row, self.X)
if matching_cols(X_row.columns, self.merged_cols):
X_row = X_cats_to_X(X_row, self.onehot_dict, self.X.columns)
if self.shap == "skorch":
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ dash-bootstrap-components>=1
dash>=2.10.1
dtreeviz>=2.1
flask_simplelogin
flask==3.0.2
Flask-WTF>=1.1
graphviz>=0.18.2
joblib
Expand Down