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

Prevent none value in gradients when some of the inputs have not impact to the target #987

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion alibi/explainers/integrated_gradients.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,11 @@ def _gradients_input(model: Union[tf.keras.models.Model],

grads = tape.gradient(preds, x)

# If certain inputs don't impact the target, the gradient is None, but we need to return a tensor
if isinstance(x, list):
for idx, grad in enumerate(grads):
if grad is None:
grads[idx] = tf.convert_to_tensor(np.zeros(x[idx].shape), dtype=x[idx].dtype)
return grads


Expand Down Expand Up @@ -497,7 +502,11 @@ def wrapper(*args, **kwargs):
grads = tape.gradient(preds, layer.inp)
else:
grads = tape.gradient(preds, layer.result)

# If certain inputs don't impact the target, the gradient is None, but we need to return a tensor
if isinstance(x, list):
for idx, grad in enumerate(grads):
if grad is None:
grads[idx] = tf.convert_to_tensor(np.zeros(x[idx].shape), dtype=x[idx].dtype)
delattr(layer, 'inp')
delattr(layer, 'result')
layer.call = orig_call
Expand Down