autospice


Nameautospice JSON
Version 0.1.5 PyPI version JSON
download
home_pageNone
SummarySPICE: Sparse and Interpretable Cognitive Equations
upload_time2025-07-23 16:25:37
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseMIT License Copyright (c) 2025 Daniel Weinhardt 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 cognitive-science reinforcement-learning machine-learning rnn dynamical-systems sindy
VCS
bugtrack_url
requirements arviz jax matplotlib numpy numpyro pandas pymc pyro_ppl pysindy scikit-learn scipy seaborn theano torch tqdm optuna dill pytest
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Computational Discovery of Sparse and Interpretable Cognitive Equations (SPICE)

![SPICE Logo](https://github.com/whyhardt/SPICE/blob/main/figures/spice_logo.png?raw=true)

SPICE is a framework for automating scientific practice in cognitive science and is based on a two cornerstones:

1. A task-specific RNN is trained to predict human behavior and thus learn implicitly latent cognitive mechanisms.

2. Sparse Identification of nonlinear Dynamics (SINDy; an equation discovery algorithm) is used to obtain mathematically interpretable equations for the learned cognitive mechanisms.

📚 **Documentation**: [https://whyhardt.github.io/SPICE/](https://whyhardt.github.io/SPICE/)

The resulting model with the neural-network architecture but with equations instead of RNN modules is called SPICE model. An overview is given in Figure 1.

This README file gives an overview on how to install and run SPICE as a scikit-learn estimator. To learn how to use SPICE in more comprehensive scenarios, you can go to [tutorials](tutorials).

![Figure 1 - SPICE Overview](https://github.com/whyhardt/SPICE/blob/main/figures/spice_overview.jpg?raw=true "Figure 1: SPICE overview")

## Installation

You can install SPICE using pip:

```bash
pip install autospice
```

or, you can clone this repository and install it locally from the root folder:

```bash
pip install -e .
```

## Features

- Scikit-learn compatible estimator interface
- Customizable network architecture for identifying complex cognitive mechanisms
- Participant embeddings for identifying individual differences
- Precoded models for simple Rescorla-Wagner, forgetting mechanism, choise perseveration and parcitipant embeddings

## Quick Start

```python
from spice.estimator import SpiceEstimator
from spice.precoded import RescorlaWagnerRNN, RESCOLA_WAGNER_CONFIG
from spice.resources.bandits import BanditsDrift, AgentQ, create_dataset

# Simulate dataset from a two-armed bandit task with a Q agent
environment = BanditsDrift(sigma=0.2, n_actions=2)

agent = AgentQ(
    n_actions=2,
    alpha_reward=0.6,  # Learning rate for positive rewards 
    alpha_penalty=0.6,  # Learning rate for negative rewards
    forget_rate=0.3,
)

dataset, _, _ = create_dataset(
    agent=agent,
    environment=environment,
    n_trials=200,
    n_sessions=256,
)

# Create and fit SPICE model
spice_estimator = SpiceEstimator(
    rnn_class=RescorlaWagnerRNN,
    spice_config=RESCOLA_WAGNER_CONFIG,
    hidden_size=8,
    learning_rate=5e-3,
    epochs=16,
    n_steps_per_call=16,
    spice_participant_id=0,
    save_path_rnn='rnn_model.pkl',   # (Optional) File path (.pkl) to save RNN model after training
    save_path_spice='spice_model.pkl', # (Optional) File path (.pkl) to save SPICE model after training
    verbose=True,
)

spice_estimator.fit(dataset.xs, dataset.ys)

# Get learned SPICE features
features = spice_estimator.spice_agent.get_spice_features()
for id, feat in features.items():
    print(f"\nAgent {id}:")
    for model_name, (feat_names, coeffs) in feat.items():
        print(f"  {model_name}:")
        for name, coeff in zip(feat_names, coeffs):
            print(f"    {name}: {coeff}")

# Predict behavior
pred_rnn, pred_spice = spice_estimator.predict(dataset.xs)

print("\nPrediction shapes:")
print(f"RNN predictions: {pred_rnn.shape}")
print(f"SPICE predictions: {pred_spice.shape}")  
```

### Saving and loading models

In addition to specifying save paths when creating the SpiceEstimator, you can also save an existing estimator's models, or load from save files:

```python
# Save trained model to file
spice_estimator.save_spice(path_rnn='rnn_model.pkl', path_spice='spice_model.pkl')

# Load saved model
loaded_spice = SpiceEstimator.load_spice(path_rnn='rnn_model.pkl', path_spice='spice_model.pkl')

# Use loaded model for predictions
pred_rnn, pred_spice = loaded_spice.predict(dataset.xs)
```

## Requirements

See `requirements.txt` for a complete list of dependencies.

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Citation

If you use this package in your research, please cite:

```bibtex
@software{spice2025,
  title = {SPICE: Sparse and Interpretable Cognitive Equations},
  year = {2025},
  author = {Weinhardt, Daniel},
  url = {https://github.com/whyhardt/SPICE}
}
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "autospice",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": "Muhip Tezcan <itezcan@uni-osnabrueck.de>",
    "keywords": "cognitive-science, reinforcement-learning, machine-learning, rnn, dynamical-systems, sindy",
    "author": null,
    "author_email": "Daniel Weinhardt <daniel.weinhardt@uni-osnabrueck.de>",
    "download_url": "https://files.pythonhosted.org/packages/4f/42/4ee17a03c322bd1707fba359aa4ee28c114c4bab580f3bb04df3e94638ca/autospice-0.1.5.tar.gz",
    "platform": null,
    "description": "# Computational Discovery of Sparse and Interpretable Cognitive Equations (SPICE)\n\n![SPICE Logo](https://github.com/whyhardt/SPICE/blob/main/figures/spice_logo.png?raw=true)\n\nSPICE is a framework for automating scientific practice in cognitive science and is based on a two cornerstones:\n\n1. A task-specific RNN is trained to predict human behavior and thus learn implicitly latent cognitive mechanisms.\n\n2. Sparse Identification of nonlinear Dynamics (SINDy; an equation discovery algorithm) is used to obtain mathematically interpretable equations for the learned cognitive mechanisms.\n\n\ud83d\udcda **Documentation**: [https://whyhardt.github.io/SPICE/](https://whyhardt.github.io/SPICE/)\n\nThe resulting model with the neural-network architecture but with equations instead of RNN modules is called SPICE model. An overview is given in Figure 1.\n\nThis README file gives an overview on how to install and run SPICE as a scikit-learn estimator. To learn how to use SPICE in more comprehensive scenarios, you can go to [tutorials](tutorials).\n\n![Figure 1 - SPICE Overview](https://github.com/whyhardt/SPICE/blob/main/figures/spice_overview.jpg?raw=true \"Figure 1: SPICE overview\")\n\n## Installation\n\nYou can install SPICE using pip:\n\n```bash\npip install autospice\n```\n\nor, you can clone this repository and install it locally from the root folder:\n\n```bash\npip install -e .\n```\n\n## Features\n\n- Scikit-learn compatible estimator interface\n- Customizable network architecture for identifying complex cognitive mechanisms\n- Participant embeddings for identifying individual differences\n- Precoded models for simple Rescorla-Wagner, forgetting mechanism, choise perseveration and parcitipant embeddings\n\n## Quick Start\n\n```python\nfrom spice.estimator import SpiceEstimator\nfrom spice.precoded import RescorlaWagnerRNN, RESCOLA_WAGNER_CONFIG\nfrom spice.resources.bandits import BanditsDrift, AgentQ, create_dataset\n\n# Simulate dataset from a two-armed bandit task with a Q agent\nenvironment = BanditsDrift(sigma=0.2, n_actions=2)\n\nagent = AgentQ(\n    n_actions=2,\n    alpha_reward=0.6,  # Learning rate for positive rewards \n    alpha_penalty=0.6,  # Learning rate for negative rewards\n    forget_rate=0.3,\n)\n\ndataset, _, _ = create_dataset(\n    agent=agent,\n    environment=environment,\n    n_trials=200,\n    n_sessions=256,\n)\n\n# Create and fit SPICE model\nspice_estimator = SpiceEstimator(\n    rnn_class=RescorlaWagnerRNN,\n    spice_config=RESCOLA_WAGNER_CONFIG,\n    hidden_size=8,\n    learning_rate=5e-3,\n    epochs=16,\n    n_steps_per_call=16,\n    spice_participant_id=0,\n    save_path_rnn='rnn_model.pkl',   # (Optional) File path (.pkl) to save RNN model after training\n    save_path_spice='spice_model.pkl', # (Optional) File path (.pkl) to save SPICE model after training\n    verbose=True,\n)\n\nspice_estimator.fit(dataset.xs, dataset.ys)\n\n# Get learned SPICE features\nfeatures = spice_estimator.spice_agent.get_spice_features()\nfor id, feat in features.items():\n    print(f\"\\nAgent {id}:\")\n    for model_name, (feat_names, coeffs) in feat.items():\n        print(f\"  {model_name}:\")\n        for name, coeff in zip(feat_names, coeffs):\n            print(f\"    {name}: {coeff}\")\n\n# Predict behavior\npred_rnn, pred_spice = spice_estimator.predict(dataset.xs)\n\nprint(\"\\nPrediction shapes:\")\nprint(f\"RNN predictions: {pred_rnn.shape}\")\nprint(f\"SPICE predictions: {pred_spice.shape}\")  \n```\n\n### Saving and loading models\n\nIn addition to specifying save paths when creating the SpiceEstimator, you can also save an existing estimator's models, or load from save files:\n\n```python\n# Save trained model to file\nspice_estimator.save_spice(path_rnn='rnn_model.pkl', path_spice='spice_model.pkl')\n\n# Load saved model\nloaded_spice = SpiceEstimator.load_spice(path_rnn='rnn_model.pkl', path_spice='spice_model.pkl')\n\n# Use loaded model for predictions\npred_rnn, pred_spice = loaded_spice.predict(dataset.xs)\n```\n\n## Requirements\n\nSee `requirements.txt` for a complete list of dependencies.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Citation\n\nIf you use this package in your research, please cite:\n\n```bibtex\n@software{spice2025,\n  title = {SPICE: Sparse and Interpretable Cognitive Equations},\n  year = {2025},\n  author = {Weinhardt, Daniel},\n  url = {https://github.com/whyhardt/SPICE}\n}\n```\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Daniel Weinhardt\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.\n        ",
    "summary": "SPICE: Sparse and Interpretable Cognitive Equations",
    "version": "0.1.5",
    "project_urls": {
        "Documentation": "https://whyhardt.github.io/SPICE/",
        "Issues": "https://github.com/whyhardt/SPICE/issues",
        "Repository": "https://github.com/whyhardt/SPICE"
    },
    "split_keywords": [
        "cognitive-science",
        " reinforcement-learning",
        " machine-learning",
        " rnn",
        " dynamical-systems",
        " sindy"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "41bcf8aa4a539622999720b5351ebee69f8fafc313e3c404ef0fb2b4a62e98f5",
                "md5": "80d7d220d0ee5965632717dcd48541b3",
                "sha256": "fe333df631764824a9ee54bbc5f64213fc3c5b90f0d42be7b7d7218775826c96"
            },
            "downloads": -1,
            "filename": "autospice-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "80d7d220d0ee5965632717dcd48541b3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 60719,
            "upload_time": "2025-07-23T16:25:36",
            "upload_time_iso_8601": "2025-07-23T16:25:36.163519Z",
            "url": "https://files.pythonhosted.org/packages/41/bc/f8aa4a539622999720b5351ebee69f8fafc313e3c404ef0fb2b4a62e98f5/autospice-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4f424ee17a03c322bd1707fba359aa4ee28c114c4bab580f3bb04df3e94638ca",
                "md5": "42f6ca0de38714656c3235b9b1049add",
                "sha256": "61192c0ddd15c96038ab4215299186a5a64f111d9b2cc2992c969a48f5ef9138"
            },
            "downloads": -1,
            "filename": "autospice-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "42f6ca0de38714656c3235b9b1049add",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 719305,
            "upload_time": "2025-07-23T16:25:37",
            "upload_time_iso_8601": "2025-07-23T16:25:37.601757Z",
            "url": "https://files.pythonhosted.org/packages/4f/42/4ee17a03c322bd1707fba359aa4ee28c114c4bab580f3bb04df3e94638ca/autospice-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-23 16:25:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "whyhardt",
    "github_project": "SPICE",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "arviz",
            "specs": [
                [
                    "==",
                    "0.20.0"
                ]
            ]
        },
        {
            "name": "jax",
            "specs": [
                [
                    "==",
                    "0.4.35"
                ]
            ]
        },
        {
            "name": "matplotlib",
            "specs": [
                [
                    "==",
                    "3.10.1"
                ]
            ]
        },
        {
            "name": "numpy",
            "specs": [
                [
                    ">=",
                    "1.21.0"
                ]
            ]
        },
        {
            "name": "numpyro",
            "specs": [
                [
                    "==",
                    "0.15.3"
                ]
            ]
        },
        {
            "name": "pandas",
            "specs": [
                [
                    "==",
                    "2.2.3"
                ]
            ]
        },
        {
            "name": "pymc",
            "specs": [
                [
                    "==",
                    "5.21.0"
                ]
            ]
        },
        {
            "name": "pyro_ppl",
            "specs": [
                [
                    "==",
                    "1.9.1"
                ]
            ]
        },
        {
            "name": "pysindy",
            "specs": [
                [
                    ">=",
                    "1.7.0"
                ]
            ]
        },
        {
            "name": "scikit-learn",
            "specs": [
                [
                    ">=",
                    "1.0.0"
                ]
            ]
        },
        {
            "name": "scipy",
            "specs": [
                [
                    "==",
                    "1.15.2"
                ]
            ]
        },
        {
            "name": "seaborn",
            "specs": [
                [
                    "==",
                    "0.13.2"
                ]
            ]
        },
        {
            "name": "theano",
            "specs": [
                [
                    "==",
                    "1.0.5"
                ]
            ]
        },
        {
            "name": "torch",
            "specs": [
                [
                    ">=",
                    "2.0.0"
                ]
            ]
        },
        {
            "name": "tqdm",
            "specs": [
                [
                    ">=",
                    "4.65.0"
                ]
            ]
        },
        {
            "name": "optuna",
            "specs": [
                [
                    "==",
                    "4.3.0"
                ]
            ]
        },
        {
            "name": "dill",
            "specs": [
                [
                    "==",
                    "0.4.0"
                ]
            ]
        },
        {
            "name": "pytest",
            "specs": [
                [
                    ">=",
                    "7.0.0"
                ]
            ]
        }
    ],
    "lcname": "autospice"
}
        
Elapsed time: 1.11849s