torchoutil


Nametorchoutil JSON
Version 0.4.0 PyPI version JSON
download
home_pageNone
SummaryCollection of functions and modules to help development in PyTorch.
upload_time2024-05-27 15:37:34
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 torch typing_extensions
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
```


## Examples

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

probs = torch.as_tensor([[0.9, 0.1], [0.4, 0.6]])
names = probs_to_name(probs, idx_to_name={0: "Cat", 1: "Dog"})
# ["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], []]
```

### Masked operations

```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]])
```

```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
```

### Pre-compute datasets to pickle or HDF files

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

```python
from torch import nn
from torchaudio.datasets import SPEECHCOMMANDS
from torchaudio.transforms import Spectrogram
from torchoutil.utils.pack import pack_to_custom

speech_commands_root = "path/to/speech_commands"
packed_root = "path/to/packed_dataset"

dataset = SPEECHCOMMANDS(speech_commands_root, download=True, subset="validation")
# dataset[0] is a tuple, contains waveform and other metadata

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_custom(dataset, packed_root, MyTransform())
```

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

packed_root = "path/to/packed_dataset"
packed_dataset = PackedDataset(packed_root)
packed_dataset[0]  # == first transformed item, i.e. transform(dataset[0])
```

### Other tensors 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 requirements
`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 `NumpyToTensor` 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/54/66/3b1784e74938845c07c94f8f2dcf02902ed7deca368ea13fd756a64d0016/torchoutil-0.4.0.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## Examples\n\n### Multilabel conversions\n```python\nimport torch\nfrom torchoutil import probs_to_name\n\nprobs = torch.as_tensor([[0.9, 0.1], [0.4, 0.6]])\nnames = probs_to_name(probs, idx_to_name={0: \"Cat\", 1: \"Dog\"})\n# [\"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### Masked operations\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```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### Pre-compute datasets to pickle or HDF files\n\nHere is an example of pre-computing spectrograms of torchaudio `SPEECHCOMMANDS` dataset, using `pack_to_custom` function:\n\n```python\nfrom torch import nn\nfrom torchaudio.datasets import SPEECHCOMMANDS\nfrom torchaudio.transforms import Spectrogram\nfrom torchoutil.utils.pack import pack_to_custom\n\nspeech_commands_root = \"path/to/speech_commands\"\npacked_root = \"path/to/packed_dataset\"\n\ndataset = SPEECHCOMMANDS(speech_commands_root, download=True, subset=\"validation\")\n# dataset[0] is a tuple, contains waveform and other metadata\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_custom(dataset, packed_root, MyTransform())\n```\n\nThen you can load the pre-computed dataset using `PackedDataset`:\n```python\nfrom torchoutil.utils.pack import PackedDataset\n\npacked_root = \"path/to/packed_dataset\"\npacked_dataset = PackedDataset(packed_root)\npacked_dataset[0]  # == first transformed item, i.e. transform(dataset[0])\n```\n\n### Other tensors 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 requirements\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 `NumpyToTensor` 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.4.0",
    "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": "54663b1784e74938845c07c94f8f2dcf02902ed7deca368ea13fd756a64d0016",
                "md5": "3e1a75256b8fdc4310b994f53ff9e78b",
                "sha256": "01b99858a0680cf40b7764286f4fa43e1e3f82eebe176630bfce98d612ec66b4"
            },
            "downloads": -1,
            "filename": "torchoutil-0.4.0.tar.gz",
            "has_sig": false,
            "md5_digest": "3e1a75256b8fdc4310b994f53ff9e78b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 65728,
            "upload_time": "2024-05-27T15:37:34",
            "upload_time_iso_8601": "2024-05-27T15:37:34.770135Z",
            "url": "https://files.pythonhosted.org/packages/54/66/3b1784e74938845c07c94f8f2dcf02902ed7deca368ea13fd756a64d0016/torchoutil-0.4.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-27 15:37:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Labbeti",
    "github_project": "torchoutil",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "torch",
            "specs": [
                [
                    ">=",
                    "1.10.0"
                ]
            ]
        },
        {
            "name": "typing_extensions",
            "specs": []
        }
    ],
    "lcname": "torchoutil"
}
        
Elapsed time: 0.73961s