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

Use numpy.random.RandomGenerator #782

Open
cwmeijer opened this issue Jun 5, 2024 · 0 comments
Open

Use numpy.random.RandomGenerator #782

cwmeijer opened this issue Jun 5, 2024 · 0 comments

Comments

@cwmeijer
Copy link
Contributor

cwmeijer commented Jun 5, 2024

We could consider using a RandomGenerator object to pass around in our code. See this blog about the motivation. ChatGPT summary: Using a RandomGenerator object avoids the pitfalls of global state and enhances reproducibility, flexibility, and compatibility with modern NumPy features.

I tried this but it will be quite a lot of places where we'd have to change code. Could be worth it. Example:

    def explain(
        self,
        model_or_function: Union[str, callable],
        input_tabular: np.array,
        labels: Optional[Iterable[int]] = None,
        mask_type: Optional[Union[str, callable]] = 'most_frequent',
        batch_size: Optional[int] = 100,
        rng: Optional[np.random.Generator] = None,  # ADD THIS LINE -------------------
    ) -> np.array:
        """Run the RISE explainer.

        Args:
            model_or_function: The function that runs the model to be explained
                                                 or the path to a ONNX model on disk.
            input_tabular: Data to be explained.
            labels: Indices of classes to be explained.
            mask_type: Imputation strategy for masked features
            batch_size: Number of samples to process by the model per batch
            rng: random number generator  # ADD THIS LINE -------------------

        Returns:
            explanation: An Explanation object containing the LIME explanations for each class.
        """
        rng = np.random.default_rng(rng)  # ADD THIS LINE -------------------

        # run the explanation.
        runner = utils.get_function(model_or_function)

        masks = np.stack(
            list(
                generate_tabular_masks(input_tabular.shape, 
                                                      number_of_masks=self.n_masks, p_keep=self.p_keep, 
                                                      rng=rng)))  # PASS RNG ON ------------------
        self.masks = masks if self.keep_masks else None

        masked = mask_data_tabular(input_tabular,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant