Пример #1
0
 def _assert_attributions(
     self,
     model,
     layer,
     inputs,
     baselines,
     target,
     expected,
     expected_delta=None,
     n_samples=5,
     attribute_to_layer_input=False,
     add_args=None,
 ):
     lgs = LayerGradientShap(model, layer)
     attrs, delta = lgs.attribute(
         inputs,
         baselines=baselines,
         target=target,
         additional_forward_args=add_args,
         n_samples=n_samples,
         stdevs=0.0009,
         return_convergence_delta=True,
         attribute_to_layer_input=attribute_to_layer_input,
     )
     if isinstance(attrs, tuple):
         for attr, exp in zip(attrs, expected):
             assertTensorAlmostEqual(self, attr, exp, 0.005)
     else:
         assertTensorAlmostEqual(self, attrs, expected, 0.005)
     if expected_delta is None:
         _assert_attribution_delta(self, inputs, attrs, n_samples, delta, True)
     else:
         for delta_i, expected_delta_i in zip(delta, expected_delta):
             self.assertAlmostEqual(delta_i, expected_delta_i, delta=0.01)
Пример #2
0
    def test_basic_multilayer_wo_multiplying_by_inputs(self) -> None:
        model = BasicModel_MultiLayer(inplace=True)
        model.eval()

        inputs = torch.tensor([[1.0, -20.0, 10.0]])
        baselines = torch.zeros(3, 3)
        lgs = LayerGradientShap(model, model.linear2, multiply_by_inputs=False)
        attrs = lgs.attribute(inputs, baselines, target=0, stdevs=0.0,)
        assertTensorAlmostEqual(self, attrs, torch.tensor([[1.0, 0.0]]))
Пример #3
0
 def _assert_attributions(
     self,
     model: Module,
     layer: Module,
     inputs: TensorOrTupleOfTensorsGeneric,
     baselines: Union[TensorOrTupleOfTensorsGeneric, Callable],
     target: TargetType,
     expected: Union[
         Tensor,
         Tuple[Tensor, ...],
         List[float],
         List[List[float]],
         Tuple[List[float], ...],
         Tuple[List[List[float]], ...],
     ],
     expected_delta: Tensor = None,
     n_samples: int = 5,
     attribute_to_layer_input: bool = False,
     add_args: Any = None,
 ) -> None:
     lgs = LayerGradientShap(model, layer)
     attrs, delta = lgs.attribute(
         inputs,
         baselines,
         target=target,
         additional_forward_args=add_args,
         n_samples=n_samples,
         stdevs=0.0009,
         return_convergence_delta=True,
         attribute_to_layer_input=attribute_to_layer_input,
     )
     assertTensorTuplesAlmostEqual(self, attrs, expected, delta=0.005)
     if expected_delta is None:
         _assert_attribution_delta(self, inputs, attrs, n_samples, delta, True)
     else:
         for delta_i, expected_delta_i in zip(delta, expected_delta):
             assertTensorAlmostEqual(self, delta_i, expected_delta_i, delta=0.01)