numpyro-oop


Namenumpyro-oop JSON
Version 0.1.1 PyPI version JSON
download
home_pageNone
SummaryA convenient object-oriented wrapper for working with numpyro models.
upload_time2025-02-09 10:41:31
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseCopyright (c) 2024 Thomas Wallis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords numpyro probabilistic programming mcmc bayesian inference
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # An object-oriented interface to numpyro

[![CI](https://github.com/ag-perception-wallis-lab/numpyro-oop/actions/workflows/pytest.yml/badge.svg)](https://github.com/ag-perception-wallis-lab/numpyro-oop/actions/workflows/pytest.yml)
[![PyPI version](https://badge.fury.io/py/numpyro-oop.svg)](https://badge.fury.io/py/numpyro-oop)

This package provides a wrapper for working with [numpyro](https://num.pyro.ai/) models.
It aims to remain model-agnostic, but package up a lot of the model fitting code to reduce repetition.

It is intended to make life a bit easier for people who are already familiar with Numpyro and Bayesian modelling.
It is not intended to fulfil the same high-level wrapper role as packages such as [brms](https://paul-buerkner.github.io/brms/).
The user is still required to write the model from scratch.
This is an intentional choice: writing the model from scratch takes longer and is less convenient for standard models like GLMs, but has the advantage that one gains a deeper insight into what is happening under the hood, and also it is more transparent to implement custom models that don't fit a standard mould.

## Getting started

```
pip install numpyro-oop
```

The basic idea is that the user defines a new class that inherits from `BaseNumpyroModel`, 
and defines (minimally) the model to be fit by overwriting the `model` method:

```python
from numpyro_oop import BaseNumpyroModel

class DemoModel(BaseNumpyroModel):
    def model(self, data=None, ...):
        ...

m1 = DemoModel(data=df, seed=42)
```

Then all other sampling and prediction steps are handled by `numpyro-oop`, or related libraries (e.g. `arviz`):

```python
# sample from the model:
m1.sample()  
# generate model predictions for the dataset given at initialization:
preds = m1.predict(...)
# generate an Arviz InferenceData object stored in self.arviz_data:
m1.generate_arviz_data()  
```
A complete demo can be found in `/scripts/demo_1.ipynb`.


## Requirements of the `model` method

Consider the following model method:

```python
class DemoModel(BaseNumpyroModel):
    def model(self, data=None, sample_conditional=True, ...):
        ...

        if sample_conditional:
            obs = data["y"].values
        else:
            obs = None
        numpyro.sample("obs", dist.Normal(mu, sigma), obs=obs)

m1 = DemoModel(data=df, seed=42)
```

First, note that we can pass `data` as an optional `kwarg` that defaults to `None`.
If data is not passed to the `model` object directly then
`model` will automatically fall back to `self.data`, defined when the class instance is initialised.

Second, note the `sample_conditional` argument and subsequent pattern.
To use Numpyro's `Predictive` method, we need the ability to set any observed data 
that a sampling distribution is conditioned upon (typically the likelihood) to be `None`.
See the [Numpyro docs](https://num.pyro.ai/en/stable/utilities.html#numpyro.infer.util.Predictive) for examples.
Currently, `numpyro-oop` requires this to be implemented by the user in the model definition 
in some way; a suggested pattern is shown above.

After the model is sampled, we can then generate posterior predictive distributions by 
passing `sample_conditional=False` as a `model_kwarg`:

```python
m1.predict(model_kwargs={"sample_conditional": False})
```

## Using reparameterizations

One of the really neat features of Numpyro is the ability to define reparameterizations 
of variables that can be applied to the model object 
(see [docs](https://num.pyro.ai/en/stable/handlers.html#numpyro.handlers.reparam)).
To use these with `numpyro-oop`, the user must overwrite the `generate_reparam_config`
method of `BaseNumpyroModel` to return a reparameterization dictionary:

```python
def generate_reparam_config(self) -> dict:
    reparam_config = {
        "theta": LocScaleReparam(0),
    }
    return reparam_config
```

In this example, the node `theta` in the model will be reparameterized with a location/scale reparam
if `use_reparam=True` when the class instance is created. 
This is handy, because you can then test the effect of your reparameterization by simply setting
`use_reparam=False` and re-fitting the model.
See `examples/demo.ipynb` for a 
working example.

## Roadmap after initial release

- [ ] include doctest, improved examples
- [ ] demo and tests for multiple group variables
- [ ] export docs to some static page (readthedocs or similar); detail info on class methods and attributes
- [ ] Contributor guidelines
- [ ] Fix type hints via linter checks


### Development notes

Install the library with development dependencies via `pip install -e ".[dev]"`.



            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "numpyro-oop",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "numpyro, probabilistic programming, mcmc, bayesian inference",
    "author": null,
    "author_email": "Thomas Wallis <thomas.wallis@tu-darmstadt.de>",
    "download_url": "https://files.pythonhosted.org/packages/41/c0/b22410ebae67fc491f674232ebf53c749b89dcf96d35bf1966b26f825b49/numpyro_oop-0.1.1.tar.gz",
    "platform": null,
    "description": "# An object-oriented interface to numpyro\n\n[![CI](https://github.com/ag-perception-wallis-lab/numpyro-oop/actions/workflows/pytest.yml/badge.svg)](https://github.com/ag-perception-wallis-lab/numpyro-oop/actions/workflows/pytest.yml)\n[![PyPI version](https://badge.fury.io/py/numpyro-oop.svg)](https://badge.fury.io/py/numpyro-oop)\n\nThis package provides a wrapper for working with [numpyro](https://num.pyro.ai/) models.\nIt aims to remain model-agnostic, but package up a lot of the model fitting code to reduce repetition.\n\nIt is intended to make life a bit easier for people who are already familiar with Numpyro and Bayesian modelling.\nIt is not intended to fulfil the same high-level wrapper role as packages such as [brms](https://paul-buerkner.github.io/brms/).\nThe user is still required to write the model from scratch.\nThis is an intentional choice: writing the model from scratch takes longer and is less convenient for standard models like GLMs, but has the advantage that one gains a deeper insight into what is happening under the hood, and also it is more transparent to implement custom models that don't fit a standard mould.\n\n## Getting started\n\n```\npip install numpyro-oop\n```\n\nThe basic idea is that the user defines a new class that inherits from `BaseNumpyroModel`, \nand defines (minimally) the model to be fit by overwriting the `model` method:\n\n```python\nfrom numpyro_oop import BaseNumpyroModel\n\nclass DemoModel(BaseNumpyroModel):\n    def model(self, data=None, ...):\n        ...\n\nm1 = DemoModel(data=df, seed=42)\n```\n\nThen all other sampling and prediction steps are handled by `numpyro-oop`, or related libraries (e.g. `arviz`):\n\n```python\n# sample from the model:\nm1.sample()  \n# generate model predictions for the dataset given at initialization:\npreds = m1.predict(...)\n# generate an Arviz InferenceData object stored in self.arviz_data:\nm1.generate_arviz_data()  \n```\nA complete demo can be found in `/scripts/demo_1.ipynb`.\n\n\n## Requirements of the `model` method\n\nConsider the following model method:\n\n```python\nclass DemoModel(BaseNumpyroModel):\n    def model(self, data=None, sample_conditional=True, ...):\n        ...\n\n        if sample_conditional:\n            obs = data[\"y\"].values\n        else:\n            obs = None\n        numpyro.sample(\"obs\", dist.Normal(mu, sigma), obs=obs)\n\nm1 = DemoModel(data=df, seed=42)\n```\n\nFirst, note that we can pass `data` as an optional `kwarg` that defaults to `None`.\nIf data is not passed to the `model` object directly then\n`model` will automatically fall back to `self.data`, defined when the class instance is initialised.\n\nSecond, note the `sample_conditional` argument and subsequent pattern.\nTo use Numpyro's `Predictive` method, we need the ability to set any observed data \nthat a sampling distribution is conditioned upon (typically the likelihood) to be `None`.\nSee the [Numpyro docs](https://num.pyro.ai/en/stable/utilities.html#numpyro.infer.util.Predictive) for examples.\nCurrently, `numpyro-oop` requires this to be implemented by the user in the model definition \nin some way; a suggested pattern is shown above.\n\nAfter the model is sampled, we can then generate posterior predictive distributions by \npassing `sample_conditional=False` as a `model_kwarg`:\n\n```python\nm1.predict(model_kwargs={\"sample_conditional\": False})\n```\n\n## Using reparameterizations\n\nOne of the really neat features of Numpyro is the ability to define reparameterizations \nof variables that can be applied to the model object \n(see [docs](https://num.pyro.ai/en/stable/handlers.html#numpyro.handlers.reparam)).\nTo use these with `numpyro-oop`, the user must overwrite the `generate_reparam_config`\nmethod of `BaseNumpyroModel` to return a reparameterization dictionary:\n\n```python\ndef generate_reparam_config(self) -> dict:\n    reparam_config = {\n        \"theta\": LocScaleReparam(0),\n    }\n    return reparam_config\n```\n\nIn this example, the node `theta` in the model will be reparameterized with a location/scale reparam\nif `use_reparam=True` when the class instance is created. \nThis is handy, because you can then test the effect of your reparameterization by simply setting\n`use_reparam=False` and re-fitting the model.\nSee `examples/demo.ipynb` for a \nworking example.\n\n## Roadmap after initial release\n\n- [ ] include doctest, improved examples\n- [ ] demo and tests for multiple group variables\n- [ ] export docs to some static page (readthedocs or similar); detail info on class methods and attributes\n- [ ] Contributor guidelines\n- [ ] Fix type hints via linter checks\n\n\n### Development notes\n\nInstall the library with development dependencies via `pip install -e \".[dev]\"`.\n\n\n",
    "bugtrack_url": null,
    "license": "Copyright (c) 2024 Thomas Wallis\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "A convenient object-oriented wrapper for working with numpyro models.",
    "version": "0.1.1",
    "project_urls": null,
    "split_keywords": [
        "numpyro",
        " probabilistic programming",
        " mcmc",
        " bayesian inference"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0f2d78378b6101f9980f7f0c09d830d95e90c82b97897278eb50e81d73acc812",
                "md5": "156e131ce6a6b8fdd080a2534ddd5dca",
                "sha256": "c2c32bab021ef316a4ce1d1f3f99676cb7eb388eb1792bb6846e758b06165a02"
            },
            "downloads": -1,
            "filename": "numpyro_oop-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "156e131ce6a6b8fdd080a2534ddd5dca",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 9597,
            "upload_time": "2025-02-09T10:41:29",
            "upload_time_iso_8601": "2025-02-09T10:41:29.172566Z",
            "url": "https://files.pythonhosted.org/packages/0f/2d/78378b6101f9980f7f0c09d830d95e90c82b97897278eb50e81d73acc812/numpyro_oop-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "41c0b22410ebae67fc491f674232ebf53c749b89dcf96d35bf1966b26f825b49",
                "md5": "6eafb63788623cc2abc296c0e7381d6b",
                "sha256": "15eb8cdd036204fbb577b98370b6c8aefb98cc34c2c56972a477e077a684635b"
            },
            "downloads": -1,
            "filename": "numpyro_oop-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "6eafb63788623cc2abc296c0e7381d6b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 13286,
            "upload_time": "2025-02-09T10:41:31",
            "upload_time_iso_8601": "2025-02-09T10:41:31.060898Z",
            "url": "https://files.pythonhosted.org/packages/41/c0/b22410ebae67fc491f674232ebf53c749b89dcf96d35bf1966b26f825b49/numpyro_oop-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-02-09 10:41:31",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "numpyro-oop"
}
        
Elapsed time: 2.62416s