sawmil


Namesawmil JSON
Version 0.1.10 PyPI version JSON
download
home_pageNone
SummarySparse Multiple-Instance Learning: SVM, NSK, sMIL and sAwMIL.
upload_time2025-09-04 13:39:19
maintainerNone
docs_urlNone
authorGermans Savcisens, Tina Eliassi-Rad
requires_python>=3.11
licenseMIT License Copyright (c) 2025 Germans Savcisens and Tina Eliassi-Rad 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 mil bag kernels multiple-instance-learning sawmil sparse svm
VCS
bugtrack_url
requirements numpy scikit-learn gurobipy osqp scipy
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Sparse Multiple-Instance Learning in Python

![PyPI - Version](https://img.shields.io/pypi/v/sawmil?style=flat-square)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/sawmil?style=flat-square)
![PyPI - Status](https://img.shields.io/pypi/status/sawmil?style=flat-square)
![GitHub License](https://img.shields.io/github/license/carlomarxdk/sawmil?style=flat-square)
[![Docs](https://img.shields.io/badge/docs-latest-purple?logo=mkdocs&style=flat-square)](https://carlomarxdk.github.io/sawmil/)
[![DOI](https://zenodo.org/badge/1046623935.svg)](https://doi.org/10.5281/zenodo.16990499)

MIL models based on the Support Vector Machines (NSK, sMIL, sAwMIL).
Inspired by the outdated [misvm](https://github.com/garydoranjr/misvm) package.

## Documentation

Refer to the [Initial Documentation](https://carlomarxdk.github.io/sawmil/).

## Implemented Models

### Normalized Set Kernels (`NSK`)

> Gärtner, Thomas, Peter A. Flach, Adam Kowalczyk, and Alex J. Smola. [Multi-instance kernels](https://dl.acm.org/doi/10.5555/645531.656014). Proceedings of the 19th International Conference on Machine Learning (2002).

### Sparse MIL (`sMIL`)

> Bunescu, Razvan C., and Raymond J. Mooney. [Multiple instance learning for sparse positive bags](https://dl.acm.org/doi/10.1145/1273496.1273510). Proceedings of the 24th International Conference on Machine Learning (2007).

### Sparse Aware MIL (`sAwMIL`)

Classifier used in [trilemma-of-truth](https://github.com/carlomarxdk/trilemma-of-truth):
> Savcisens, Germans, and Tina Eliassi-Rad. [The Trilemma of Truth in Large Language Models](https://arxiv.org/abs/2506.23921). arXiv preprint arXiv:2506.23921 (2025).

---

## Installation

`sawmil` supports two QP backends: [Gurobi](https://gurobi.com) and [OSQP](https://osqp.org/).
By default, the base package installs **without** any solver; pick one (or both) via extras.

### Base package (no solver)

```bash
pip install sawmil
# it installs numpy>=1.22 and scikit-learn>=1.7.0
```

### Option 1 — Gurobi backend

> Gurobi is commercial software. You’ll need a valid license (academic or commercial), refer to the [official website](https://gurobi.com).

```bash
pip install "sawmil[gurobi]"
# in additionl to the base packages, it install gurobi>12.0.3
```

### Option 2 — OSQP backend

```bash
pip install "sawmil[osqp]"
# in additionl to the base packages, it installs osqp>=1.0.4 and scipy
```

### Option 3 — All supported solvers

```bash
pip install "sawmil[full]"
```

### Picking the solver in code

```python
from sawmil import SVM, RBF

k = RBF(gamma = 0.1)
# solver= "osqp" (default is "gurobi")
# SVM is for single-instances 
clf = SVM(C=1.0, 
          kernel=k, 
          solver="osqp").fit(X, y)
```

## Quick start

### 1. Generate Dummy Data

``` python
from sawmil.data import generate_dummy_bags
import numpy as np
rng = np.random.default_rng(0)

ds = generate_dummy_bags(
    n_pos=300, n_neg=100, inst_per_bag=(5, 15), d=2,
    pos_centers=((+2,+1), (+4,+3)),
    neg_centers=((-1.5,-1.0), (-3.0,+0.5)),
    pos_scales=((2.0, 0.6), (1.2, 0.8)),
    neg_scales=((1.5, 0.5), (2.5, 0.9)),
    pos_intra_rate=(0.25, 0.85),
    ensure_pos_in_every_pos_bag=True,
    neg_pos_noise_rate=(0.00, 0.05),
    pos_neg_noise_rate=(0.00, 0.20),
    outlier_rate=0.1,
    outlier_scale=8.0,
    random_state=42,
)
```

### 2. Fit `NSK` with RBF Kernel

**Load a kernel:**

```python
from sawmil.kernels import get_kernel, RBF
k1 = get_kernel("rbf", gamma=0.1)
k2 = RBF(gamma=0.1)
# k1 == k2

```

**Fit NSK Model:**

```python
from sawmil.nsk import NSK

clf = NSK(C=1, kernel=k, 
          # bag kernel settings
          normalizer='average',
          # solver params
          scale_C=True, 
          tol=1e-8, 
          verbose=False).fit(ds, None)
y = ds.y
print("Train acc:", clf.score(ds, y))
```

### 3. Fit `sMIL` Model with Linear Kernel

```python
from sawmil.smil import sMIL

k = get_kernel("linear") # base (single-instance kernel)
clf = sMIL(C=0.1, 
           kernel=k, 
           scale_C=True, 
           tol=1e-8, 
           verbose=False).fit(ds, None)
```

See more examples in the [`example.ipynb`](https://github.com/carlomarxdk/sawmil/blob/main/example.ipynb) notebook.

### 4. Fit `sAwMIL` with Combined Kernels

```python
from sawmil.kernels import Product, Polynomial, Linear, RBF, Sum, Scale
from sawmil.sawmil import sAwMIL

k = Sum(Linear(), 
        Scale(0.5, 
              Product(Polynomial(degree=2), RBF(gamma=1.0))))

clf = sAwMIL(C=0.1, 
             kernel=k,
             solver="gurobi", 
             eta=0.95) # here eta is high, since all items in the bag are relevant
clf.fit(ds)
print("Train acc:", clf.score(ds, ds.y))
```

## Citation

If you use `sawmil` package in academic work, please cite:

Savcisens, G. & Eliassi-Rad, T. *sAwMIL: Python package for Sparse Multiple-Instance Learning* (2025).

```bibtex
@software{savcisens2025sawmil,
  author = {Savcisens, Germans and Eliassi-Rad, Tina},
  title = {sAwMIL: Python package for Sparse Multiple-Instance Learning},
  year = {2025},
  doi = {10.5281/zenodo.16990499},
  url = {https://github.com/carlomarxdk/sawmil}
}
```

If you want to reference a specific version of the package, find the [correct DOI here](https://doi.org/10.5281/zenodo.16990499).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "sawmil",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "MIL, bag, kernels, multiple-instance-learning, sawmil, sparse, svm",
    "author": "Germans Savcisens, Tina Eliassi-Rad",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/b8/6f/4179f417223c8d49aac81c45025093400d0d41beda51bf859bd9e92d7471/sawmil-0.1.10.tar.gz",
    "platform": null,
    "description": "# Sparse Multiple-Instance Learning in Python\n\n![PyPI - Version](https://img.shields.io/pypi/v/sawmil?style=flat-square)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/sawmil?style=flat-square)\n![PyPI - Status](https://img.shields.io/pypi/status/sawmil?style=flat-square)\n![GitHub License](https://img.shields.io/github/license/carlomarxdk/sawmil?style=flat-square)\n[![Docs](https://img.shields.io/badge/docs-latest-purple?logo=mkdocs&style=flat-square)](https://carlomarxdk.github.io/sawmil/)\n[![DOI](https://zenodo.org/badge/1046623935.svg)](https://doi.org/10.5281/zenodo.16990499)\n\nMIL models based on the Support Vector Machines (NSK, sMIL, sAwMIL).\nInspired by the outdated [misvm](https://github.com/garydoranjr/misvm) package.\n\n## Documentation\n\nRefer to the [Initial Documentation](https://carlomarxdk.github.io/sawmil/).\n\n## Implemented Models\n\n### Normalized Set Kernels (`NSK`)\n\n> G\u00e4rtner, Thomas, Peter A. Flach, Adam Kowalczyk, and Alex J. Smola. [Multi-instance kernels](https://dl.acm.org/doi/10.5555/645531.656014). Proceedings of the 19th International Conference on Machine Learning (2002).\n\n### Sparse MIL (`sMIL`)\n\n> Bunescu, Razvan C., and Raymond J. Mooney. [Multiple instance learning for sparse positive bags](https://dl.acm.org/doi/10.1145/1273496.1273510). Proceedings of the 24th International Conference on Machine Learning (2007).\n\n### Sparse Aware MIL (`sAwMIL`)\n\nClassifier used in [trilemma-of-truth](https://github.com/carlomarxdk/trilemma-of-truth):\n> Savcisens, Germans, and Tina Eliassi-Rad. [The Trilemma of Truth in Large Language Models](https://arxiv.org/abs/2506.23921). arXiv preprint arXiv:2506.23921 (2025).\n\n---\n\n## Installation\n\n`sawmil` supports two QP backends: [Gurobi](https://gurobi.com) and [OSQP](https://osqp.org/).\nBy default, the base package installs **without** any solver; pick one (or both) via extras.\n\n### Base package (no solver)\n\n```bash\npip install sawmil\n# it installs numpy>=1.22 and scikit-learn>=1.7.0\n```\n\n### Option 1 \u2014 Gurobi backend\n\n> Gurobi is commercial software. You\u2019ll need a valid license (academic or commercial), refer to the [official website](https://gurobi.com).\n\n```bash\npip install \"sawmil[gurobi]\"\n# in additionl to the base packages, it install gurobi>12.0.3\n```\n\n### Option 2 \u2014 OSQP backend\n\n```bash\npip install \"sawmil[osqp]\"\n# in additionl to the base packages, it installs osqp>=1.0.4 and scipy\n```\n\n### Option 3 \u2014 All supported solvers\n\n```bash\npip install \"sawmil[full]\"\n```\n\n### Picking the solver in code\n\n```python\nfrom sawmil import SVM, RBF\n\nk = RBF(gamma = 0.1)\n# solver= \"osqp\" (default is \"gurobi\")\n# SVM is for single-instances \nclf = SVM(C=1.0, \n          kernel=k, \n          solver=\"osqp\").fit(X, y)\n```\n\n## Quick start\n\n### 1. Generate Dummy Data\n\n``` python\nfrom sawmil.data import generate_dummy_bags\nimport numpy as np\nrng = np.random.default_rng(0)\n\nds = generate_dummy_bags(\n    n_pos=300, n_neg=100, inst_per_bag=(5, 15), d=2,\n    pos_centers=((+2,+1), (+4,+3)),\n    neg_centers=((-1.5,-1.0), (-3.0,+0.5)),\n    pos_scales=((2.0, 0.6), (1.2, 0.8)),\n    neg_scales=((1.5, 0.5), (2.5, 0.9)),\n    pos_intra_rate=(0.25, 0.85),\n    ensure_pos_in_every_pos_bag=True,\n    neg_pos_noise_rate=(0.00, 0.05),\n    pos_neg_noise_rate=(0.00, 0.20),\n    outlier_rate=0.1,\n    outlier_scale=8.0,\n    random_state=42,\n)\n```\n\n### 2. Fit `NSK` with RBF Kernel\n\n**Load a kernel:**\n\n```python\nfrom sawmil.kernels import get_kernel, RBF\nk1 = get_kernel(\"rbf\", gamma=0.1)\nk2 = RBF(gamma=0.1)\n# k1 == k2\n\n```\n\n**Fit NSK Model:**\n\n```python\nfrom sawmil.nsk import NSK\n\nclf = NSK(C=1, kernel=k, \n          # bag kernel settings\n          normalizer='average',\n          # solver params\n          scale_C=True, \n          tol=1e-8, \n          verbose=False).fit(ds, None)\ny = ds.y\nprint(\"Train acc:\", clf.score(ds, y))\n```\n\n### 3. Fit `sMIL` Model with Linear Kernel\n\n```python\nfrom sawmil.smil import sMIL\n\nk = get_kernel(\"linear\") # base (single-instance kernel)\nclf = sMIL(C=0.1, \n           kernel=k, \n           scale_C=True, \n           tol=1e-8, \n           verbose=False).fit(ds, None)\n```\n\nSee more examples in the [`example.ipynb`](https://github.com/carlomarxdk/sawmil/blob/main/example.ipynb) notebook.\n\n### 4. Fit `sAwMIL` with Combined Kernels\n\n```python\nfrom sawmil.kernels import Product, Polynomial, Linear, RBF, Sum, Scale\nfrom sawmil.sawmil import sAwMIL\n\nk = Sum(Linear(), \n        Scale(0.5, \n              Product(Polynomial(degree=2), RBF(gamma=1.0))))\n\nclf = sAwMIL(C=0.1, \n             kernel=k,\n             solver=\"gurobi\", \n             eta=0.95) # here eta is high, since all items in the bag are relevant\nclf.fit(ds)\nprint(\"Train acc:\", clf.score(ds, ds.y))\n```\n\n## Citation\n\nIf you use `sawmil` package in academic work, please cite:\n\nSavcisens, G. & Eliassi-Rad, T. *sAwMIL: Python package for Sparse Multiple-Instance Learning* (2025).\n\n```bibtex\n@software{savcisens2025sawmil,\n  author = {Savcisens, Germans and Eliassi-Rad, Tina},\n  title = {sAwMIL: Python package for Sparse Multiple-Instance Learning},\n  year = {2025},\n  doi = {10.5281/zenodo.16990499},\n  url = {https://github.com/carlomarxdk/sawmil}\n}\n```\n\nIf you want to reference a specific version of the package, find the [correct DOI here](https://doi.org/10.5281/zenodo.16990499).\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Germans Savcisens and Tina Eliassi-Rad\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": "Sparse Multiple-Instance Learning: SVM, NSK, sMIL and sAwMIL.",
    "version": "0.1.10",
    "project_urls": {
        "Citation": "https://github.com/carlomarxdk/sawmil/blob/main/citation.cff",
        "DOI": "https://doi.org/10.5281/zenodo.16990499",
        "Documentation": "https://carlomarxdk.github.io/sawmil/",
        "Homepage": "https://github.com/carlomarxdk/sawmil",
        "Issues": "https://github.com/carlomarxdk/sawmil/issues",
        "Paper": "https://arxiv.org/abs/2506.23921"
    },
    "split_keywords": [
        "mil",
        " bag",
        " kernels",
        " multiple-instance-learning",
        " sawmil",
        " sparse",
        " svm"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7ca7e8281671fcd2ef1d71331dc1e9949478b1929a040e6a75eed570f90d8493",
                "md5": "07d6bc9605cb7a27ea2307582e0605dc",
                "sha256": "fb7ae42d915bd5cd3ffa680c9bc6bda2e316ceca8a969324ca1a7df4458cac7d"
            },
            "downloads": -1,
            "filename": "sawmil-0.1.10-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "07d6bc9605cb7a27ea2307582e0605dc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 33750,
            "upload_time": "2025-09-04T13:39:18",
            "upload_time_iso_8601": "2025-09-04T13:39:18.386995Z",
            "url": "https://files.pythonhosted.org/packages/7c/a7/e8281671fcd2ef1d71331dc1e9949478b1929a040e6a75eed570f90d8493/sawmil-0.1.10-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b86f4179f417223c8d49aac81c45025093400d0d41beda51bf859bd9e92d7471",
                "md5": "585e83158c93d5de225fb5fbcc199dfd",
                "sha256": "d5ed5a85e70352ef5916c4965c74a6e7532e9c035b66cc92c0775e1ef1d25e1c"
            },
            "downloads": -1,
            "filename": "sawmil-0.1.10.tar.gz",
            "has_sig": false,
            "md5_digest": "585e83158c93d5de225fb5fbcc199dfd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 25662,
            "upload_time": "2025-09-04T13:39:19",
            "upload_time_iso_8601": "2025-09-04T13:39:19.563814Z",
            "url": "https://files.pythonhosted.org/packages/b8/6f/4179f417223c8d49aac81c45025093400d0d41beda51bf859bd9e92d7471/sawmil-0.1.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-04 13:39:19",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "carlomarxdk",
    "github_project": "sawmil",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "numpy",
            "specs": [
                [
                    ">=",
                    "1.22"
                ]
            ]
        },
        {
            "name": "scikit-learn",
            "specs": [
                [
                    ">=",
                    "1.7.0"
                ]
            ]
        },
        {
            "name": "gurobipy",
            "specs": [
                [
                    ">=",
                    "12.0.3"
                ]
            ]
        },
        {
            "name": "osqp",
            "specs": [
                [
                    ">=",
                    "1.0.4"
                ]
            ]
        },
        {
            "name": "scipy",
            "specs": [
                [
                    ">=",
                    "1.16.1"
                ]
            ]
        }
    ],
    "lcname": "sawmil"
}
        
Elapsed time: 1.07405s