torchoutil


Nametorchoutil JSON
Version 0.3.1 PyPI version JSON
download
home_pageNone
SummaryCollection of functions and modules to help development in PyTorch.
upload_time2024-04-25 15:01:35
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License Copyright (c) 2024 Labbeti 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 pytorch deep-learning
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # torchoutil

<center>

<a href="https://www.python.org/">
    <img alt="Python" src="https://img.shields.io/badge/-Python 3.8+-blue?style=for-the-badge&logo=python&logoColor=white">
</a>
<a href="https://pytorch.org/get-started/locally/">
    <img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch 1.10+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white">
</a>
<a href="https://black.readthedocs.io/en/stable/">
    <img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray">
</a>
<a href="https://github.com/Labbeti/torchoutil/actions">
    <img alt="Build" src="https://img.shields.io/github/actions/workflow/status/Labbeti/torchoutil/test.yaml?branch=main&style=for-the-badge&logo=github">
</a>
<a href='https://torchoutil.readthedocs.io/en/stable/?badge=stable'>
    <img src='https://readthedocs.org/projects/torchoutil/badge/?version=stable&style=for-the-badge' alt='Documentation Status' />
</a>

Collection of functions and modules to help development in PyTorch.

</center>


## Installation
```bash
pip install torchoutil
```

The only requirement is **PyTorch**.

To check if the package is installed and show the package version, you can use the following command:
```bash
torchoutil-info
```


## Usage

### Batch of padded sequences
```python
import torch
from torchoutil import masked_mean

x = torch.as_tensor([1, 2, 3, 4])
mask = torch.as_tensor([True, True, False, False])
result = masked_mean(x, mask)
# result contains the mean of the values marked as True: 1.5
```

```python
import torch
from torchoutil import lengths_to_non_pad_mask

x = torch.as_tensor([3, 1, 2])
mask = lengths_to_non_pad_mask(x, max_len=4)
# Each row i contains x[i] True values for non-padding mask
# tensor([[True, True, True, False],
#         [True, False, False, False],
#         [True, True, False, False]])
```

### Multilabel conversions
```python
import torch
from torchoutil import probs_to_names

probs = torch.as_tensor([[0.9, 0.1], [0.6, 0.9]])
names = probs_to_names(probs, threshold=0.5, idx_to_name={0: "Cat", 1: "Dog"})
# [["Cat"], ["Cat", "Dog"]]
```

```python
import torch
from torchoutil import multihot_to_indices

multihot = torch.as_tensor([[1, 0, 0], [0, 1, 1], [0, 0, 0]])
indices = multihot_to_indices(multihot)
# [[0], [1, 2], []]
```

### Easely pre-compute transforms

Here is an example of pre-computing spectrograms of torchaudio `SPEECHCOMMANDS` dataset, using `pack_to_pickle` function:

```python
from torch import nn
from torchaudio.datasets import SPEECHCOMMANDS
from torchaudio.transforms import Spectrogram
from torchoutil.utils.pickle_dataset import pack_to_pickle

speech_commands_root = "path/to/speech_commands"
pickle_root = "path/to/pickle_dataset"

dataset = SPEECHCOMMANDS(speech_commands_root, download=True, subset="validation")

class MyTransform(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.spectrogram_extractor = Spectrogram()

    def forward(self, item):
        waveform = item[0]
        spectrogram = self.spectrogram_extractor(waveform)
        return (spectrogram,) + item[1:]

pack_to_pickle(dataset, pickle_root, MyTransform())
```

Then you can load the pre-computed dataset using `PickleDataset`:
```python
from torchoutil.utils.pickle_dataset import PickleDataset

pickle_root = "path/to/pickle_dataset"
pickle_dataset = PickleDataset(pickle_root)
pickle_dataset[0]  # == first transformed item, i.e. transform(dataset[0])
```

### ...and more tensor manipulations!

```python
import torch
from torchoutil import insert_at_indices

x = torch.as_tensor([1, 2, 3, 4])
result = insert_at_indices(x, indices=[0, 2], values=5)
# result contains tensor with inserted values: tensor([5, 1, 2, 5, 3, 4])
```

```python
import torch
from torchoutil import get_inverse_perm

perm = torch.randperm(10)
inv_perm = get_inverse_perm(perm)

x1 = torch.rand(10)
x2 = x1[perm]
x3 = x2[inv_perm]
# inv_perm are indices that allow us to get x3 from x2, i.e. x1 == x3 here
```

## Extras
`torchoutil` also provides additional modules when some specific package are already installed in your environment.
All extras can be installed with `pip install torchoutil[extras]`

- If `tensorboard` is installed, the function `load_event_file` can be used. It is useful to load manually all data contained in an tensorboard event file.
- If `numpy` is installed, the classes `FromNumpy` and  `ToNumpy` can be used and their related function. It is meant to be used to compose dynamic transforms into `Sequential` module.
- If `h5py` is installed, the function `pack_to_hdf` and class `HDFDataset` can be used. Can be used to pack/read dataset to HDF files, and supports variable-length sequences of data.


## Contact
Maintainer:
- [Étienne Labbé](https://labbeti.github.io/) "Labbeti": labbeti.pub@gmail.com

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "torchoutil",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "\"\u00c9tienne Labb\u00e9 (Labbeti)\" <labbeti.pub@gmail.com>",
    "keywords": "pytorch, deep-learning",
    "author": null,
    "author_email": "\"\u00c9tienne Labb\u00e9 (Labbeti)\" <labbeti.pub@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c4/cb/cfa5faf5f7464909673c25289cb82a3ab43dcbc6ed6d8caec3ef743faa22/torchoutil-0.3.1.tar.gz",
    "platform": null,
    "description": "# torchoutil\n\n<center>\n\n<a href=\"https://www.python.org/\">\n    <img alt=\"Python\" src=\"https://img.shields.io/badge/-Python 3.8+-blue?style=for-the-badge&logo=python&logoColor=white\">\n</a>\n<a href=\"https://pytorch.org/get-started/locally/\">\n    <img alt=\"PyTorch\" src=\"https://img.shields.io/badge/-PyTorch 1.10+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white\">\n</a>\n<a href=\"https://black.readthedocs.io/en/stable/\">\n    <img alt=\"Code style: black\" src=\"https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray\">\n</a>\n<a href=\"https://github.com/Labbeti/torchoutil/actions\">\n    <img alt=\"Build\" src=\"https://img.shields.io/github/actions/workflow/status/Labbeti/torchoutil/test.yaml?branch=main&style=for-the-badge&logo=github\">\n</a>\n<a href='https://torchoutil.readthedocs.io/en/stable/?badge=stable'>\n    <img src='https://readthedocs.org/projects/torchoutil/badge/?version=stable&style=for-the-badge' alt='Documentation Status' />\n</a>\n\nCollection of functions and modules to help development in PyTorch.\n\n</center>\n\n\n## Installation\n```bash\npip install torchoutil\n```\n\nThe only requirement is **PyTorch**.\n\nTo check if the package is installed and show the package version, you can use the following command:\n```bash\ntorchoutil-info\n```\n\n\n## Usage\n\n### Batch of padded sequences\n```python\nimport torch\nfrom torchoutil import masked_mean\n\nx = torch.as_tensor([1, 2, 3, 4])\nmask = torch.as_tensor([True, True, False, False])\nresult = masked_mean(x, mask)\n# result contains the mean of the values marked as True: 1.5\n```\n\n```python\nimport torch\nfrom torchoutil import lengths_to_non_pad_mask\n\nx = torch.as_tensor([3, 1, 2])\nmask = lengths_to_non_pad_mask(x, max_len=4)\n# Each row i contains x[i] True values for non-padding mask\n# tensor([[True, True, True, False],\n#         [True, False, False, False],\n#         [True, True, False, False]])\n```\n\n### Multilabel conversions\n```python\nimport torch\nfrom torchoutil import probs_to_names\n\nprobs = torch.as_tensor([[0.9, 0.1], [0.6, 0.9]])\nnames = probs_to_names(probs, threshold=0.5, idx_to_name={0: \"Cat\", 1: \"Dog\"})\n# [[\"Cat\"], [\"Cat\", \"Dog\"]]\n```\n\n```python\nimport torch\nfrom torchoutil import multihot_to_indices\n\nmultihot = torch.as_tensor([[1, 0, 0], [0, 1, 1], [0, 0, 0]])\nindices = multihot_to_indices(multihot)\n# [[0], [1, 2], []]\n```\n\n### Easely pre-compute transforms\n\nHere is an example of pre-computing spectrograms of torchaudio `SPEECHCOMMANDS` dataset, using `pack_to_pickle` function:\n\n```python\nfrom torch import nn\nfrom torchaudio.datasets import SPEECHCOMMANDS\nfrom torchaudio.transforms import Spectrogram\nfrom torchoutil.utils.pickle_dataset import pack_to_pickle\n\nspeech_commands_root = \"path/to/speech_commands\"\npickle_root = \"path/to/pickle_dataset\"\n\ndataset = SPEECHCOMMANDS(speech_commands_root, download=True, subset=\"validation\")\n\nclass MyTransform(nn.Module):\n    def __init__(self) -> None:\n        super().__init__()\n        self.spectrogram_extractor = Spectrogram()\n\n    def forward(self, item):\n        waveform = item[0]\n        spectrogram = self.spectrogram_extractor(waveform)\n        return (spectrogram,) + item[1:]\n\npack_to_pickle(dataset, pickle_root, MyTransform())\n```\n\nThen you can load the pre-computed dataset using `PickleDataset`:\n```python\nfrom torchoutil.utils.pickle_dataset import PickleDataset\n\npickle_root = \"path/to/pickle_dataset\"\npickle_dataset = PickleDataset(pickle_root)\npickle_dataset[0]  # == first transformed item, i.e. transform(dataset[0])\n```\n\n### ...and more tensor manipulations!\n\n```python\nimport torch\nfrom torchoutil import insert_at_indices\n\nx = torch.as_tensor([1, 2, 3, 4])\nresult = insert_at_indices(x, indices=[0, 2], values=5)\n# result contains tensor with inserted values: tensor([5, 1, 2, 5, 3, 4])\n```\n\n```python\nimport torch\nfrom torchoutil import get_inverse_perm\n\nperm = torch.randperm(10)\ninv_perm = get_inverse_perm(perm)\n\nx1 = torch.rand(10)\nx2 = x1[perm]\nx3 = x2[inv_perm]\n# inv_perm are indices that allow us to get x3 from x2, i.e. x1 == x3 here\n```\n\n## Extras\n`torchoutil` also provides additional modules when some specific package are already installed in your environment.\nAll extras can be installed with `pip install torchoutil[extras]`\n\n- If `tensorboard` is installed, the function `load_event_file` can be used. It is useful to load manually all data contained in an tensorboard event file.\n- If `numpy` is installed, the classes `FromNumpy` and  `ToNumpy` can be used and their related function. It is meant to be used to compose dynamic transforms into `Sequential` module.\n- If `h5py` is installed, the function `pack_to_hdf` and class `HDFDataset` can be used. Can be used to pack/read dataset to HDF files, and supports variable-length sequences of data.\n\n\n## Contact\nMaintainer:\n- [\u00c9tienne Labb\u00e9](https://labbeti.github.io/) \"Labbeti\": labbeti.pub@gmail.com\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Labbeti  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. ",
    "summary": "Collection of functions and modules to help development in PyTorch.",
    "version": "0.3.1",
    "project_urls": {
        "Changelog": "https://github.com/Labbeti/torchoutil/blob/main/CHANGELOG.md",
        "Documentation": "https://torchoutil.readthedocs.io/",
        "Homepage": "https://pypi.org/project/torchoutil/",
        "Repository": "https://github.com/Labbeti/torchoutil.git",
        "Tracker": "https://github.com/Labbeti/torchoutil/issues"
    },
    "split_keywords": [
        "pytorch",
        " deep-learning"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c4cbcfa5faf5f7464909673c25289cb82a3ab43dcbc6ed6d8caec3ef743faa22",
                "md5": "6f3e46645732a9bb84742cc21d0c44f3",
                "sha256": "dc788d9044a64e3f16e1e513fcffb83849e81f853ed54c81f5a9411a2a200bda"
            },
            "downloads": -1,
            "filename": "torchoutil-0.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "6f3e46645732a9bb84742cc21d0c44f3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 56132,
            "upload_time": "2024-04-25T15:01:35",
            "upload_time_iso_8601": "2024-04-25T15:01:35.857169Z",
            "url": "https://files.pythonhosted.org/packages/c4/cb/cfa5faf5f7464909673c25289cb82a3ab43dcbc6ed6d8caec3ef743faa22/torchoutil-0.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-25 15:01:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Labbeti",
    "github_project": "torchoutil",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "torchoutil"
}
        
Elapsed time: 0.25613s