stein-thinning


Namestein-thinning JSON
Version 0.2.0 PyPI version JSON
download
home_pageNone
SummaryOptimally compress sampling algorithm outputs
upload_time2024-11-17 14:03:35
maintainerNone
docs_urlNone
authorStein Thinning team
requires_python>=3.7
licenseCopyright 2024 Stein Thinning team 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 mcmc stein thinning
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Stein Thinning
This Python package implements an algorithm for optimally compressing
sampling algorithm outputs by minimising a kernel Stein discrepancy.
Please see the accompanying paper "Optimal Thinning of MCMC Output"
([arXiv](https://arxiv.org/pdf/2005.03952.pdf)) for details of the
algorithm.

# Installing the package

The latest stable version can be installed via pip:
```
pip install stein-thinning
```

To install the current development version, use this command:
```
pip install git+https://github.com/wilson-ye-chen/stein_thinning
```

# Getting Started
For example, correlated samples from a posterior distribution are
obtained using a MCMC algorithm and stored in the NumPy array `smpl`,
and the corresponding gradients of the log-posterior are stored in
another NumPy array `grad`. One can then perform Stein Thinning to
obtain a subset of 40 sample points by running the following code:
```python
from stein_thinning.thinning import thin
idx = thin(smpl, grad, 40)
```
The `thin` function returns a NumPy array containing the row indices
in `smpl` (and `grad`) of the selected points. Please refer to `demo.py`
as a starting example.

The default usage requires no additional user input and is based on
the identity (`id`) preconditioning matrix and standardised sample.
Alternatively, the user can choose to specify which heuristic to use
for computing the preconditioning matrix by setting the option string
to either `id`, `med`,  `sclmed`, or `smpcov`. Standardisation can be
disabled by setting `stnd=False`. For example, the default setting
corresponds to:
```python
idx = thin(smpl, grad, 40, stnd=True, pre='id')
```
The details for each of the heuristics are documented in Section 2.3 of
the accompanying paper.

# PyStan Example
As an illustration of how Stein Thinning can be used to post-process
output from [Stan](https://mc-stan.org/users/interfaces/pystan), consider
the following simple Stan script that produces correlated samples from a
bivariate Gaussian model:
```python
from pystan import StanModel
mc = """
parameters {vector[2] x;}
model {x ~ multi_normal([0, 0], [[1, 0.8], [0.8, 1]]);}
"""
sm = stan.build(mc, random_seed=12345)
fit = sm.sample(num_samples=1000)
```
The bivariate Gaussian model is used for illustration, but regardless of
the complexity of the model being sampled the output of Stan will always
be a `fit` object (StanFit instance). The sampled points and the
log-posterior gradients can be extracted from the returned `fit` object:
```python
import numpy as np
sample = fit['x'].T
gradient = np.apply_along_axis(lambda x: sm.grad_log_prob(x.tolist()), 1, sample)
idx = thin(sample, gradient, 40)
```
The selected points can then be plotted:
```python
plt.figure()
plt.scatter(sample[:, 0], sample[:, 1], color='lightgray')
plt.scatter(sample[idx, 0], sample[idx, 1], color='red')
plt.show()
```

![Stein Thinning Demo Results](https://raw.githubusercontent.com/wilson-ye-chen/stein_thinning/master/stein_thinning/demo/pystan.png)

The above example can be found in `stein_thinning/demo/pystan.py`.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "stein-thinning",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "mcmc, Stein, thinning",
    "author": "Stein Thinning team",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/1a/3d/8209c53f925a8c765891fa06c318b42f01f1995d1eee3e9f8a8198c7a1ea/stein_thinning-0.2.0.tar.gz",
    "platform": null,
    "description": "# Stein Thinning\nThis Python package implements an algorithm for optimally compressing\nsampling algorithm outputs by minimising a kernel Stein discrepancy.\nPlease see the accompanying paper \"Optimal Thinning of MCMC Output\"\n([arXiv](https://arxiv.org/pdf/2005.03952.pdf)) for details of the\nalgorithm.\n\n# Installing the package\n\nThe latest stable version can be installed via pip:\n```\npip install stein-thinning\n```\n\nTo install the current development version, use this command:\n```\npip install git+https://github.com/wilson-ye-chen/stein_thinning\n```\n\n# Getting Started\nFor example, correlated samples from a posterior distribution are\nobtained using a MCMC algorithm and stored in the NumPy array `smpl`,\nand the corresponding gradients of the log-posterior are stored in\nanother NumPy array `grad`. One can then perform Stein Thinning to\nobtain a subset of 40 sample points by running the following code:\n```python\nfrom stein_thinning.thinning import thin\nidx = thin(smpl, grad, 40)\n```\nThe `thin` function returns a NumPy array containing the row indices\nin `smpl` (and `grad`) of the selected points. Please refer to `demo.py`\nas a starting example.\n\nThe default usage requires no additional user input and is based on\nthe identity (`id`) preconditioning matrix and standardised sample.\nAlternatively, the user can choose to specify which heuristic to use\nfor computing the preconditioning matrix by setting the option string\nto either `id`, `med`,  `sclmed`, or `smpcov`. Standardisation can be\ndisabled by setting `stnd=False`. For example, the default setting\ncorresponds to:\n```python\nidx = thin(smpl, grad, 40, stnd=True, pre='id')\n```\nThe details for each of the heuristics are documented in Section 2.3 of\nthe accompanying paper.\n\n# PyStan Example\nAs an illustration of how Stein Thinning can be used to post-process\noutput from [Stan](https://mc-stan.org/users/interfaces/pystan), consider\nthe following simple Stan script that produces correlated samples from a\nbivariate Gaussian model:\n```python\nfrom pystan import StanModel\nmc = \"\"\"\nparameters {vector[2] x;}\nmodel {x ~ multi_normal([0, 0], [[1, 0.8], [0.8, 1]]);}\n\"\"\"\nsm = stan.build(mc, random_seed=12345)\nfit = sm.sample(num_samples=1000)\n```\nThe bivariate Gaussian model is used for illustration, but regardless of\nthe complexity of the model being sampled the output of Stan will always\nbe a `fit` object (StanFit instance). The sampled points and the\nlog-posterior gradients can be extracted from the returned `fit` object:\n```python\nimport numpy as np\nsample = fit['x'].T\ngradient = np.apply_along_axis(lambda x: sm.grad_log_prob(x.tolist()), 1, sample)\nidx = thin(sample, gradient, 40)\n```\nThe selected points can then be plotted:\n```python\nplt.figure()\nplt.scatter(sample[:, 0], sample[:, 1], color='lightgray')\nplt.scatter(sample[idx, 0], sample[idx, 1], color='red')\nplt.show()\n```\n\n![Stein Thinning Demo Results](https://raw.githubusercontent.com/wilson-ye-chen/stein_thinning/master/stein_thinning/demo/pystan.png)\n\nThe above example can be found in `stein_thinning/demo/pystan.py`.\n",
    "bugtrack_url": null,
    "license": "Copyright 2024 Stein Thinning team  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \u201cSoftware\u201d), 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 \u201cAS IS\u201d, 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.",
    "summary": "Optimally compress sampling algorithm outputs",
    "version": "0.2.0",
    "project_urls": {
        "Homepage": "https://github.com/wilson-ye-chen/stein_thinning"
    },
    "split_keywords": [
        "mcmc",
        " stein",
        " thinning"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a26c7e6704ac8d2b1c30d3165164276f11003cc7988e2c62dee70c4685a3a5cd",
                "md5": "8a225e516a7e4a410229025a394912c2",
                "sha256": "f72f8a5f6369ec72d1df36a5fe505c1bee9e103c704d05a2d912f12cbb76d5bc"
            },
            "downloads": -1,
            "filename": "stein_thinning-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8a225e516a7e4a410229025a394912c2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 27398,
            "upload_time": "2024-11-17T14:03:33",
            "upload_time_iso_8601": "2024-11-17T14:03:33.254921Z",
            "url": "https://files.pythonhosted.org/packages/a2/6c/7e6704ac8d2b1c30d3165164276f11003cc7988e2c62dee70c4685a3a5cd/stein_thinning-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1a3d8209c53f925a8c765891fa06c318b42f01f1995d1eee3e9f8a8198c7a1ea",
                "md5": "a4e88a4cbda44c34863adcd61ce0cb84",
                "sha256": "226880b9e561aef2383030cbba5466276f29b65af4ce0adb277f244d983ae543"
            },
            "downloads": -1,
            "filename": "stein_thinning-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "a4e88a4cbda44c34863adcd61ce0cb84",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 27870,
            "upload_time": "2024-11-17T14:03:35",
            "upload_time_iso_8601": "2024-11-17T14:03:35.663787Z",
            "url": "https://files.pythonhosted.org/packages/1a/3d/8209c53f925a8c765891fa06c318b42f01f1995d1eee3e9f8a8198c7a1ea/stein_thinning-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-17 14:03:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "wilson-ye-chen",
    "github_project": "stein_thinning",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "stein-thinning"
}
        
Elapsed time: 1.14327s