Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/INSTALLER +1 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/METADATA +582 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/RECORD +709 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/WHEEL +5 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/licenses/LICENSE +201 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/top_level.txt +1 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/sam.py +121 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/scc.py +220 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/ssim.py +529 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/tv.py +77 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/uqi.py +171 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/utils.py +173 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/vif.py +154 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/__init__.py +23 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_iqa.py +350 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_score.py +354 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/lve.py +93 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/__init__.py +34 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/cramers.py +183 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/fleiss_kappa.py +99 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/pearson.py +174 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/theils_u.py +195 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/tschuprows.py +193 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/utils.py +146 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/__init__.py +26 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/cosine.py +91 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/euclidean.py +89 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/helpers.py +60 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/linear.py +84 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/manhattan.py +83 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/minkowski.py +93 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/__init__.py +61 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/concordance.py +83 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/cosine_similarity.py +101 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/crps.py +99 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/csi.py +112 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/explained_variance.py +142 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/js_divergence.py +102 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kendall.py +430 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kl_divergence.py +115 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_cosh.py +95 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_mse.py +76 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mae.py +81 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mape.py +91 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/minkowski.py +84 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mse.py +82 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/nrmse.py +106 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/pearson.py +189 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/r2.py +174 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/rse.py +80 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: torchmetrics
|
| 3 |
+
Version: 1.9.0
|
| 4 |
+
Summary: PyTorch native Metrics
|
| 5 |
+
Home-page: https://github.com/Lightning-AI/torchmetrics
|
| 6 |
+
Download-URL: https://github.com/Lightning-AI/torchmetrics/archive/master.zip
|
| 7 |
+
Author: Lightning-AI et al.
|
| 8 |
+
Author-email: name@pytorchlightning.ai
|
| 9 |
+
License: Apache-2.0
|
| 10 |
+
Project-URL: Bug Tracker, https://github.com/Lightning-AI/torchmetrics/issues
|
| 11 |
+
Project-URL: Documentation, https://torchmetrics.rtfd.io/en/latest/
|
| 12 |
+
Project-URL: Source Code, https://github.com/Lightning-AI/torchmetrics
|
| 13 |
+
Keywords: deep learning,machine learning,pytorch,metrics,AI
|
| 14 |
+
Classifier: Environment :: Console
|
| 15 |
+
Classifier: Natural Language :: English
|
| 16 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 19 |
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
| 20 |
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
| 21 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 22 |
+
Classifier: Operating System :: OS Independent
|
| 23 |
+
Classifier: Programming Language :: Python :: 3
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 27 |
+
Requires-Python: >=3.10
|
| 28 |
+
Description-Content-Type: text/markdown
|
| 29 |
+
License-File: LICENSE
|
| 30 |
+
Requires-Dist: numpy>1.20.0
|
| 31 |
+
Requires-Dist: packaging>17.1
|
| 32 |
+
Requires-Dist: torch>=2.0.0
|
| 33 |
+
Requires-Dist: lightning-utilities>=0.15.3
|
| 34 |
+
Provides-Extra: audio
|
| 35 |
+
Requires-Dist: requests>=2.22.0; extra == "audio"
|
| 36 |
+
Requires-Dist: onnxruntime>=1.12.0; extra == "audio"
|
| 37 |
+
Requires-Dist: gammatone>=1.0.0; extra == "audio"
|
| 38 |
+
Requires-Dist: pesq>=0.0.4; extra == "audio"
|
| 39 |
+
Requires-Dist: pystoi>=0.4.0; extra == "audio"
|
| 40 |
+
Requires-Dist: librosa>=0.10.0; extra == "audio"
|
| 41 |
+
Requires-Dist: torchaudio>=2.0.1; extra == "audio"
|
| 42 |
+
Provides-Extra: clustering
|
| 43 |
+
Requires-Dist: torch_linear_assignment>=0.0.2; extra == "clustering"
|
| 44 |
+
Provides-Extra: debug
|
| 45 |
+
Provides-Extra: detection
|
| 46 |
+
Requires-Dist: pycocotools>2.0.0; extra == "detection"
|
| 47 |
+
Requires-Dist: torchvision>=0.15.1; extra == "detection"
|
| 48 |
+
Provides-Extra: image
|
| 49 |
+
Requires-Dist: torch-fidelity<=0.4.0; extra == "image"
|
| 50 |
+
Requires-Dist: torchvision>=0.15.1; extra == "image"
|
| 51 |
+
Requires-Dist: scipy>1.0.0; extra == "image"
|
| 52 |
+
Provides-Extra: integrate
|
| 53 |
+
Provides-Extra: multimodal
|
| 54 |
+
Requires-Dist: timm>=0.9.0; extra == "multimodal"
|
| 55 |
+
Requires-Dist: transformers>=4.43.0; extra == "multimodal"
|
| 56 |
+
Requires-Dist: einops>=0.7.0; extra == "multimodal"
|
| 57 |
+
Requires-Dist: piq<=0.8.0; extra == "multimodal"
|
| 58 |
+
Provides-Extra: text
|
| 59 |
+
Requires-Dist: tqdm<4.68.0; extra == "text"
|
| 60 |
+
Requires-Dist: nltk>3.8.1; extra == "text"
|
| 61 |
+
Requires-Dist: ipadic>=1.0.0; extra == "text"
|
| 62 |
+
Requires-Dist: mecab-python3>=1.0.6; extra == "text"
|
| 63 |
+
Requires-Dist: transformers>=4.43.0; extra == "text"
|
| 64 |
+
Requires-Dist: regex>=2021.9.24; extra == "text"
|
| 65 |
+
Requires-Dist: sentencepiece>=0.2.0; extra == "text"
|
| 66 |
+
Provides-Extra: typing
|
| 67 |
+
Requires-Dist: types-six; extra == "typing"
|
| 68 |
+
Requires-Dist: mypy==1.17.1; extra == "typing"
|
| 69 |
+
Requires-Dist: types-requests; extra == "typing"
|
| 70 |
+
Requires-Dist: types-tabulate; extra == "typing"
|
| 71 |
+
Requires-Dist: types-setuptools; extra == "typing"
|
| 72 |
+
Requires-Dist: types-emoji; extra == "typing"
|
| 73 |
+
Requires-Dist: torch==2.8.0; extra == "typing"
|
| 74 |
+
Requires-Dist: types-PyYAML; extra == "typing"
|
| 75 |
+
Requires-Dist: types-protobuf; extra == "typing"
|
| 76 |
+
Provides-Extra: video
|
| 77 |
+
Requires-Dist: vmaf-torch>=1.1.0; extra == "video"
|
| 78 |
+
Requires-Dist: einops>=0.7.0; extra == "video"
|
| 79 |
+
Provides-Extra: visual
|
| 80 |
+
Requires-Dist: matplotlib>=3.6.0; extra == "visual"
|
| 81 |
+
Requires-Dist: SciencePlots>=2.0.0; extra == "visual"
|
| 82 |
+
Provides-Extra: all
|
| 83 |
+
Requires-Dist: requests>=2.22.0; extra == "all"
|
| 84 |
+
Requires-Dist: onnxruntime>=1.12.0; extra == "all"
|
| 85 |
+
Requires-Dist: gammatone>=1.0.0; extra == "all"
|
| 86 |
+
Requires-Dist: pesq>=0.0.4; extra == "all"
|
| 87 |
+
Requires-Dist: pystoi>=0.4.0; extra == "all"
|
| 88 |
+
Requires-Dist: librosa>=0.10.0; extra == "all"
|
| 89 |
+
Requires-Dist: torchaudio>=2.0.1; extra == "all"
|
| 90 |
+
Requires-Dist: torch_linear_assignment>=0.0.2; extra == "all"
|
| 91 |
+
Requires-Dist: pycocotools>2.0.0; extra == "all"
|
| 92 |
+
Requires-Dist: torchvision>=0.15.1; extra == "all"
|
| 93 |
+
Requires-Dist: torch-fidelity<=0.4.0; extra == "all"
|
| 94 |
+
Requires-Dist: torchvision>=0.15.1; extra == "all"
|
| 95 |
+
Requires-Dist: scipy>1.0.0; extra == "all"
|
| 96 |
+
Requires-Dist: timm>=0.9.0; extra == "all"
|
| 97 |
+
Requires-Dist: transformers>=4.43.0; extra == "all"
|
| 98 |
+
Requires-Dist: einops>=0.7.0; extra == "all"
|
| 99 |
+
Requires-Dist: piq<=0.8.0; extra == "all"
|
| 100 |
+
Requires-Dist: tqdm<4.68.0; extra == "all"
|
| 101 |
+
Requires-Dist: nltk>3.8.1; extra == "all"
|
| 102 |
+
Requires-Dist: ipadic>=1.0.0; extra == "all"
|
| 103 |
+
Requires-Dist: mecab-python3>=1.0.6; extra == "all"
|
| 104 |
+
Requires-Dist: transformers>=4.43.0; extra == "all"
|
| 105 |
+
Requires-Dist: regex>=2021.9.24; extra == "all"
|
| 106 |
+
Requires-Dist: sentencepiece>=0.2.0; extra == "all"
|
| 107 |
+
Requires-Dist: types-six; extra == "all"
|
| 108 |
+
Requires-Dist: mypy==1.17.1; extra == "all"
|
| 109 |
+
Requires-Dist: types-requests; extra == "all"
|
| 110 |
+
Requires-Dist: types-tabulate; extra == "all"
|
| 111 |
+
Requires-Dist: types-setuptools; extra == "all"
|
| 112 |
+
Requires-Dist: types-emoji; extra == "all"
|
| 113 |
+
Requires-Dist: torch==2.8.0; extra == "all"
|
| 114 |
+
Requires-Dist: types-PyYAML; extra == "all"
|
| 115 |
+
Requires-Dist: types-protobuf; extra == "all"
|
| 116 |
+
Requires-Dist: vmaf-torch>=1.1.0; extra == "all"
|
| 117 |
+
Requires-Dist: einops>=0.7.0; extra == "all"
|
| 118 |
+
Requires-Dist: matplotlib>=3.6.0; extra == "all"
|
| 119 |
+
Requires-Dist: SciencePlots>=2.0.0; extra == "all"
|
| 120 |
+
Provides-Extra: dev
|
| 121 |
+
Requires-Dist: requests>=2.22.0; extra == "dev"
|
| 122 |
+
Requires-Dist: onnxruntime>=1.12.0; extra == "dev"
|
| 123 |
+
Requires-Dist: gammatone>=1.0.0; extra == "dev"
|
| 124 |
+
Requires-Dist: pesq>=0.0.4; extra == "dev"
|
| 125 |
+
Requires-Dist: pystoi>=0.4.0; extra == "dev"
|
| 126 |
+
Requires-Dist: librosa>=0.10.0; extra == "dev"
|
| 127 |
+
Requires-Dist: torchaudio>=2.0.1; extra == "dev"
|
| 128 |
+
Requires-Dist: torch_linear_assignment>=0.0.2; extra == "dev"
|
| 129 |
+
Requires-Dist: pycocotools>2.0.0; extra == "dev"
|
| 130 |
+
Requires-Dist: torchvision>=0.15.1; extra == "dev"
|
| 131 |
+
Requires-Dist: torch-fidelity<=0.4.0; extra == "dev"
|
| 132 |
+
Requires-Dist: torchvision>=0.15.1; extra == "dev"
|
| 133 |
+
Requires-Dist: scipy>1.0.0; extra == "dev"
|
| 134 |
+
Requires-Dist: timm>=0.9.0; extra == "dev"
|
| 135 |
+
Requires-Dist: transformers>=4.43.0; extra == "dev"
|
| 136 |
+
Requires-Dist: einops>=0.7.0; extra == "dev"
|
| 137 |
+
Requires-Dist: piq<=0.8.0; extra == "dev"
|
| 138 |
+
Requires-Dist: tqdm<4.68.0; extra == "dev"
|
| 139 |
+
Requires-Dist: nltk>3.8.1; extra == "dev"
|
| 140 |
+
Requires-Dist: ipadic>=1.0.0; extra == "dev"
|
| 141 |
+
Requires-Dist: mecab-python3>=1.0.6; extra == "dev"
|
| 142 |
+
Requires-Dist: transformers>=4.43.0; extra == "dev"
|
| 143 |
+
Requires-Dist: regex>=2021.9.24; extra == "dev"
|
| 144 |
+
Requires-Dist: sentencepiece>=0.2.0; extra == "dev"
|
| 145 |
+
Requires-Dist: types-six; extra == "dev"
|
| 146 |
+
Requires-Dist: mypy==1.17.1; extra == "dev"
|
| 147 |
+
Requires-Dist: types-requests; extra == "dev"
|
| 148 |
+
Requires-Dist: types-tabulate; extra == "dev"
|
| 149 |
+
Requires-Dist: types-setuptools; extra == "dev"
|
| 150 |
+
Requires-Dist: types-emoji; extra == "dev"
|
| 151 |
+
Requires-Dist: torch==2.8.0; extra == "dev"
|
| 152 |
+
Requires-Dist: types-PyYAML; extra == "dev"
|
| 153 |
+
Requires-Dist: types-protobuf; extra == "dev"
|
| 154 |
+
Requires-Dist: vmaf-torch>=1.1.0; extra == "dev"
|
| 155 |
+
Requires-Dist: einops>=0.7.0; extra == "dev"
|
| 156 |
+
Requires-Dist: matplotlib>=3.6.0; extra == "dev"
|
| 157 |
+
Requires-Dist: SciencePlots>=2.0.0; extra == "dev"
|
| 158 |
+
Requires-Dist: pytorch-msssim==1.0.0; extra == "dev"
|
| 159 |
+
Requires-Dist: sewar>=0.4.4; extra == "dev"
|
| 160 |
+
Requires-Dist: setuptools<82.0.0; extra == "dev"
|
| 161 |
+
Requires-Dist: scikit-image>=0.19.0; extra == "dev"
|
| 162 |
+
Requires-Dist: dists-pytorch==0.1; extra == "dev"
|
| 163 |
+
Requires-Dist: rouge-score>0.1.0; extra == "dev"
|
| 164 |
+
Requires-Dist: netcal>1.0.0; extra == "dev"
|
| 165 |
+
Requires-Dist: pandas>1.4.0; extra == "dev"
|
| 166 |
+
Requires-Dist: numpy<2.4.0; extra == "dev"
|
| 167 |
+
Requires-Dist: torch_complex<0.5.0; extra == "dev"
|
| 168 |
+
Requires-Dist: permetrics==2.0.0; extra == "dev"
|
| 169 |
+
Requires-Dist: jiwer>=2.3.0; extra == "dev"
|
| 170 |
+
Requires-Dist: aeon>=1.0.0; python_version > "3.10" and extra == "dev"
|
| 171 |
+
Requires-Dist: mir-eval>=0.6; extra == "dev"
|
| 172 |
+
Requires-Dist: huggingface-hub<0.35; extra == "dev"
|
| 173 |
+
Requires-Dist: faster-coco-eval>=1.6.3; extra == "dev"
|
| 174 |
+
Requires-Dist: mecab-ko-dic>=1.0.0; python_version < "3.12" and extra == "dev"
|
| 175 |
+
Requires-Dist: monai==1.4.0; extra == "dev"
|
| 176 |
+
Requires-Dist: mecab-ko<1.1.0,>=1.0.0; python_version < "3.12" and extra == "dev"
|
| 177 |
+
Requires-Dist: bert_score==0.3.13; extra == "dev"
|
| 178 |
+
Requires-Dist: sacrebleu>=2.3.0; extra == "dev"
|
| 179 |
+
Requires-Dist: scipy>1.0.0; extra == "dev"
|
| 180 |
+
Requires-Dist: lpips<=0.1.4; extra == "dev"
|
| 181 |
+
Requires-Dist: dython==0.7.9; extra == "dev"
|
| 182 |
+
Requires-Dist: properscoring==0.1; extra == "dev"
|
| 183 |
+
Requires-Dist: fast-bss-eval>=0.1.0; extra == "dev"
|
| 184 |
+
Requires-Dist: PyTDC==0.4.1; (platform_system == "Windows" and python_version < "3.12") and extra == "dev"
|
| 185 |
+
Requires-Dist: fairlearn; extra == "dev"
|
| 186 |
+
Requires-Dist: kornia>=0.6.7; extra == "dev"
|
| 187 |
+
Requires-Dist: statsmodels>0.13.5; extra == "dev"
|
| 188 |
+
Dynamic: author
|
| 189 |
+
Dynamic: author-email
|
| 190 |
+
Dynamic: classifier
|
| 191 |
+
Dynamic: description
|
| 192 |
+
Dynamic: description-content-type
|
| 193 |
+
Dynamic: download-url
|
| 194 |
+
Dynamic: home-page
|
| 195 |
+
Dynamic: keywords
|
| 196 |
+
Dynamic: license
|
| 197 |
+
Dynamic: license-file
|
| 198 |
+
Dynamic: project-url
|
| 199 |
+
Dynamic: provides-extra
|
| 200 |
+
Dynamic: requires-dist
|
| 201 |
+
Dynamic: requires-python
|
| 202 |
+
Dynamic: summary
|
| 203 |
+
|
| 204 |
+
<div align="center">
|
| 205 |
+
|
| 206 |
+
<img src="https://github.com/Lightning-AI/torchmetrics/raw/v1.9.0/docs/source/_static/images/logo.png" width="400px">
|
| 207 |
+
|
| 208 |
+
**Machine learning metrics for distributed, scalable PyTorch applications.**
|
| 209 |
+
|
| 210 |
+
______________________________________________________________________
|
| 211 |
+
|
| 212 |
+
<p align="center">
|
| 213 |
+
<a href="#what-is-torchmetrics">What is Torchmetrics</a> •
|
| 214 |
+
<a href="#implementing-your-own-module-metric">Implementing a metric</a> •
|
| 215 |
+
<a href="#build-in-metrics">Built-in metrics</a> •
|
| 216 |
+
<a href="https://lightning.ai/docs/torchmetrics/stable/">Docs</a> •
|
| 217 |
+
<a href="#community">Community</a> •
|
| 218 |
+
<a href="#license">License</a>
|
| 219 |
+
</p>
|
| 220 |
+
|
| 221 |
+
______________________________________________________________________
|
| 222 |
+
|
| 223 |
+
[](https://pypi.org/project/torchmetrics/)
|
| 224 |
+
[](https://badge.fury.io/py/torchmetrics)
|
| 225 |
+
[
|
| 226 |
+
](https://pepy.tech/project/torchmetrics)
|
| 227 |
+
[](https://anaconda.org/conda-forge/torchmetrics)
|
| 228 |
+
[](https://github.com/Lightning-AI/torchmetrics/blob/master/LICENSE)
|
| 229 |
+
|
| 230 |
+
[](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml)
|
| 231 |
+
[](https://dev.azure.com/Lightning-AI/Metrics/_build/latest?definitionId=2&branchName=refs%2Ftags%2Fv1.9.0)
|
| 232 |
+
[](https://codecov.io/gh/Lightning-AI/torchmetrics)
|
| 233 |
+
[](https://results.pre-commit.ci/latest/github/Lightning-AI/torchmetrics/master)
|
| 234 |
+
|
| 235 |
+
[](https://torchmetrics.readthedocs.io/en/latest/?badge=latest)
|
| 236 |
+
[](https://discord.gg/VptPCZkGNa)
|
| 237 |
+
[](https://doi.org/10.5281/zenodo.5844769)
|
| 238 |
+
[](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43)
|
| 239 |
+
|
| 240 |
+
______________________________________________________________________
|
| 241 |
+
|
| 242 |
+
</div>
|
| 243 |
+
|
| 244 |
+
# Looking for GPUs?
|
| 245 |
+
|
| 246 |
+
Over 340,000 developers use [Lightning Cloud](https://lightning.ai/?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme) - purpose-built for PyTorch and PyTorch Lightning.
|
| 247 |
+
|
| 248 |
+
- [GPUs](https://lightning.ai/pricing?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme) from $0.19.
|
| 249 |
+
- [Clusters](https://lightning.ai/clusters?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): frontier-grade training/inference clusters.
|
| 250 |
+
- [AI Studio (vibe train)](https://lightning.ai/studios?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): workspaces where AI helps you debug, tune and vibe train.
|
| 251 |
+
- [AI Studio (vibe deploy)](https://lightning.ai/studios?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): workspaces where AI helps you optimize, and deploy models.
|
| 252 |
+
- [Notebooks](https://lightning.ai/notebooks?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): Persistent GPU workspaces where AI helps you code and analyze.
|
| 253 |
+
- [Inference](https://lightning.ai/deploy?utm_source=tm_readme&utm_medium=referral&utm_campaign=tm_readme): Deploy models as inference APIs.
|
| 254 |
+
|
| 255 |
+
# Installation
|
| 256 |
+
|
| 257 |
+
Simple installation from PyPI
|
| 258 |
+
|
| 259 |
+
```bash
|
| 260 |
+
pip install torchmetrics
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
<details>
|
| 264 |
+
<summary>Other installations</summary>
|
| 265 |
+
|
| 266 |
+
Install using conda
|
| 267 |
+
|
| 268 |
+
```bash
|
| 269 |
+
conda install -c conda-forge torchmetrics
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
Install using uv
|
| 273 |
+
|
| 274 |
+
```bash
|
| 275 |
+
uv add torchmetrics
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
Pip from source
|
| 279 |
+
|
| 280 |
+
```bash
|
| 281 |
+
# with git
|
| 282 |
+
pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stable
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
Pip from archive
|
| 286 |
+
|
| 287 |
+
```bash
|
| 288 |
+
pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zip
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
Extra dependencies for specialized metrics:
|
| 292 |
+
|
| 293 |
+
```bash
|
| 294 |
+
pip install torchmetrics[audio]
|
| 295 |
+
pip install torchmetrics[image]
|
| 296 |
+
pip install torchmetrics[text]
|
| 297 |
+
pip install torchmetrics[all] # install all of the above
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
Install latest developer version
|
| 301 |
+
|
| 302 |
+
```bash
|
| 303 |
+
pip install https://github.com/Lightning-AI/torchmetrics/archive/master.zip
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
</details>
|
| 307 |
+
|
| 308 |
+
______________________________________________________________________
|
| 309 |
+
|
| 310 |
+
# What is TorchMetrics
|
| 311 |
+
|
| 312 |
+
TorchMetrics is a collection of 100+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers:
|
| 313 |
+
|
| 314 |
+
- A standardized interface to increase reproducibility
|
| 315 |
+
- Reduces boilerplate
|
| 316 |
+
- Automatic accumulation over batches
|
| 317 |
+
- Metrics optimized for distributed-training
|
| 318 |
+
- Automatic synchronization between multiple devices
|
| 319 |
+
|
| 320 |
+
You can use TorchMetrics with any PyTorch model or with [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) to enjoy additional features such as:
|
| 321 |
+
|
| 322 |
+
- Module metrics are automatically placed on the correct device.
|
| 323 |
+
- Native support for logging metrics in Lightning to reduce even more boilerplate.
|
| 324 |
+
|
| 325 |
+
# Using TorchMetrics
|
| 326 |
+
|
| 327 |
+
### Module metrics
|
| 328 |
+
|
| 329 |
+
The [module-based metrics](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) contain internal metric states (similar to the parameters of the PyTorch module) that automate accumulation and synchronization across devices!
|
| 330 |
+
|
| 331 |
+
- Automatic accumulation over multiple batches
|
| 332 |
+
- Automatic synchronization between multiple devices
|
| 333 |
+
- Metric arithmetic
|
| 334 |
+
|
| 335 |
+
**This can be run on CPU, single GPU or multi-GPUs!**
|
| 336 |
+
|
| 337 |
+
For the single GPU/CPU case:
|
| 338 |
+
|
| 339 |
+
```python
|
| 340 |
+
import torch
|
| 341 |
+
|
| 342 |
+
# import our library
|
| 343 |
+
import torchmetrics
|
| 344 |
+
|
| 345 |
+
# initialize metric
|
| 346 |
+
metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5)
|
| 347 |
+
|
| 348 |
+
# move the metric to device you want computations to take place
|
| 349 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 350 |
+
metric.to(device)
|
| 351 |
+
|
| 352 |
+
n_batches = 10
|
| 353 |
+
for i in range(n_batches):
|
| 354 |
+
# simulate a classification problem
|
| 355 |
+
preds = torch.randn(10, 5).softmax(dim=-1).to(device)
|
| 356 |
+
target = torch.randint(5, (10,)).to(device)
|
| 357 |
+
|
| 358 |
+
# metric on current batch
|
| 359 |
+
acc = metric(preds, target)
|
| 360 |
+
print(f"Accuracy on batch {i}: {acc}")
|
| 361 |
+
|
| 362 |
+
# metric on all batches using custom accumulation
|
| 363 |
+
acc = metric.compute()
|
| 364 |
+
print(f"Accuracy on all data: {acc}")
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
Module metric usage remains the same when using multiple GPUs or multiple nodes.
|
| 368 |
+
|
| 369 |
+
<details>
|
| 370 |
+
<summary>Example using DDP</summary>
|
| 371 |
+
|
| 372 |
+
<!--phmdoctest-mark.skip-->
|
| 373 |
+
|
| 374 |
+
```python
|
| 375 |
+
import os
|
| 376 |
+
import torch
|
| 377 |
+
import torch.distributed as dist
|
| 378 |
+
import torch.multiprocessing as mp
|
| 379 |
+
from torch import nn
|
| 380 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 381 |
+
import torchmetrics
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def metric_ddp(rank, world_size):
|
| 385 |
+
os.environ["MASTER_ADDR"] = "localhost"
|
| 386 |
+
os.environ["MASTER_PORT"] = "12355"
|
| 387 |
+
|
| 388 |
+
# create default process group
|
| 389 |
+
dist.init_process_group("gloo", rank=rank, world_size=world_size)
|
| 390 |
+
|
| 391 |
+
# initialize model
|
| 392 |
+
metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5)
|
| 393 |
+
|
| 394 |
+
# define a model and append your metric to it
|
| 395 |
+
# this allows metric states to be placed on correct accelerators when
|
| 396 |
+
# .to(device) is called on the model
|
| 397 |
+
model = nn.Linear(10, 10)
|
| 398 |
+
model.metric = metric
|
| 399 |
+
model = model.to(rank)
|
| 400 |
+
|
| 401 |
+
# initialize DDP
|
| 402 |
+
model = DDP(model, device_ids=[rank])
|
| 403 |
+
|
| 404 |
+
n_epochs = 5
|
| 405 |
+
# this shows iteration over multiple training epochs
|
| 406 |
+
for n in range(n_epochs):
|
| 407 |
+
# this will be replaced by a DataLoader with a DistributedSampler
|
| 408 |
+
n_batches = 10
|
| 409 |
+
for i in range(n_batches):
|
| 410 |
+
# simulate a classification problem
|
| 411 |
+
preds = torch.randn(10, 5).softmax(dim=-1)
|
| 412 |
+
target = torch.randint(5, (10,))
|
| 413 |
+
|
| 414 |
+
# metric on current batch
|
| 415 |
+
acc = metric(preds, target)
|
| 416 |
+
if rank == 0: # print only for rank 0
|
| 417 |
+
print(f"Accuracy on batch {i}: {acc}")
|
| 418 |
+
|
| 419 |
+
# metric on all batches and all accelerators using custom accumulation
|
| 420 |
+
# accuracy is same across both accelerators
|
| 421 |
+
acc = metric.compute()
|
| 422 |
+
print(f"Accuracy on all data: {acc}, accelerator rank: {rank}")
|
| 423 |
+
|
| 424 |
+
# Resetting internal state such that metric ready for new data
|
| 425 |
+
metric.reset()
|
| 426 |
+
|
| 427 |
+
# cleanup
|
| 428 |
+
dist.destroy_process_group()
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
if __name__ == "__main__":
|
| 432 |
+
world_size = 2 # number of gpus to parallelize over
|
| 433 |
+
mp.spawn(metric_ddp, args=(world_size,), nprocs=world_size, join=True)
|
| 434 |
+
```
|
| 435 |
+
|
| 436 |
+
</details>
|
| 437 |
+
|
| 438 |
+
### Implementing your own Module metric
|
| 439 |
+
|
| 440 |
+
Implementing your own metric is as easy as subclassing an [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). Simply, subclass `torchmetrics.Metric`
|
| 441 |
+
and just implement the `update` and `compute` methods:
|
| 442 |
+
|
| 443 |
+
```python
|
| 444 |
+
import torch
|
| 445 |
+
from torchmetrics import Metric
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class MyAccuracy(Metric):
|
| 449 |
+
def __init__(self):
|
| 450 |
+
# remember to call super
|
| 451 |
+
super().__init__()
|
| 452 |
+
# call `self.add_state`for every internal state that is needed for the metrics computations
|
| 453 |
+
# dist_reduce_fx indicates the function that should be used to reduce
|
| 454 |
+
# state from multiple processes
|
| 455 |
+
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
|
| 456 |
+
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
|
| 457 |
+
|
| 458 |
+
def update(self, preds: torch.Tensor, target: torch.Tensor) -> None:
|
| 459 |
+
# extract predicted class index for computing accuracy
|
| 460 |
+
preds = preds.argmax(dim=-1)
|
| 461 |
+
assert preds.shape == target.shape
|
| 462 |
+
# update metric states
|
| 463 |
+
self.correct += torch.sum(preds == target)
|
| 464 |
+
self.total += target.numel()
|
| 465 |
+
|
| 466 |
+
def compute(self) -> torch.Tensor:
|
| 467 |
+
# compute final result
|
| 468 |
+
return self.correct.float() / self.total
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
my_metric = MyAccuracy()
|
| 472 |
+
preds = torch.randn(10, 5).softmax(dim=-1)
|
| 473 |
+
target = torch.randint(5, (10,))
|
| 474 |
+
|
| 475 |
+
print(my_metric(preds, target))
|
| 476 |
+
```
|
| 477 |
+
|
| 478 |
+
### Functional metrics
|
| 479 |
+
|
| 480 |
+
Similar to [`torch.nn`](https://pytorch.org/docs/stable/nn.html), most metrics have both a [module-based](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) and functional version.
|
| 481 |
+
The functional versions are simple python functions that as input take [torch.tensors](https://pytorch.org/docs/stable/tensors.html) and return the corresponding metric as a [torch.tensor](https://pytorch.org/docs/stable/tensors.html).
|
| 482 |
+
|
| 483 |
+
```python
|
| 484 |
+
import torch
|
| 485 |
+
|
| 486 |
+
# import our library
|
| 487 |
+
import torchmetrics
|
| 488 |
+
|
| 489 |
+
# simulate a classification problem
|
| 490 |
+
preds = torch.randn(10, 5).softmax(dim=-1)
|
| 491 |
+
target = torch.randint(5, (10,))
|
| 492 |
+
|
| 493 |
+
acc = torchmetrics.functional.classification.multiclass_accuracy(
|
| 494 |
+
preds, target, num_classes=5
|
| 495 |
+
)
|
| 496 |
+
```
|
| 497 |
+
|
| 498 |
+
### Covered domains and example metrics
|
| 499 |
+
|
| 500 |
+
In total TorchMetrics contains [100+ metrics](https://lightning.ai/docs/torchmetrics/stable/all-metrics.html), which
|
| 501 |
+
covers the following domains:
|
| 502 |
+
|
| 503 |
+
- Audio
|
| 504 |
+
- Classification
|
| 505 |
+
- Detection
|
| 506 |
+
- Information Retrieval
|
| 507 |
+
- Image
|
| 508 |
+
- Multimodal (Image-Text-3D Talking Heads)
|
| 509 |
+
- Nominal
|
| 510 |
+
- Regression
|
| 511 |
+
- Segmentation
|
| 512 |
+
- Text
|
| 513 |
+
|
| 514 |
+
Each domain may require some additional dependencies which can be installed with `pip install torchmetrics[audio]`,
|
| 515 |
+
`pip install torchmetrics['image']` etc.
|
| 516 |
+
|
| 517 |
+
### Additional features
|
| 518 |
+
|
| 519 |
+
#### Plotting
|
| 520 |
+
|
| 521 |
+
Visualization of metrics can be important to help understand what is going on with your machine learning algorithms.
|
| 522 |
+
Torchmetrics have built-in plotting support (install dependencies with `pip install torchmetrics[visual]`) for nearly
|
| 523 |
+
all modular metrics through the `.plot` method. Simply call the method to get a simple visualization of any metric!
|
| 524 |
+
|
| 525 |
+
```python
|
| 526 |
+
import torch
|
| 527 |
+
from torchmetrics.classification import MulticlassAccuracy, MulticlassConfusionMatrix
|
| 528 |
+
|
| 529 |
+
num_classes = 3
|
| 530 |
+
|
| 531 |
+
# this will generate two distributions that comes more similar as iterations increase
|
| 532 |
+
w = torch.randn(num_classes)
|
| 533 |
+
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
|
| 534 |
+
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
|
| 535 |
+
|
| 536 |
+
acc = MulticlassAccuracy(num_classes=num_classes, average="micro")
|
| 537 |
+
acc_per_class = MulticlassAccuracy(num_classes=num_classes, average=None)
|
| 538 |
+
confmat = MulticlassConfusionMatrix(num_classes=num_classes)
|
| 539 |
+
|
| 540 |
+
# plot single value
|
| 541 |
+
for i in range(5):
|
| 542 |
+
acc_per_class.update(preds(i), target(i))
|
| 543 |
+
confmat.update(preds(i), target(i))
|
| 544 |
+
fig1, ax1 = acc_per_class.plot()
|
| 545 |
+
fig2, ax2 = confmat.plot()
|
| 546 |
+
|
| 547 |
+
# plot multiple values
|
| 548 |
+
values = []
|
| 549 |
+
for i in range(10):
|
| 550 |
+
values.append(acc(preds(i), target(i)))
|
| 551 |
+
fig3, ax3 = acc.plot(values)
|
| 552 |
+
```
|
| 553 |
+
|
| 554 |
+
<p align="center">
|
| 555 |
+
<img src="https://github.com/Lightning-AI/torchmetrics/raw/v1.9.0/docs/source/_static/images/plot_example.png" width="1000">
|
| 556 |
+
</p>
|
| 557 |
+
|
| 558 |
+
For examples of plotting different metrics try running [this example file](_samples/plotting.py).
|
| 559 |
+
|
| 560 |
+
# Contribute!
|
| 561 |
+
|
| 562 |
+
The lightning + TorchMetrics team is hard at work adding even more metrics.
|
| 563 |
+
But we're looking for incredible contributors like you to submit new metrics
|
| 564 |
+
and improve existing ones!
|
| 565 |
+
|
| 566 |
+
Join our [Discord](https://discord.com/invite/tfXFetEZxv) to get help with becoming a contributor!
|
| 567 |
+
|
| 568 |
+
# Community
|
| 569 |
+
|
| 570 |
+
For help or questions, join our huge community on [Discord](https://discord.com/invite/tfXFetEZxv)!
|
| 571 |
+
|
| 572 |
+
# Citation
|
| 573 |
+
|
| 574 |
+
We’re excited to continue the strong legacy of open source software and have been inspired
|
| 575 |
+
over the years by Caffe, Theano, Keras, PyTorch, torchbearer, ignite, sklearn and fast.ai.
|
| 576 |
+
|
| 577 |
+
If you want to cite this framework feel free to use GitHub's built-in citation option to generate a bibtex or APA-Style citation based on [this file](https://github.com/Lightning-AI/torchmetrics/blob/master/CITATION.cff) (but only if you loved it 😊).
|
| 578 |
+
|
| 579 |
+
# License
|
| 580 |
+
|
| 581 |
+
Please observe the Apache 2.0 license that is listed in this repository.
|
| 582 |
+
In addition, the Lightning framework is Patent Pending.
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torchmetrics-1.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
torchmetrics-1.9.0.dist-info/METADATA,sha256=6aaxD25cq-5RUK_DDtcP3RTlVrG4VpeaM0HSy6Ibqt0,23134
|
| 3 |
+
torchmetrics-1.9.0.dist-info/RECORD,,
|
| 4 |
+
torchmetrics-1.9.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
| 5 |
+
torchmetrics-1.9.0.dist-info/licenses/LICENSE,sha256=-jH0M_W0vB-3MPucZ4-QGC2Tv3a22Yuk0A9ARUrIuDI,11352
|
| 6 |
+
torchmetrics-1.9.0.dist-info/top_level.txt,sha256=wUt7Alce9yBXuCXPU2Mcfh3_6ZjoYejoj2silrPGA_Q,13
|
| 7 |
+
torchmetrics/__about__.py,sha256=D5zucYwCJrFMOc_8wbvI8p-r8XRT-j6kVaOvw_dNfnU,1239
|
| 8 |
+
torchmetrics/__init__.py,sha256=NinAv0FcLhc4rO-8cH_FXB-0cEqvI38uZL0v6sYk6Ls,9490
|
| 9 |
+
torchmetrics/__pycache__/__about__.cpython-310.pyc,,
|
| 10 |
+
torchmetrics/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
torchmetrics/__pycache__/aggregation.cpython-310.pyc,,
|
| 12 |
+
torchmetrics/__pycache__/collections.cpython-310.pyc,,
|
| 13 |
+
torchmetrics/__pycache__/metric.cpython-310.pyc,,
|
| 14 |
+
torchmetrics/aggregation.py,sha256=0b56QtlPggVi4YC0oPeLlYvFOD1Q7IWKhRtKIBLRqII,28384
|
| 15 |
+
torchmetrics/audio/__init__.py,sha256=yRvq2xMGIOveZSWYGqhRF01oLpvWej_iyc4vn6UQqew,2536
|
| 16 |
+
torchmetrics/audio/__pycache__/__init__.cpython-310.pyc,,
|
| 17 |
+
torchmetrics/audio/__pycache__/_deprecated.cpython-310.pyc,,
|
| 18 |
+
torchmetrics/audio/__pycache__/dnsmos.cpython-310.pyc,,
|
| 19 |
+
torchmetrics/audio/__pycache__/nisqa.cpython-310.pyc,,
|
| 20 |
+
torchmetrics/audio/__pycache__/pesq.cpython-310.pyc,,
|
| 21 |
+
torchmetrics/audio/__pycache__/pit.cpython-310.pyc,,
|
| 22 |
+
torchmetrics/audio/__pycache__/sdr.cpython-310.pyc,,
|
| 23 |
+
torchmetrics/audio/__pycache__/snr.cpython-310.pyc,,
|
| 24 |
+
torchmetrics/audio/__pycache__/srmr.cpython-310.pyc,,
|
| 25 |
+
torchmetrics/audio/__pycache__/stoi.cpython-310.pyc,,
|
| 26 |
+
torchmetrics/audio/_deprecated.py,sha256=-_Q_my6O20Itu7ISoyKqZz3NmN6xMk4uTH8s48BV4Ag,4065
|
| 27 |
+
torchmetrics/audio/dnsmos.py,sha256=DVBuN07qox7KNNDCZ3my0PjL2hZtkIYfqux5prjZgI4,8057
|
| 28 |
+
torchmetrics/audio/nisqa.py,sha256=_m9EeZQfEd0MNwlwZACOOQAuSScpgoERrtieFuyzAdk,6027
|
| 29 |
+
torchmetrics/audio/pesq.py,sha256=l5Y0ClQhqnWiKkmBD0W9fwt80qE6QsO62USvZhPn1is,7348
|
| 30 |
+
torchmetrics/audio/pit.py,sha256=TxGn-jDkK3yVavjnRTxCKMWVovQzoijiZKNSkIfQpbo,6914
|
| 31 |
+
torchmetrics/audio/sdr.py,sha256=aQzlxGiONWBfNWxzAgLLmkrL9vjDh--2an2-SdETbYg,15295
|
| 32 |
+
torchmetrics/audio/snr.py,sha256=FJQKwuHUoB8Q--mlrDKL3sH6kdpZTlkupP60UpQsvQU,12701
|
| 33 |
+
torchmetrics/audio/srmr.py,sha256=HxYPY1sh8b26iZw5jc1BnHwa_LRD5el58Ogec0HjY9U,7378
|
| 34 |
+
torchmetrics/audio/stoi.py,sha256=ZtaXNTieNiDuhfntrPP_1Mu1TxEBr9hAxC0vz1RyJ34,6428
|
| 35 |
+
torchmetrics/classification/__init__.py,sha256=DWUA3NXdeh20ZyFuLGQ6QKcoGM1aZfT6XKPqwhhkW9Q,7467
|
| 36 |
+
torchmetrics/classification/__pycache__/__init__.cpython-310.pyc,,
|
| 37 |
+
torchmetrics/classification/__pycache__/accuracy.cpython-310.pyc,,
|
| 38 |
+
torchmetrics/classification/__pycache__/auroc.cpython-310.pyc,,
|
| 39 |
+
torchmetrics/classification/__pycache__/average_precision.cpython-310.pyc,,
|
| 40 |
+
torchmetrics/classification/__pycache__/base.cpython-310.pyc,,
|
| 41 |
+
torchmetrics/classification/__pycache__/calibration_error.cpython-310.pyc,,
|
| 42 |
+
torchmetrics/classification/__pycache__/cohen_kappa.cpython-310.pyc,,
|
| 43 |
+
torchmetrics/classification/__pycache__/confusion_matrix.cpython-310.pyc,,
|
| 44 |
+
torchmetrics/classification/__pycache__/eer.cpython-310.pyc,,
|
| 45 |
+
torchmetrics/classification/__pycache__/exact_match.cpython-310.pyc,,
|
| 46 |
+
torchmetrics/classification/__pycache__/f_beta.cpython-310.pyc,,
|
| 47 |
+
torchmetrics/classification/__pycache__/group_fairness.cpython-310.pyc,,
|
| 48 |
+
torchmetrics/classification/__pycache__/hamming.cpython-310.pyc,,
|
| 49 |
+
torchmetrics/classification/__pycache__/hinge.cpython-310.pyc,,
|
| 50 |
+
torchmetrics/classification/__pycache__/jaccard.cpython-310.pyc,,
|
| 51 |
+
torchmetrics/classification/__pycache__/logauc.cpython-310.pyc,,
|
| 52 |
+
torchmetrics/classification/__pycache__/matthews_corrcoef.cpython-310.pyc,,
|
| 53 |
+
torchmetrics/classification/__pycache__/negative_predictive_value.cpython-310.pyc,,
|
| 54 |
+
torchmetrics/classification/__pycache__/precision_fixed_recall.cpython-310.pyc,,
|
| 55 |
+
torchmetrics/classification/__pycache__/precision_recall.cpython-310.pyc,,
|
| 56 |
+
torchmetrics/classification/__pycache__/precision_recall_curve.cpython-310.pyc,,
|
| 57 |
+
torchmetrics/classification/__pycache__/ranking.cpython-310.pyc,,
|
| 58 |
+
torchmetrics/classification/__pycache__/recall_fixed_precision.cpython-310.pyc,,
|
| 59 |
+
torchmetrics/classification/__pycache__/roc.cpython-310.pyc,,
|
| 60 |
+
torchmetrics/classification/__pycache__/sensitivity_specificity.cpython-310.pyc,,
|
| 61 |
+
torchmetrics/classification/__pycache__/specificity.cpython-310.pyc,,
|
| 62 |
+
torchmetrics/classification/__pycache__/specificity_sensitivity.cpython-310.pyc,,
|
| 63 |
+
torchmetrics/classification/__pycache__/stat_scores.cpython-310.pyc,,
|
| 64 |
+
torchmetrics/classification/accuracy.py,sha256=li5d2sLrZMU11EOJxwbf0k5CVf4EbzykR1qhEOqK44Q,23408
|
| 65 |
+
torchmetrics/classification/auroc.py,sha256=SAb3TdBVCWpoZ2ki2ftiL2rqK5S08Fntej2Tc1lTrG0,25595
|
| 66 |
+
torchmetrics/classification/average_precision.py,sha256=OxolA2NDz6K3C_LuL5_cexeVvOU_5pYJgBhpqYF3dQ0,25457
|
| 67 |
+
torchmetrics/classification/base.py,sha256=V5wu8vUqgJ23upaI4alsL7019gkL9H3k4A1-oXG4FXY,1234
|
| 68 |
+
torchmetrics/classification/calibration_error.py,sha256=ZJgJcbtCMPgE2jgwrV6Kl-vlyG78JJfTMa49rhO9tLE,17288
|
| 69 |
+
torchmetrics/classification/cohen_kappa.py,sha256=UVTRv8x9_s4-Ixnxl7qf8yWzRZGKyK5JctcHTz5LuT0,13717
|
| 70 |
+
torchmetrics/classification/confusion_matrix.py,sha256=ulifUwFRmr45Gw-K-grd_nliQYUwKtJrx2Dt-e9oowg,23841
|
| 71 |
+
torchmetrics/classification/eer.py,sha256=c_BFrYkbdRu2cuJftio_r4NP2u4CR187vp1k4cWTG-A,21210
|
| 72 |
+
torchmetrics/classification/exact_match.py,sha256=i1WQDaRYUYzxaiBeJEAtcXSJVEPjr8rELrDtEcMhKI4,20293
|
| 73 |
+
torchmetrics/classification/f_beta.py,sha256=1YxmohjAAwMXybbf2p7tncdseJthu9XRbCrQMkWsjss,54228
|
| 74 |
+
torchmetrics/classification/group_fairness.py,sha256=gaTZRXdEdpFwwOpvbpSo4zr0nm-S1nd2CiYWZoZrs1I,13784
|
| 75 |
+
torchmetrics/classification/hamming.py,sha256=LNEJxKWB_jr4QCkACseoY42mnFlrYSNidHsMMuCCrpA,24081
|
| 76 |
+
torchmetrics/classification/hinge.py,sha256=djewxadp9uubjuXIX-zpuHgLmcettQUwHM3k9eG0UEo,15828
|
| 77 |
+
torchmetrics/classification/jaccard.py,sha256=KoQZwZ6plXFqtrdGl3gTpJNv19g2Wo471tMA1x3aexg,20552
|
| 78 |
+
torchmetrics/classification/logauc.py,sha256=syZ1mL2VEWanxVEGQx4bj5kCprZjFLzXLVRhpxFl8KY,23446
|
| 79 |
+
torchmetrics/classification/matthews_corrcoef.py,sha256=SucLKvwnTJIQCbBhV8lTrUWTowzxfNCz-QOrK-GVA1U,17086
|
| 80 |
+
torchmetrics/classification/negative_predictive_value.py,sha256=HA6enJuGNAtlFLnDug9pOUgjGXLGbuwcD4mq8VxNDSo,24587
|
| 81 |
+
torchmetrics/classification/precision_fixed_recall.py,sha256=pRTECzSJbsoDTHkPAY8YICc9wM2pw7RMmNEC0sw9kqo,25300
|
| 82 |
+
torchmetrics/classification/precision_recall.py,sha256=gbPlpSJTiV9v4pCeGoFnZ1Xaj1oJneGfiVGcDC1nMRs,48258
|
| 83 |
+
torchmetrics/classification/precision_recall_curve.py,sha256=uDIdQqBLI4TRPb0kd-rE2bTUDwqpzxKj7FgJVcMOtEE,35413
|
| 84 |
+
torchmetrics/classification/ranking.py,sha256=KHs7A1VZvDIZmZWMzpAW34yi9DStNTzU77iuOpo3cCo,18332
|
| 85 |
+
torchmetrics/classification/recall_fixed_precision.py,sha256=gahv-ypAqMrkUY60uAL1OSEtqQimWctLievklKJLJqY,25272
|
| 86 |
+
torchmetrics/classification/roc.py,sha256=tN3bZ56NdyhyyvVLki1fdMzAZRf1W3_dUwH1V8IgAB8,30543
|
| 87 |
+
torchmetrics/classification/sensitivity_specificity.py,sha256=ml2-satmeUB6uKpy_meXeaHHIIZAEnlJ8erR8S9i-AI,18702
|
| 88 |
+
torchmetrics/classification/specificity.py,sha256=KvZwwWhaL3h1ZR5lSnJ748ChLno-uq_kbT8x-M9vMtM,23645
|
| 89 |
+
torchmetrics/classification/specificity_sensitivity.py,sha256=qc59pDyFIXxPNMZIy_6ikOLmsCovyYDCxIkxR8mro8s,18811
|
| 90 |
+
torchmetrics/classification/stat_scores.py,sha256=MOVEwrA6kt0SaSMKrx9DOsg-6-0lL-25lu-aIhYY-2Q,26230
|
| 91 |
+
torchmetrics/clustering/__init__.py,sha256=7i2WpseBvmmLmBboB6CSCZiU_WebDOaM1KGUMLT0PEY,1794
|
| 92 |
+
torchmetrics/clustering/__pycache__/__init__.cpython-310.pyc,,
|
| 93 |
+
torchmetrics/clustering/__pycache__/adjusted_mutual_info_score.cpython-310.pyc,,
|
| 94 |
+
torchmetrics/clustering/__pycache__/adjusted_rand_score.cpython-310.pyc,,
|
| 95 |
+
torchmetrics/clustering/__pycache__/calinski_harabasz_score.cpython-310.pyc,,
|
| 96 |
+
torchmetrics/clustering/__pycache__/cluster_accuracy.cpython-310.pyc,,
|
| 97 |
+
torchmetrics/clustering/__pycache__/davies_bouldin_score.cpython-310.pyc,,
|
| 98 |
+
torchmetrics/clustering/__pycache__/dunn_index.cpython-310.pyc,,
|
| 99 |
+
torchmetrics/clustering/__pycache__/fowlkes_mallows_index.cpython-310.pyc,,
|
| 100 |
+
torchmetrics/clustering/__pycache__/homogeneity_completeness_v_measure.cpython-310.pyc,,
|
| 101 |
+
torchmetrics/clustering/__pycache__/mutual_info_score.cpython-310.pyc,,
|
| 102 |
+
torchmetrics/clustering/__pycache__/normalized_mutual_info_score.cpython-310.pyc,,
|
| 103 |
+
torchmetrics/clustering/__pycache__/rand_score.cpython-310.pyc,,
|
| 104 |
+
torchmetrics/clustering/adjusted_mutual_info_score.py,sha256=0vi2mjpjSrEFrfoxmZXX0Cf89BD_N7V60CdgZDc6yac,5389
|
| 105 |
+
torchmetrics/clustering/adjusted_rand_score.py,sha256=vtA9yYIaoeStHN6qgn2omjElVvvwK9GEGCRnOqoqHEs,5191
|
| 106 |
+
torchmetrics/clustering/calinski_harabasz_score.py,sha256=tu358N-itZQqrlTT0nA1t0Yu7LXiii9HJRCJ3rgghno,5357
|
| 107 |
+
torchmetrics/clustering/cluster_accuracy.py,sha256=D7_Qr8feZ7AD75lOESldMuC79e5SV8yDxpAVrV1x7p0,6034
|
| 108 |
+
torchmetrics/clustering/davies_bouldin_score.py,sha256=4-S5yAgbH4g2Q6id4SkB6BkaJok49DKg2kRp_k9SZJ4,5478
|
| 109 |
+
torchmetrics/clustering/dunn_index.py,sha256=dfGpxsESjwFErInYSac345XE_aWj9rzfhehZq6xpFcI,5014
|
| 110 |
+
torchmetrics/clustering/fowlkes_mallows_index.py,sha256=Yl5qiFxoH3_Nf5XjGipRLKeUR81NCZk1oQifc2Ppyhw,4619
|
| 111 |
+
torchmetrics/clustering/homogeneity_completeness_v_measure.py,sha256=j2JlfxjUPdVvy01lELlyvwZ0ri4OqyoXw4yN15S_J08,12969
|
| 112 |
+
torchmetrics/clustering/mutual_info_score.py,sha256=VyZqKcF4qMGZwLPX-_UmGW0ZFE8OpLj9wJU520aaoVw,5044
|
| 113 |
+
torchmetrics/clustering/normalized_mutual_info_score.py,sha256=Xt0NuydOkm0dZ6wGnm-oHxU8tjTe16Opsuf9tnThNJE,5282
|
| 114 |
+
torchmetrics/clustering/rand_score.py,sha256=kFZzSBMXtSex74q4XFNwdFFNRrfp5hbuV4GEqSjKdhY,4886
|
| 115 |
+
torchmetrics/collections.py,sha256=swVhMCOmaRfV55Y56SrZw1ENzMBD6lQXYW_EhhLz24g,33319
|
| 116 |
+
torchmetrics/detection/__init__.py,sha256=52oQOnyWr0b4Pa5do22VYW2kcdK1wxc1ct-LqnCHLC0,1398
|
| 117 |
+
torchmetrics/detection/__pycache__/__init__.cpython-310.pyc,,
|
| 118 |
+
torchmetrics/detection/__pycache__/_deprecated.cpython-310.pyc,,
|
| 119 |
+
torchmetrics/detection/__pycache__/_mean_ap.cpython-310.pyc,,
|
| 120 |
+
torchmetrics/detection/__pycache__/ciou.cpython-310.pyc,,
|
| 121 |
+
torchmetrics/detection/__pycache__/diou.cpython-310.pyc,,
|
| 122 |
+
torchmetrics/detection/__pycache__/giou.cpython-310.pyc,,
|
| 123 |
+
torchmetrics/detection/__pycache__/helpers.cpython-310.pyc,,
|
| 124 |
+
torchmetrics/detection/__pycache__/iou.cpython-310.pyc,,
|
| 125 |
+
torchmetrics/detection/__pycache__/mean_ap.cpython-310.pyc,,
|
| 126 |
+
torchmetrics/detection/__pycache__/panoptic_qualities.cpython-310.pyc,,
|
| 127 |
+
torchmetrics/detection/_deprecated.py,sha256=SSLnxdFWx8BAFTd5Rd8salDvHP0TUCwjQxV2vEpu14g,2359
|
| 128 |
+
torchmetrics/detection/_mean_ap.py,sha256=FH-1pw2HFUIqYpM6fJn5i8YRHABxJpPhO7nEMSg5-4Q,43130
|
| 129 |
+
torchmetrics/detection/ciou.py,sha256=S0D_1Nh8-IvI5jpeI71I7TdZttAFwDRo03wJaaYxKp4,8176
|
| 130 |
+
torchmetrics/detection/diou.py,sha256=PjjWFXu8Vfxpf4NYVVOo5fAUBFHuQo1RiN0cFVk3z48,8133
|
| 131 |
+
torchmetrics/detection/giou.py,sha256=_0SaXFbtLcQUZAfzakl8AIZAR3uDeC2EO_PC41m97eA,7899
|
| 132 |
+
torchmetrics/detection/helpers.py,sha256=Q6UpNZ00BC2RMRsTYV-NOj7X6HQFDdOXTfq8kmdHC3s,36145
|
| 133 |
+
torchmetrics/detection/iou.py,sha256=swTsOn1r768KYd6lpEhsRinBBDmHlmopBuNfYtg3nPU,13195
|
| 134 |
+
torchmetrics/detection/mean_ap.py,sha256=tDxJHsFaCf2uihU8QOPL7yIZcDbbg8ujMKCuWFhVBbk,33109
|
| 135 |
+
torchmetrics/detection/panoptic_qualities.py,sha256=gVOdRYu9wcrmj-NCfSJbbQOfsR-vMpNzmKa075Qmkbg,22057
|
| 136 |
+
torchmetrics/functional/__init__.py,sha256=8_bsjdxoMayi-o2VvkSrHc34-lHyrlDKpForqSsS4SM,9825
|
| 137 |
+
torchmetrics/functional/__pycache__/__init__.cpython-310.pyc,,
|
| 138 |
+
torchmetrics/functional/audio/__init__.py,sha256=Wm3T4Yg21V1PQz8K_oviNepH26pLxipN_dcoXDwp_1w,2744
|
| 139 |
+
torchmetrics/functional/audio/__pycache__/__init__.cpython-310.pyc,,
|
| 140 |
+
torchmetrics/functional/audio/__pycache__/_deprecated.cpython-310.pyc,,
|
| 141 |
+
torchmetrics/functional/audio/__pycache__/dnsmos.cpython-310.pyc,,
|
| 142 |
+
torchmetrics/functional/audio/__pycache__/nisqa.cpython-310.pyc,,
|
| 143 |
+
torchmetrics/functional/audio/__pycache__/pesq.cpython-310.pyc,,
|
| 144 |
+
torchmetrics/functional/audio/__pycache__/pit.cpython-310.pyc,,
|
| 145 |
+
torchmetrics/functional/audio/__pycache__/sdr.cpython-310.pyc,,
|
| 146 |
+
torchmetrics/functional/audio/__pycache__/snr.cpython-310.pyc,,
|
| 147 |
+
torchmetrics/functional/audio/__pycache__/srmr.cpython-310.pyc,,
|
| 148 |
+
torchmetrics/functional/audio/__pycache__/stoi.cpython-310.pyc,,
|
| 149 |
+
torchmetrics/functional/audio/_deprecated.py,sha256=Nsfcx04pVCRoFOHP7QSGOYiNNpEBrNViYr9k0uBxdzY,4431
|
| 150 |
+
torchmetrics/functional/audio/dnsmos.py,sha256=h4zYSzUd7i0YDYRsaOG2BuUk8wiwvm4FG0C4mTQVOyY,11843
|
| 151 |
+
torchmetrics/functional/audio/nisqa.py,sha256=XH6yDuY06sHESP3tSKZrr5CLx2qedO8uOGHe7bxkP9E,16465
|
| 152 |
+
torchmetrics/functional/audio/pesq.py,sha256=Da09vsLFJngu4hGibzHLF2Jnpfu-FnlMf8BDLfbBH18,5029
|
| 153 |
+
torchmetrics/functional/audio/pit.py,sha256=Ju7x4uL4PTJE0tdKQFaSqrPMxQnfBxAokaPDxRbwO3I,9834
|
| 154 |
+
torchmetrics/functional/audio/sdr.py,sha256=PC5NwI7Py-CmrirHCebelerStEhRRfJ_43fJXiLBEk8,11910
|
| 155 |
+
torchmetrics/functional/audio/snr.py,sha256=jrr7-_oSTXw_qHUgGUTaaQ063OJDw2UpGuaxVFP9LOg,5002
|
| 156 |
+
torchmetrics/functional/audio/srmr.py,sha256=ktp7whxQrKm3kU6XP9yvdvn0x1d5jjaYfLdt7azPTsA,14170
|
| 157 |
+
torchmetrics/functional/audio/stoi.py,sha256=g6rfViTkjy9zA-_Iit6VMTYDRPO3kVg-OekrVtESzRA,4217
|
| 158 |
+
torchmetrics/functional/classification/__init__.py,sha256=fywVnR_Hdh9zW7DHuqMx2COZqPjN2UaKSqAqM-VZKgk,8295
|
| 159 |
+
torchmetrics/functional/classification/__pycache__/__init__.cpython-310.pyc,,
|
| 160 |
+
torchmetrics/functional/classification/__pycache__/accuracy.cpython-310.pyc,,
|
| 161 |
+
torchmetrics/functional/classification/__pycache__/auroc.cpython-310.pyc,,
|
| 162 |
+
torchmetrics/functional/classification/__pycache__/average_precision.cpython-310.pyc,,
|
| 163 |
+
torchmetrics/functional/classification/__pycache__/calibration_error.cpython-310.pyc,,
|
| 164 |
+
torchmetrics/functional/classification/__pycache__/cohen_kappa.cpython-310.pyc,,
|
| 165 |
+
torchmetrics/functional/classification/__pycache__/confusion_matrix.cpython-310.pyc,,
|
| 166 |
+
torchmetrics/functional/classification/__pycache__/eer.cpython-310.pyc,,
|
| 167 |
+
torchmetrics/functional/classification/__pycache__/exact_match.cpython-310.pyc,,
|
| 168 |
+
torchmetrics/functional/classification/__pycache__/f_beta.cpython-310.pyc,,
|
| 169 |
+
torchmetrics/functional/classification/__pycache__/group_fairness.cpython-310.pyc,,
|
| 170 |
+
torchmetrics/functional/classification/__pycache__/hamming.cpython-310.pyc,,
|
| 171 |
+
torchmetrics/functional/classification/__pycache__/hinge.cpython-310.pyc,,
|
| 172 |
+
torchmetrics/functional/classification/__pycache__/jaccard.cpython-310.pyc,,
|
| 173 |
+
torchmetrics/functional/classification/__pycache__/logauc.cpython-310.pyc,,
|
| 174 |
+
torchmetrics/functional/classification/__pycache__/matthews_corrcoef.cpython-310.pyc,,
|
| 175 |
+
torchmetrics/functional/classification/__pycache__/negative_predictive_value.cpython-310.pyc,,
|
| 176 |
+
torchmetrics/functional/classification/__pycache__/precision_fixed_recall.cpython-310.pyc,,
|
| 177 |
+
torchmetrics/functional/classification/__pycache__/precision_recall.cpython-310.pyc,,
|
| 178 |
+
torchmetrics/functional/classification/__pycache__/precision_recall_curve.cpython-310.pyc,,
|
| 179 |
+
torchmetrics/functional/classification/__pycache__/ranking.cpython-310.pyc,,
|
| 180 |
+
torchmetrics/functional/classification/__pycache__/recall_fixed_precision.cpython-310.pyc,,
|
| 181 |
+
torchmetrics/functional/classification/__pycache__/roc.cpython-310.pyc,,
|
| 182 |
+
torchmetrics/functional/classification/__pycache__/sensitivity_specificity.cpython-310.pyc,,
|
| 183 |
+
torchmetrics/functional/classification/__pycache__/specificity.cpython-310.pyc,,
|
| 184 |
+
torchmetrics/functional/classification/__pycache__/specificity_sensitivity.cpython-310.pyc,,
|
| 185 |
+
torchmetrics/functional/classification/__pycache__/stat_scores.cpython-310.pyc,,
|
| 186 |
+
torchmetrics/functional/classification/accuracy.py,sha256=oN2_8ExcHx0E9TcDevuyicC2O2ScMRzUJmtnMluk-oI,20039
|
| 187 |
+
torchmetrics/functional/classification/auroc.py,sha256=s5PhrMKJjoCO6FOOuMFJ0zMp7W6-_JjWnvaFx2WK5bU,23714
|
| 188 |
+
torchmetrics/functional/classification/average_precision.py,sha256=8JLUguxEVel5K6HEQ5xF0FaXnTB9H4NUMEeMv_QYzYw,23577
|
| 189 |
+
torchmetrics/functional/classification/calibration_error.py,sha256=HRg8c73p3uvTykykPx0gPM7UlX-IHgzPBT037z5Quac,16976
|
| 190 |
+
torchmetrics/functional/classification/cohen_kappa.py,sha256=GhLGVkiU6oX6Av99uGNbAiywPE8UF8eoapRMFkVhlIM,11633
|
| 191 |
+
torchmetrics/functional/classification/confusion_matrix.py,sha256=IZtK8pY36posNW7FUEAqViQdGS9amO3r01iXUE23qAw,27785
|
| 192 |
+
torchmetrics/functional/classification/eer.py,sha256=92hHrYFpaJ9AjafQXjkiS2OVXzTvZDXPA4W-Xl6KOCE,13176
|
| 193 |
+
torchmetrics/functional/classification/exact_match.py,sha256=bvJUNWa0VnHNeGC7sQBQZ0RUD3O--ml8gk-YxqlYeg8,11963
|
| 194 |
+
torchmetrics/functional/classification/f_beta.py,sha256=d03WGgnIcF6TBW6XbDELlaqzqxKJL-zTGcQo4LU4hhw,37936
|
| 195 |
+
torchmetrics/functional/classification/group_fairness.py,sha256=IPgJgQsoWuzv5fgst5O4dkYu-1L5kYh8MAifz3kUpqs,16872
|
| 196 |
+
torchmetrics/functional/classification/hamming.py,sha256=AWxWwllptTn0GpNOmewLvatwLKuFgBNr0hDdR64Ujyc,20726
|
| 197 |
+
torchmetrics/functional/classification/hinge.py,sha256=T_cFHhhZKlAkII5Jx5HMAr27IwV0cv9bMzctWuqa7Ks,12404
|
| 198 |
+
torchmetrics/functional/classification/jaccard.py,sha256=upbjIwzZ_ggVezBVNZNWKqltQSiviv4B-N0P5u0y71s,17235
|
| 199 |
+
torchmetrics/functional/classification/logauc.py,sha256=o5P1iu538mLtGDo1n0Rv1as6_HxXDgq3cmhm1hK0g5Q,17864
|
| 200 |
+
torchmetrics/functional/classification/matthews_corrcoef.py,sha256=JJIQigQt7xGoElLHjzEAU2CF5Yqonl_IUzCO3BpF-tY,12855
|
| 201 |
+
torchmetrics/functional/classification/negative_predictive_value.py,sha256=9vO9brzv2Ubmp_LFkKztfcjv0YdapkZm2Ata7DFT-8Q,20655
|
| 202 |
+
torchmetrics/functional/classification/precision_fixed_recall.py,sha256=NMo_KziOn0iJfsLx4suWy0YXAGklpW5ZCy9fqrZdoEQ,18024
|
| 203 |
+
torchmetrics/functional/classification/precision_recall.py,sha256=IWYoKEPs3HUf1Mqf3U9aVMSK0CzjXO74V2iEJ5wS-fs,36816
|
| 204 |
+
torchmetrics/functional/classification/precision_recall_curve.py,sha256=ne1lHINYQVdzmIilMgiNO7_x83v7nB-Pn9bOT4rSBq4,47564
|
| 205 |
+
torchmetrics/functional/classification/ranking.py,sha256=ndKaQlMPDW36EJ6r-2jZZZX7Kr6TGlr4rGrC2Br9z8Q,11377
|
| 206 |
+
torchmetrics/functional/classification/recall_fixed_precision.py,sha256=SjMaETyWPwrZJaV9TX5qFMT50SopeCGwpUVERcKBCXs,21870
|
| 207 |
+
torchmetrics/functional/classification/roc.py,sha256=-3nASnhSc0JKQWJBirp5Oo811bD46tblXyjZxshS-T8,28559
|
| 208 |
+
torchmetrics/functional/classification/sensitivity_specificity.py,sha256=EIVTPmnhASlHBiXSMq4CfqEbdB4FFlctSvqZYhq1ZWQ,22197
|
| 209 |
+
torchmetrics/functional/classification/specificity.py,sha256=U5JhctBhJk7OCgDmnUkfj5fLRBTj9WNuKFdEJ9ci4bg,18562
|
| 210 |
+
torchmetrics/functional/classification/specificity_sensitivity.py,sha256=MBfj89U5MFhdxC_i6T63hjnaq7LxdDZOKmrjJdakSR4,23556
|
| 211 |
+
torchmetrics/functional/classification/stat_scores.py,sha256=cH8JMBweBeFQQ3xDx0ZLuYmfHMw-2bl3y67A5So-MvY,41365
|
| 212 |
+
torchmetrics/functional/clustering/__init__.py,sha256=AD1Is3Bd41C4Ux8pEr3vqbbXKoADPYggpP5Cy2W8Irs,1961
|
| 213 |
+
torchmetrics/functional/clustering/__pycache__/__init__.cpython-310.pyc,,
|
| 214 |
+
torchmetrics/functional/clustering/__pycache__/adjusted_mutual_info_score.cpython-310.pyc,,
|
| 215 |
+
torchmetrics/functional/clustering/__pycache__/adjusted_rand_score.cpython-310.pyc,,
|
| 216 |
+
torchmetrics/functional/clustering/__pycache__/calinski_harabasz_score.cpython-310.pyc,,
|
| 217 |
+
torchmetrics/functional/clustering/__pycache__/cluster_accuracy.cpython-310.pyc,,
|
| 218 |
+
torchmetrics/functional/clustering/__pycache__/davies_bouldin_score.cpython-310.pyc,,
|
| 219 |
+
torchmetrics/functional/clustering/__pycache__/dunn_index.cpython-310.pyc,,
|
| 220 |
+
torchmetrics/functional/clustering/__pycache__/fowlkes_mallows_index.cpython-310.pyc,,
|
| 221 |
+
torchmetrics/functional/clustering/__pycache__/homogeneity_completeness_v_measure.cpython-310.pyc,,
|
| 222 |
+
torchmetrics/functional/clustering/__pycache__/mutual_info_score.cpython-310.pyc,,
|
| 223 |
+
torchmetrics/functional/clustering/__pycache__/normalized_mutual_info_score.cpython-310.pyc,,
|
| 224 |
+
torchmetrics/functional/clustering/__pycache__/rand_score.cpython-310.pyc,,
|
| 225 |
+
torchmetrics/functional/clustering/__pycache__/utils.cpython-310.pyc,,
|
| 226 |
+
torchmetrics/functional/clustering/adjusted_mutual_info_score.py,sha256=u8Bu-7oXp9SFnuhJw_Ni2Q3T_4UvJQAX6aym71bcFjw,4470
|
| 227 |
+
torchmetrics/functional/clustering/adjusted_rand_score.py,sha256=S63-9ipbJ2xwdzDzkjpjKoU5AK18ajumXqJXhFIF-uU,2422
|
| 228 |
+
torchmetrics/functional/clustering/calinski_harabasz_score.py,sha256=A0KO1NQQOjXKNIK0o33dr0IKfMI1-t59W7aDIAOs9SY,2432
|
| 229 |
+
torchmetrics/functional/clustering/cluster_accuracy.py,sha256=CABBa3QK11i_OZG6eoDRI6fA-n1PMM0Jhmy9fofgI6g,2538
|
| 230 |
+
torchmetrics/functional/clustering/davies_bouldin_score.py,sha256=kocPnHdOgG-fUB7GcAeUzqAOjkzXCT8LFf4SZQtVJCQ,2595
|
| 231 |
+
torchmetrics/functional/clustering/dunn_index.py,sha256=tNmaPqi-3ageHHruNbz0f5hJ8VgkS55KG6irCGPKKls,2764
|
| 232 |
+
torchmetrics/functional/clustering/fowlkes_mallows_index.py,sha256=fvY5b869WfAyEcoAnNKH6uYhNBgBcIbWBKI-AOIeaWI,2477
|
| 233 |
+
torchmetrics/functional/clustering/homogeneity_completeness_v_measure.py,sha256=gQFqVNpPyef8RtVxkd4snud8Ku8fTzQWlGlYYXb8w6Q,4374
|
| 234 |
+
torchmetrics/functional/clustering/mutual_info_score.py,sha256=DOAZhmgC-Qj3-gtaR1XahDr6CsjLKf_bLo5OBiofmFY,2616
|
| 235 |
+
torchmetrics/functional/clustering/normalized_mutual_info_score.py,sha256=QUqPGhyJqckNjzMo1_2xgbmvTkCV-e-bw78vlsyKIDg,2104
|
| 236 |
+
torchmetrics/functional/clustering/rand_score.py,sha256=wpZODfoQXhG_nstuB0bmieB4aHpdMZksxWlJNtBv40g,2602
|
| 237 |
+
torchmetrics/functional/clustering/utils.py,sha256=5XXzlUNdMKZj7kEpvGjjBYEjnljHudiy_RAu7QYIKaU,10090
|
| 238 |
+
torchmetrics/functional/detection/__init__.py,sha256=Xo65qcNkcJbQTpex3Ym8JTIlOXkNt66G1ae7wpeVbYQ,1510
|
| 239 |
+
torchmetrics/functional/detection/__pycache__/__init__.cpython-310.pyc,,
|
| 240 |
+
torchmetrics/functional/detection/__pycache__/_deprecated.cpython-310.pyc,,
|
| 241 |
+
torchmetrics/functional/detection/__pycache__/_panoptic_quality_common.cpython-310.pyc,,
|
| 242 |
+
torchmetrics/functional/detection/__pycache__/ciou.cpython-310.pyc,,
|
| 243 |
+
torchmetrics/functional/detection/__pycache__/diou.cpython-310.pyc,,
|
| 244 |
+
torchmetrics/functional/detection/__pycache__/giou.cpython-310.pyc,,
|
| 245 |
+
torchmetrics/functional/detection/__pycache__/iou.cpython-310.pyc,,
|
| 246 |
+
torchmetrics/functional/detection/__pycache__/map.cpython-310.pyc,,
|
| 247 |
+
torchmetrics/functional/detection/__pycache__/panoptic_qualities.cpython-310.pyc,,
|
| 248 |
+
torchmetrics/functional/detection/_deprecated.py,sha256=QOLkrR_L5cYascVaOz58mm32DTe-gjFGDqTKcB56sro,2308
|
| 249 |
+
torchmetrics/functional/detection/_panoptic_quality_common.py,sha256=A7LctJ-pmMMJpB4qCXhNRhpH5A4-60FcJRv3IPIMIss,20147
|
| 250 |
+
torchmetrics/functional/detection/ciou.py,sha256=GDPVS1z0tLlGpZqSvJHHhK0R-aIKeq1nt84Jar3S0hY,4912
|
| 251 |
+
torchmetrics/functional/detection/diou.py,sha256=D9-UygjNRESR6ft__AG0pFgBGn0q6F_gZlwfUd5yiFA,4914
|
| 252 |
+
torchmetrics/functional/detection/giou.py,sha256=TYCYK6-2U2UPhnrrmsgePc8T9yfxKiXRFmhsR9_O3fs,4918
|
| 253 |
+
torchmetrics/functional/detection/iou.py,sha256=k-pVlsypkbaPPDRtPJJMyR8tjUBLxes-VM8efgK32oU,4833
|
| 254 |
+
torchmetrics/functional/detection/map.py,sha256=TXMFJC8hoPVkkzYA2omYwzM42XYOPhnYqWAh3K6UCmM,9732
|
| 255 |
+
torchmetrics/functional/detection/panoptic_qualities.py,sha256=rR3_bXo4hS8e1KZ9NRzIIwzu9FCZSoZP9I-st0Ev4Zk,11547
|
| 256 |
+
torchmetrics/functional/image/__init__.py,sha256=n4FQ3CJqqtODHOHpWmT3DQlg1e6f7YpXgoHqDuctBts,2890
|
| 257 |
+
torchmetrics/functional/image/__pycache__/__init__.cpython-310.pyc,,
|
| 258 |
+
torchmetrics/functional/image/__pycache__/_deprecated.cpython-310.pyc,,
|
| 259 |
+
torchmetrics/functional/image/__pycache__/arniqa.cpython-310.pyc,,
|
| 260 |
+
torchmetrics/functional/image/__pycache__/d_lambda.cpython-310.pyc,,
|
| 261 |
+
torchmetrics/functional/image/__pycache__/d_s.cpython-310.pyc,,
|
| 262 |
+
torchmetrics/functional/image/__pycache__/dists.cpython-310.pyc,,
|
| 263 |
+
torchmetrics/functional/image/__pycache__/ergas.cpython-310.pyc,,
|
| 264 |
+
torchmetrics/functional/image/__pycache__/gradients.cpython-310.pyc,,
|
| 265 |
+
torchmetrics/functional/image/__pycache__/lpips.cpython-310.pyc,,
|
| 266 |
+
torchmetrics/functional/image/__pycache__/perceptual_path_length.cpython-310.pyc,,
|
| 267 |
+
torchmetrics/functional/image/__pycache__/psnr.cpython-310.pyc,,
|
| 268 |
+
torchmetrics/functional/image/__pycache__/psnrb.cpython-310.pyc,,
|
| 269 |
+
torchmetrics/functional/image/__pycache__/qnr.cpython-310.pyc,,
|
| 270 |
+
torchmetrics/functional/image/__pycache__/rase.cpython-310.pyc,,
|
| 271 |
+
torchmetrics/functional/image/__pycache__/rmse_sw.cpython-310.pyc,,
|
| 272 |
+
torchmetrics/functional/image/__pycache__/sam.cpython-310.pyc,,
|
| 273 |
+
torchmetrics/functional/image/__pycache__/scc.cpython-310.pyc,,
|
| 274 |
+
torchmetrics/functional/image/__pycache__/ssim.cpython-310.pyc,,
|
| 275 |
+
torchmetrics/functional/image/__pycache__/tv.cpython-310.pyc,,
|
| 276 |
+
torchmetrics/functional/image/__pycache__/uqi.cpython-310.pyc,,
|
| 277 |
+
torchmetrics/functional/image/__pycache__/utils.cpython-310.pyc,,
|
| 278 |
+
torchmetrics/functional/image/__pycache__/vif.cpython-310.pyc,,
|
| 279 |
+
torchmetrics/functional/image/_deprecated.py,sha256=5UaCvIG8KZPdhwHV4tZKwIFCiHCQngWa9oju0isVFx8,8940
|
| 280 |
+
torchmetrics/functional/image/arniqa.py,sha256=DL71C6UqeMBiLv_CQ4psGQZ6BSSY0wfb0r_DoDcOyv8,12220
|
| 281 |
+
torchmetrics/functional/image/d_lambda.py,sha256=rivTjYLrmJhdZSPcNtIHGrdVcAMTnxqIPQPlZ_0UMvE,5623
|
| 282 |
+
torchmetrics/functional/image/d_s.py,sha256=dElq0cbZcSc00f9JQRhxSn3Qas-rzVOjRuvr1rdQDPc,11095
|
| 283 |
+
torchmetrics/functional/image/dists.py,sha256=V3-TWDXgaPhC_2gp7gMlls_X46b4eWdJFG6SifsKG94,8930
|
| 284 |
+
torchmetrics/functional/image/dists_models/weights.pt,sha256=9eZcliMLf2yplWkWR9SCI35Mq4pQxcSleE8hnvB0ghg,12288
|
| 285 |
+
torchmetrics/functional/image/ergas.py,sha256=S0nZ6EHupd9e5yu9XRFyf-Pngwisv5TX_65niiKbXko,4167
|
| 286 |
+
torchmetrics/functional/image/gradients.py,sha256=GiniMRsV22SoyGWxs087in4G9itrWt_wNHftxC4oKA4,2886
|
| 287 |
+
torchmetrics/functional/image/lpips.py,sha256=tkftKrTUZiKJMczXD6HvUd5h3Zt8_DCOvbKOPUutqIo,17630
|
| 288 |
+
torchmetrics/functional/image/lpips_models/alex.pth,sha256=33MoXjWyI1Wi34fNtrcLNDcTtmft29pz4Zd-DIYINcA,6009
|
| 289 |
+
torchmetrics/functional/image/lpips_models/squeeze.pth,sha256=SlNQ8jYAy3mSPOZbsHy_V9ykYTKYlBU-BaE0a9Uxz3Y,10811
|
| 290 |
+
torchmetrics/functional/image/lpips_models/vgg.pth,sha256=p4kooK8eXw_LHzuej4w6Klo94kTYMK1cH-3cebhDKGg,7289
|
| 291 |
+
torchmetrics/functional/image/perceptual_path_length.py,sha256=Xh_Em1YMdxm7z3hQcKQ6qcU0h9PoA6PJXbBDHCYWohA,13741
|
| 292 |
+
torchmetrics/functional/image/psnr.py,sha256=fbM3yUNPLyR-oh7qgIHB81pkFCQzXeiheLzAtWdf4OI,5560
|
| 293 |
+
torchmetrics/functional/image/psnrb.py,sha256=jcyB5f7jSUtM5swlYZRRlDydF8zAj4dfUr70Zp8mpQ8,4858
|
| 294 |
+
torchmetrics/functional/image/qnr.py,sha256=Y91qy2uOjRFeqQQEJtKibyhHAYwfF61azcnJ26tPfb4,3201
|
| 295 |
+
torchmetrics/functional/image/rase.py,sha256=AeIk9mkg18dIUor6QD472wINP41MuB3Trm0C_-a1p6U,3980
|
| 296 |
+
torchmetrics/functional/image/rmse_sw.py,sha256=QsHOEd7csxo8TNaAmD5Umkjb4ArFEH0QOOAyg_3-J0U,5546
|
| 297 |
+
torchmetrics/functional/image/sam.py,sha256=nMIZS7cVLPPUIBOmK_IHWGjNqRKPq2ZLvCrq9U8s5hI,4198
|
| 298 |
+
torchmetrics/functional/image/scc.py,sha256=V8PdnvMxGfZr3cWs3p_gV47V_pnZHUSWHDpCtN4f4OM,8610
|
| 299 |
+
torchmetrics/functional/image/ssim.py,sha256=upztfW16SDf8NKHKYQSodPOHxMKc7Y6mYo_NU34O7OA,21771
|
| 300 |
+
torchmetrics/functional/image/tv.py,sha256=bQmlbCqN4Mt_gRtPrABhe3Qq3LiTOGpOQRl-Vu8A78c,2799
|
| 301 |
+
torchmetrics/functional/image/uqi.py,sha256=Vu5myFN9iwfeW-SWNxeheG5I-6QLmAe4CFArmd9p538,6566
|
| 302 |
+
torchmetrics/functional/image/utils.py,sha256=Suy8BfPBTakcEd01IauLTdfGCfNZgOVKcgmVePrGByc,6013
|
| 303 |
+
torchmetrics/functional/image/vif.py,sha256=9b6VpqMk9DmHdxXBuka0lkAj37yCJCdleUu5nRfN5nY,6419
|
| 304 |
+
torchmetrics/functional/multimodal/__init__.py,sha256=MwecONDNOv7y6xnyDNUt2_c3jIaNFYjU70CBNgAoDx0,1019
|
| 305 |
+
torchmetrics/functional/multimodal/__pycache__/__init__.cpython-310.pyc,,
|
| 306 |
+
torchmetrics/functional/multimodal/__pycache__/clip_iqa.cpython-310.pyc,,
|
| 307 |
+
torchmetrics/functional/multimodal/__pycache__/clip_score.cpython-310.pyc,,
|
| 308 |
+
torchmetrics/functional/multimodal/__pycache__/lve.cpython-310.pyc,,
|
| 309 |
+
torchmetrics/functional/multimodal/clip_iqa.py,sha256=jbyyAUOBnw8e_EcABnJ3l1gUfnHcel3FWFJQfJfD__I,15942
|
| 310 |
+
torchmetrics/functional/multimodal/clip_score.py,sha256=Tx38ulxuK4nc9vS4L6u4OivCVafVytwl4MWOGDv_BX4,15186
|
| 311 |
+
torchmetrics/functional/multimodal/lve.py,sha256=6KKx7TtTPdaoxdEi9hbpLh3yb8i2hrxHPHGc9BUnX90,4398
|
| 312 |
+
torchmetrics/functional/nominal/__init__.py,sha256=JDtSc1P4crHRJSQb6PXymlWykb4-eGed-kLHVzNHpI0,1285
|
| 313 |
+
torchmetrics/functional/nominal/__pycache__/__init__.cpython-310.pyc,,
|
| 314 |
+
torchmetrics/functional/nominal/__pycache__/cramers.cpython-310.pyc,,
|
| 315 |
+
torchmetrics/functional/nominal/__pycache__/fleiss_kappa.cpython-310.pyc,,
|
| 316 |
+
torchmetrics/functional/nominal/__pycache__/pearson.cpython-310.pyc,,
|
| 317 |
+
torchmetrics/functional/nominal/__pycache__/theils_u.cpython-310.pyc,,
|
| 318 |
+
torchmetrics/functional/nominal/__pycache__/tschuprows.cpython-310.pyc,,
|
| 319 |
+
torchmetrics/functional/nominal/__pycache__/utils.cpython-310.pyc,,
|
| 320 |
+
torchmetrics/functional/nominal/cramers.py,sha256=Ot_7UFSz_Pv-73eNoUFdzUywPwdPw__de9wDiCOBN_Q,7340
|
| 321 |
+
torchmetrics/functional/nominal/fleiss_kappa.py,sha256=3vjLTQ8Qs5wTWosHjJ4-7RFaBnAivrA3EedNMa2xYzg,4226
|
| 322 |
+
torchmetrics/functional/nominal/pearson.py,sha256=7SZeWnwTzvgxHD7_8oBHsQKoGJtUiRsO5OJ1TZkqf9g,6875
|
| 323 |
+
torchmetrics/functional/nominal/theils_u.py,sha256=APxXfi7RFrrdPhfmBQ2ux1pWjOZ1ALN9dICMf6SQafA,7107
|
| 324 |
+
torchmetrics/functional/nominal/tschuprows.py,sha256=6la3UCp8aPIzfTxT80bvmS9qpI5CmS8FxQAlShFCz1k,7639
|
| 325 |
+
torchmetrics/functional/nominal/utils.py,sha256=8S75LS3YDDKBlSny5rgurDQUi9_yU9IGwr8c0rtGTfM,5745
|
| 326 |
+
torchmetrics/functional/pairwise/__init__.py,sha256=f1NY4J7hgdcrpKk2yLHXF9yojm8qbGOmB8G4h9jrVRk,1173
|
| 327 |
+
torchmetrics/functional/pairwise/__pycache__/__init__.cpython-310.pyc,,
|
| 328 |
+
torchmetrics/functional/pairwise/__pycache__/cosine.cpython-310.pyc,,
|
| 329 |
+
torchmetrics/functional/pairwise/__pycache__/euclidean.cpython-310.pyc,,
|
| 330 |
+
torchmetrics/functional/pairwise/__pycache__/helpers.cpython-310.pyc,,
|
| 331 |
+
torchmetrics/functional/pairwise/__pycache__/linear.cpython-310.pyc,,
|
| 332 |
+
torchmetrics/functional/pairwise/__pycache__/manhattan.cpython-310.pyc,,
|
| 333 |
+
torchmetrics/functional/pairwise/__pycache__/minkowski.cpython-310.pyc,,
|
| 334 |
+
torchmetrics/functional/pairwise/cosine.py,sha256=CPg8_Q4hLUe6YymgbZiCir1FtSWmnYROnXZpv5LYnyw,3499
|
| 335 |
+
torchmetrics/functional/pairwise/euclidean.py,sha256=p9WZz6TBwQS25cZKDcU-6_tnDwF5OOTtkTIUBE2whq0,3449
|
| 336 |
+
torchmetrics/functional/pairwise/helpers.py,sha256=8gZxrpBBUuRJdUnx49JUloeAlwgH3gM8-Ul8VBilKzs,2246
|
| 337 |
+
torchmetrics/functional/pairwise/linear.py,sha256=OLOP2usOlbPOzD05vXlnWLlHkGgS68x94lP7UmRdkJU,3176
|
| 338 |
+
torchmetrics/functional/pairwise/manhattan.py,sha256=zXQBFhxpmYzVtXSclM7sIPHXWXea-1tSmszU4CrjUng,3196
|
| 339 |
+
torchmetrics/functional/pairwise/minkowski.py,sha256=jkms9LhEdX5yE9aezLKZXk3KeLi3EfLsPjUfxTlwCTQ,3999
|
| 340 |
+
torchmetrics/functional/regression/__init__.py,sha256=NhakHreDD8TvYs7wk0aFEJ72pHeCC6I_rIJFHy_rRgw,3045
|
| 341 |
+
torchmetrics/functional/regression/__pycache__/__init__.cpython-310.pyc,,
|
| 342 |
+
torchmetrics/functional/regression/__pycache__/concordance.cpython-310.pyc,,
|
| 343 |
+
torchmetrics/functional/regression/__pycache__/cosine_similarity.cpython-310.pyc,,
|
| 344 |
+
torchmetrics/functional/regression/__pycache__/crps.cpython-310.pyc,,
|
| 345 |
+
torchmetrics/functional/regression/__pycache__/csi.cpython-310.pyc,,
|
| 346 |
+
torchmetrics/functional/regression/__pycache__/explained_variance.cpython-310.pyc,,
|
| 347 |
+
torchmetrics/functional/regression/__pycache__/js_divergence.cpython-310.pyc,,
|
| 348 |
+
torchmetrics/functional/regression/__pycache__/kendall.cpython-310.pyc,,
|
| 349 |
+
torchmetrics/functional/regression/__pycache__/kl_divergence.cpython-310.pyc,,
|
| 350 |
+
torchmetrics/functional/regression/__pycache__/log_cosh.cpython-310.pyc,,
|
| 351 |
+
torchmetrics/functional/regression/__pycache__/log_mse.cpython-310.pyc,,
|
| 352 |
+
torchmetrics/functional/regression/__pycache__/mae.cpython-310.pyc,,
|
| 353 |
+
torchmetrics/functional/regression/__pycache__/mape.cpython-310.pyc,,
|
| 354 |
+
torchmetrics/functional/regression/__pycache__/minkowski.cpython-310.pyc,,
|
| 355 |
+
torchmetrics/functional/regression/__pycache__/mse.cpython-310.pyc,,
|
| 356 |
+
torchmetrics/functional/regression/__pycache__/nrmse.cpython-310.pyc,,
|
| 357 |
+
torchmetrics/functional/regression/__pycache__/pearson.cpython-310.pyc,,
|
| 358 |
+
torchmetrics/functional/regression/__pycache__/r2.cpython-310.pyc,,
|
| 359 |
+
torchmetrics/functional/regression/__pycache__/rse.cpython-310.pyc,,
|
| 360 |
+
torchmetrics/functional/regression/__pycache__/spearman.cpython-310.pyc,,
|
| 361 |
+
torchmetrics/functional/regression/__pycache__/symmetric_mape.cpython-310.pyc,,
|
| 362 |
+
torchmetrics/functional/regression/__pycache__/tweedie_deviance.cpython-310.pyc,,
|
| 363 |
+
torchmetrics/functional/regression/__pycache__/utils.cpython-310.pyc,,
|
| 364 |
+
torchmetrics/functional/regression/__pycache__/wmape.cpython-310.pyc,,
|
| 365 |
+
torchmetrics/functional/regression/concordance.py,sha256=PKw3PFNytnMbVY1DLdVcYJPoeymqCxzm3JFW1yY2F9I,3340
|
| 366 |
+
torchmetrics/functional/regression/cosine_similarity.py,sha256=OGlqnXQZe6I-JSTmbhRQDhip9UQi_OWfEZ1xgjGU_0s,3628
|
| 367 |
+
torchmetrics/functional/regression/crps.py,sha256=md5MRhhKUlJhMyzkXBIg4W58VMiWj9Cn1kRw5V7Wphs,3767
|
| 368 |
+
torchmetrics/functional/regression/csi.py,sha256=0pURdVheU2yk5neMLcdbv8KTmLIn3z8t5QYs-Col92c,4855
|
| 369 |
+
torchmetrics/functional/regression/explained_variance.py,sha256=ul817GvdESRyAI8e9veAiv1RJQWw2HnOigA5YKzQT9o,5492
|
| 370 |
+
torchmetrics/functional/regression/js_divergence.py,sha256=l6WIe1R6AGKCwdmxBoaO06IPV4oGvWNc-MI8BQA7MBU,4237
|
| 371 |
+
torchmetrics/functional/regression/kendall.py,sha256=AG4AzLnwP-o3QawCaXlaSpsndBhkaYtmTRUf2I4kpPc,15816
|
| 372 |
+
torchmetrics/functional/regression/kl_divergence.py,sha256=6C7eQPvQgoH-jDFzRU3txjv_RedCyfTcNouQlFrOu3Q,4392
|
| 373 |
+
torchmetrics/functional/regression/log_cosh.py,sha256=-xCnETLaQ6e5o2N7jiORi7wtsv9dhIIiccFrKZxZ6Ck,3500
|
| 374 |
+
torchmetrics/functional/regression/log_mse.py,sha256=HjJy6qvVFo4MsmFPT6KkMVQs1n4iCaH_t6Ucw2xpi08,2598
|
| 375 |
+
torchmetrics/functional/regression/mae.py,sha256=Vysyes-BPJ2xk42x07eEuiJ3bg7GJ-W-hj5m80ci-NA,2855
|
| 376 |
+
torchmetrics/functional/regression/mape.py,sha256=1UHopkH9KN-KYB9qOSGklkUqFqN1KAS-WkPAmVVDNZE,3023
|
| 377 |
+
torchmetrics/functional/regression/minkowski.py,sha256=sQYgJm2edpTZhTDIVAyGGZjJ9EAzgoeF8cB-j64GMMU,3010
|
| 378 |
+
torchmetrics/functional/regression/mse.py,sha256=pNg7uuCSvTqjQrG2XiYbsZKn5CZIrndzP3ZGFCduMcE,2893
|
| 379 |
+
torchmetrics/functional/regression/nrmse.py,sha256=07f9JsO9PYf8P4UlsuMISnK7eORJPsuwE5DVS6Oi1bk,4376
|
| 380 |
+
torchmetrics/functional/regression/pearson.py,sha256=u2S2HXDzHD55V7XhHtfukpROXiqtDFniJnnmcKr7UVg,7368
|
| 381 |
+
torchmetrics/functional/regression/r2.py,sha256=M6NC_RAOHNtldiUENV7R1L2pvsnVoo5WpxzAdnVE__M,6613
|
| 382 |
+
torchmetrics/functional/regression/rse.py,sha256=o8AFBRGSS2Evcux83H6IEn6PuywjpJZC6fg9e9Y3y6A,2945
|
| 383 |
+
torchmetrics/functional/regression/spearman.py,sha256=G1hn6br1BpSDMEZ8HJS_axHPNNHyxkflW107ZhK9k2s,4723
|
| 384 |
+
torchmetrics/functional/regression/symmetric_mape.py,sha256=Kt2Y3v6sTEdLCA0M5YOBgoLPtJC6Jff5utmbdDSZMeI,3298
|
| 385 |
+
torchmetrics/functional/regression/tweedie_deviance.py,sha256=3Z-kVkKUDvUUxDtjiyqAUot2KOrzHPDJ_lVH9mSwRJw,6071
|
| 386 |
+
torchmetrics/functional/regression/utils.py,sha256=J5w3uY5qnyeoibifzsIwxE7cAm7ooFEVW--k4qDGFkU,1805
|
| 387 |
+
torchmetrics/functional/regression/wmape.py,sha256=z8SRSBAg_lTAJemBpfuat-B_kU_fl5Y1sLv0cj9Qf8c,2615
|
| 388 |
+
torchmetrics/functional/retrieval/__init__.py,sha256=hQRnCa7zEI8V_VhJSCWwJL3VDjWz1blooSUiq98gvJ8,1688
|
| 389 |
+
torchmetrics/functional/retrieval/__pycache__/__init__.cpython-310.pyc,,
|
| 390 |
+
torchmetrics/functional/retrieval/__pycache__/_deprecated.cpython-310.pyc,,
|
| 391 |
+
torchmetrics/functional/retrieval/__pycache__/auroc.cpython-310.pyc,,
|
| 392 |
+
torchmetrics/functional/retrieval/__pycache__/average_precision.cpython-310.pyc,,
|
| 393 |
+
torchmetrics/functional/retrieval/__pycache__/fall_out.cpython-310.pyc,,
|
| 394 |
+
torchmetrics/functional/retrieval/__pycache__/hit_rate.cpython-310.pyc,,
|
| 395 |
+
torchmetrics/functional/retrieval/__pycache__/ndcg.cpython-310.pyc,,
|
| 396 |
+
torchmetrics/functional/retrieval/__pycache__/precision.cpython-310.pyc,,
|
| 397 |
+
torchmetrics/functional/retrieval/__pycache__/precision_recall_curve.cpython-310.pyc,,
|
| 398 |
+
torchmetrics/functional/retrieval/__pycache__/r_precision.cpython-310.pyc,,
|
| 399 |
+
torchmetrics/functional/retrieval/__pycache__/recall.cpython-310.pyc,,
|
| 400 |
+
torchmetrics/functional/retrieval/__pycache__/reciprocal_rank.cpython-310.pyc,,
|
| 401 |
+
torchmetrics/functional/retrieval/_deprecated.py,sha256=N-MbyyAnk_u6zeaf83wK-TMv-E1aVu39JYXayStaH7g,5410
|
| 402 |
+
torchmetrics/functional/retrieval/auroc.py,sha256=1pqKdtd8kektGa03au4NKvtedoIoD8FydMY5tZ9U3Zo,2663
|
| 403 |
+
torchmetrics/functional/retrieval/average_precision.py,sha256=5MDU0IJiHv5CWaPqY2-8Li9XuibiAxZjvz-kUTgYivE,2676
|
| 404 |
+
torchmetrics/functional/retrieval/fall_out.py,sha256=Q2M7qmf57NyWYRdWAvNUbyQEbY_nWVWFA_Ftahluybs,2671
|
| 405 |
+
torchmetrics/functional/retrieval/hit_rate.py,sha256=CpkO2zLnBxreNCQVvF7neJD7m9lVmUc72fhTi0KrWQk,2409
|
| 406 |
+
torchmetrics/functional/retrieval/ndcg.py,sha256=tZky3qj7gmM8wZeqZHAFLn7spAIkpGpm0i_NPWLwjII,4328
|
| 407 |
+
torchmetrics/functional/retrieval/precision.py,sha256=Wf1NpSk2WUgwmjXnBGNltH-qqHwCcBzcz1JpDPTa5H8,2847
|
| 408 |
+
torchmetrics/functional/retrieval/precision_recall_curve.py,sha256=uiCXPAtjOekAuhxHQoV5yDQmBfKcJbQNHMbLz0rXP_g,4037
|
| 409 |
+
torchmetrics/functional/retrieval/r_precision.py,sha256=DpxPzInI5c5Fdz1-JLLi99P32Z6iJfGltFAk7l4bkfM,2121
|
| 410 |
+
torchmetrics/functional/retrieval/recall.py,sha256=HGhXI7BRjNGkSNk-z4xEN_yNMfpMRdv0o6GGXz2RuYQ,2593
|
| 411 |
+
torchmetrics/functional/retrieval/reciprocal_rank.py,sha256=XtA4BSXu5Keuy5tDVXVRNkcvPG0KqQdFAp660yYN6UE,2518
|
| 412 |
+
torchmetrics/functional/segmentation/__init__.py,sha256=i0DFQxUagC0C0AHT30H9i-32lzwtMu6Ev1kG_v5LfGc,972
|
| 413 |
+
torchmetrics/functional/segmentation/__pycache__/__init__.cpython-310.pyc,,
|
| 414 |
+
torchmetrics/functional/segmentation/__pycache__/dice.cpython-310.pyc,,
|
| 415 |
+
torchmetrics/functional/segmentation/__pycache__/generalized_dice.cpython-310.pyc,,
|
| 416 |
+
torchmetrics/functional/segmentation/__pycache__/hausdorff_distance.cpython-310.pyc,,
|
| 417 |
+
torchmetrics/functional/segmentation/__pycache__/mean_iou.cpython-310.pyc,,
|
| 418 |
+
torchmetrics/functional/segmentation/__pycache__/utils.cpython-310.pyc,,
|
| 419 |
+
torchmetrics/functional/segmentation/dice.py,sha256=hxZpHtPh1Lo6km2Kg3aIzWoEfENlEvGS5k3AqE0bgEc,8807
|
| 420 |
+
torchmetrics/functional/segmentation/generalized_dice.py,sha256=0MVbNWf1RD6pOGPPAY663inK_QS0ZYA1HhV_aMhtyvQ,6838
|
| 421 |
+
torchmetrics/functional/segmentation/hausdorff_distance.py,sha256=ahBDXnaNrdAY_xxPAA79UdUmrA75Ejl1S6HBXaYVXuA,4940
|
| 422 |
+
torchmetrics/functional/segmentation/mean_iou.py,sha256=fB5ex8V5ibeRTmSfPZ4xQ7XeTl_Giisj3w3J6OMU1lo,6786
|
| 423 |
+
torchmetrics/functional/segmentation/utils.py,sha256=d4M7lahG2YDouysZ_rSojoFXTSYats9gHLR9wUyTLSk,50136
|
| 424 |
+
torchmetrics/functional/shape/__init__.py,sha256=FxPrVkJAILigFAzOdvGI98m-dVSrwwn6Nw_Wr_8wWzo,688
|
| 425 |
+
torchmetrics/functional/shape/__pycache__/__init__.cpython-310.pyc,,
|
| 426 |
+
torchmetrics/functional/shape/__pycache__/procrustes.cpython-310.pyc,,
|
| 427 |
+
torchmetrics/functional/shape/procrustes.py,sha256=nDlQc3WczwcIGISPEWtjOrn-i2p7uLQfsgfpigHtl50,2728
|
| 428 |
+
torchmetrics/functional/text/__init__.py,sha256=kEA3cUZAlO9SLXyUNgb71p_ZX9CNlxwxhfLhyIYJYIU,2067
|
| 429 |
+
torchmetrics/functional/text/__pycache__/__init__.cpython-310.pyc,,
|
| 430 |
+
torchmetrics/functional/text/__pycache__/_deprecated.cpython-310.pyc,,
|
| 431 |
+
torchmetrics/functional/text/__pycache__/bert.cpython-310.pyc,,
|
| 432 |
+
torchmetrics/functional/text/__pycache__/bleu.cpython-310.pyc,,
|
| 433 |
+
torchmetrics/functional/text/__pycache__/cer.cpython-310.pyc,,
|
| 434 |
+
torchmetrics/functional/text/__pycache__/chrf.cpython-310.pyc,,
|
| 435 |
+
torchmetrics/functional/text/__pycache__/edit.cpython-310.pyc,,
|
| 436 |
+
torchmetrics/functional/text/__pycache__/eed.cpython-310.pyc,,
|
| 437 |
+
torchmetrics/functional/text/__pycache__/helper.cpython-310.pyc,,
|
| 438 |
+
torchmetrics/functional/text/__pycache__/helper_embedding_metric.cpython-310.pyc,,
|
| 439 |
+
torchmetrics/functional/text/__pycache__/infolm.cpython-310.pyc,,
|
| 440 |
+
torchmetrics/functional/text/__pycache__/mer.cpython-310.pyc,,
|
| 441 |
+
torchmetrics/functional/text/__pycache__/perplexity.cpython-310.pyc,,
|
| 442 |
+
torchmetrics/functional/text/__pycache__/rouge.cpython-310.pyc,,
|
| 443 |
+
torchmetrics/functional/text/__pycache__/sacre_bleu.cpython-310.pyc,,
|
| 444 |
+
torchmetrics/functional/text/__pycache__/squad.cpython-310.pyc,,
|
| 445 |
+
torchmetrics/functional/text/__pycache__/ter.cpython-310.pyc,,
|
| 446 |
+
torchmetrics/functional/text/__pycache__/wer.cpython-310.pyc,,
|
| 447 |
+
torchmetrics/functional/text/__pycache__/wil.cpython-310.pyc,,
|
| 448 |
+
torchmetrics/functional/text/__pycache__/wip.cpython-310.pyc,,
|
| 449 |
+
torchmetrics/functional/text/_deprecated.py,sha256=1332p3ojAoUPQabLW3u2aEwA0ymH-RwT9XuizxW4Fk0,13963
|
| 450 |
+
torchmetrics/functional/text/bert.py,sha256=BS9sruyRl96OgwAKH0Qo7TriKFK9i6iy2XrsXQeF758,26746
|
| 451 |
+
torchmetrics/functional/text/bleu.py,sha256=P2F2FZN-dVz7GHTbXTTTgprhcwWddZ7uc5jSHpsYFl8,7598
|
| 452 |
+
torchmetrics/functional/text/cer.py,sha256=QPsm_kUS_FKnjVOcxF6SORQyF1TuBhTLsXuZ87yWfGM,2970
|
| 453 |
+
torchmetrics/functional/text/chrf.py,sha256=L5CMw4D5h3gB9wnvsAVytcyupYmBrzM-G0JS1M7Rpbo,25904
|
| 454 |
+
torchmetrics/functional/text/edit.py,sha256=MqHGLvmkM4NkXbfKUpcHlOu1hfnVknR92gGOlL0x_Hg,4806
|
| 455 |
+
torchmetrics/functional/text/eed.py,sha256=HyNCFszmsatkGhGyFS6hoDVtyqjyNB3wJWV7n_ZXME4,17569
|
| 456 |
+
torchmetrics/functional/text/helper.py,sha256=2AUG95KbGxyAfDgzdJt8V_uvfttPGgFAlfsN5fFFjtI,17004
|
| 457 |
+
torchmetrics/functional/text/helper_embedding_metric.py,sha256=PQId2tnXovGDNrbGIf-My7fCNb3i9om8UIUu18XcwWo,12021
|
| 458 |
+
torchmetrics/functional/text/infolm.py,sha256=yKowb2NjeDvYM1GoBxQJLxbMB88Ayixcqg_O8AE4Zps,28027
|
| 459 |
+
torchmetrics/functional/text/mer.py,sha256=roRGGKGcfpeId3yA2X7pwehlD9wF0CBi3wv4TocA5TE,3018
|
| 460 |
+
torchmetrics/functional/text/perplexity.py,sha256=AaKgl3u-bb7IOpIKBAIVjyswga6ys5gH5clt2kEYAYI,5304
|
| 461 |
+
torchmetrics/functional/text/rouge.py,sha256=hMB_kehukr2s49xrWxG5A8BmuHkUyCixhHjkeFeR7Q8,20727
|
| 462 |
+
torchmetrics/functional/text/sacre_bleu.py,sha256=jGBFcdKPLPPRHBYVbfZiU_Wut6G3EhJlI9pNkzvSDbE,20151
|
| 463 |
+
torchmetrics/functional/text/squad.py,sha256=yu_vNl5X5HX_um5TN1wVsvbc0ta5i7TxexyTy9CcdC0,9869
|
| 464 |
+
torchmetrics/functional/text/ter.py,sha256=Gqesb980zS2Rvw0n9dTtL3kZ2nuQvubRjb_q96fuyPs,23280
|
| 465 |
+
torchmetrics/functional/text/wer.py,sha256=Qpwg0IRR5oTPK1G3XMqUbaJHZW-5mHVuwBOz3Pvfl-8,2961
|
| 466 |
+
torchmetrics/functional/text/wil.py,sha256=IhJ8FOiuzaFc7agGszacKzbIjLqVqLEWfuebMylrNAk,3496
|
| 467 |
+
torchmetrics/functional/text/wip.py,sha256=jJHXGA1Df-VkFU3JmN1NMZrGGTydgVsBk-AoehmAJAY,3500
|
| 468 |
+
torchmetrics/functional/video/__init__.py,sha256=Fve47SWsGruroKBLzyymNUhLL8mBMKlW2LFpsESL-bM,829
|
| 469 |
+
torchmetrics/functional/video/__pycache__/__init__.cpython-310.pyc,,
|
| 470 |
+
torchmetrics/functional/video/__pycache__/vmaf.cpython-310.pyc,,
|
| 471 |
+
torchmetrics/functional/video/vmaf.py,sha256=n_Vdt684JgukFyoByDXMpiS324UnpSvSGfZrkESa2p4,6979
|
| 472 |
+
torchmetrics/image/__init__.py,sha256=AFPaVQ3iZqacAYCBUaGZFQQImrLd1yI1PagSvf8dv0c,3038
|
| 473 |
+
torchmetrics/image/__pycache__/__init__.cpython-310.pyc,,
|
| 474 |
+
torchmetrics/image/__pycache__/_deprecated.cpython-310.pyc,,
|
| 475 |
+
torchmetrics/image/__pycache__/arniqa.cpython-310.pyc,,
|
| 476 |
+
torchmetrics/image/__pycache__/d_lambda.cpython-310.pyc,,
|
| 477 |
+
torchmetrics/image/__pycache__/d_s.cpython-310.pyc,,
|
| 478 |
+
torchmetrics/image/__pycache__/dists.cpython-310.pyc,,
|
| 479 |
+
torchmetrics/image/__pycache__/ergas.cpython-310.pyc,,
|
| 480 |
+
torchmetrics/image/__pycache__/fid.cpython-310.pyc,,
|
| 481 |
+
torchmetrics/image/__pycache__/inception.cpython-310.pyc,,
|
| 482 |
+
torchmetrics/image/__pycache__/kid.cpython-310.pyc,,
|
| 483 |
+
torchmetrics/image/__pycache__/lpip.cpython-310.pyc,,
|
| 484 |
+
torchmetrics/image/__pycache__/mifid.cpython-310.pyc,,
|
| 485 |
+
torchmetrics/image/__pycache__/perceptual_path_length.cpython-310.pyc,,
|
| 486 |
+
torchmetrics/image/__pycache__/psnr.cpython-310.pyc,,
|
| 487 |
+
torchmetrics/image/__pycache__/psnrb.cpython-310.pyc,,
|
| 488 |
+
torchmetrics/image/__pycache__/qnr.cpython-310.pyc,,
|
| 489 |
+
torchmetrics/image/__pycache__/rase.cpython-310.pyc,,
|
| 490 |
+
torchmetrics/image/__pycache__/rmse_sw.cpython-310.pyc,,
|
| 491 |
+
torchmetrics/image/__pycache__/sam.cpython-310.pyc,,
|
| 492 |
+
torchmetrics/image/__pycache__/scc.cpython-310.pyc,,
|
| 493 |
+
torchmetrics/image/__pycache__/ssim.cpython-310.pyc,,
|
| 494 |
+
torchmetrics/image/__pycache__/tv.cpython-310.pyc,,
|
| 495 |
+
torchmetrics/image/__pycache__/uqi.cpython-310.pyc,,
|
| 496 |
+
torchmetrics/image/__pycache__/vif.cpython-310.pyc,,
|
| 497 |
+
torchmetrics/image/_deprecated.py,sha256=V2udahUjZqO7FBoodf9FlfxbFmRHT2XymEMC2W-UGhk,8504
|
| 498 |
+
torchmetrics/image/arniqa.py,sha256=gGjqflHrL9jgsp8oa2_r-MNY2zuBOlTVo6eotLLx3aM,9242
|
| 499 |
+
torchmetrics/image/d_lambda.py,sha256=xJsrJdC83iTEAfVsd8kSmKnObu68ccZ08j0-XFGXV_4,6006
|
| 500 |
+
torchmetrics/image/d_s.py,sha256=l8MuZnTsNxHjizN_NsV97aPi-0D4ghQe5QKxtBz2J_4,9464
|
| 501 |
+
torchmetrics/image/dists.py,sha256=jvoJwZXC0Tbbht99VMXOkP_u4PgQDczY6eaDyefLqOk,5725
|
| 502 |
+
torchmetrics/image/ergas.py,sha256=NydrHyzRsjcv9D93D71JBXsezj7ZVuDXPPvYV3Hd1eA,6240
|
| 503 |
+
torchmetrics/image/fid.py,sha256=C3E2rkub7mE5nmKlnRSOC3E-GfmXv4Q8SKJL49OMLMo,22297
|
| 504 |
+
torchmetrics/image/inception.py,sha256=f_EXhcRKqjgOe14WW5b6mDZ3S3RxK_D0LNl3xr-XRgM,9235
|
| 505 |
+
torchmetrics/image/kid.py,sha256=gVbHNlh_eEnigxP5n1IT9E2tHTpfgKfMIHg7rtsfQpQ,15628
|
| 506 |
+
torchmetrics/image/lpip.py,sha256=ezWAjFgGOYJjg1KZJP6dGPeXsCumLqVwfOWx0Z2QRCk,8460
|
| 507 |
+
torchmetrics/image/mifid.py,sha256=Li_gYCsImp_DModIUFWhyYLnPXWhM87IE1mKv-ILd9o,13101
|
| 508 |
+
torchmetrics/image/perceptual_path_length.py,sha256=cCWEf1DcoiryWgV8M6G2lCuQmeSsW5fHlEi3daED0ks,8523
|
| 509 |
+
torchmetrics/image/psnr.py,sha256=eN5RmFgOpNkhKO4I-7TW_-GGfDygwm1jB0nMFLgqP7w,8512
|
| 510 |
+
torchmetrics/image/psnrb.py,sha256=QQ1mjTw8QdZy5ck6-b3Q8Gh2TcxKRPug_YszyZKlNvg,6181
|
| 511 |
+
torchmetrics/image/qnr.py,sha256=KNJSmtKPmQFoSj8SAacN9eAF-OiXA8n04B_wpfyXke4,9626
|
| 512 |
+
torchmetrics/image/rase.py,sha256=N9Ra1-978iHGldbXEXL2WhqQv2hGlGQBXW2njaPfc8Q,4945
|
| 513 |
+
torchmetrics/image/rmse_sw.py,sha256=joX_z3tlN14IS_wzWOcXzNqAM5Am0tsI09apbCxWtAk,5429
|
| 514 |
+
torchmetrics/image/sam.py,sha256=O33sxzXo7I20d4uPppTUecQU4lwIOM4XTo_747smoTg,6626
|
| 515 |
+
torchmetrics/image/scc.py,sha256=vBh-6K-TFCUnsWxoH-n5l1M363cpA57dYIu_BVA2WrI,3256
|
| 516 |
+
torchmetrics/image/ssim.py,sha256=v23wARQUV9gLQVClRKoynS7oGqn-BnCbAbIkdyU-yFY,19532
|
| 517 |
+
torchmetrics/image/tv.py,sha256=kh38dodRJ63HcImc5Svg5QrVoWFNDaJBbYBwRLnueZQ,5306
|
| 518 |
+
torchmetrics/image/uqi.py,sha256=d75vZMDVnu7DVoBayMT6BjVtf35qKjf0NsDScD_4Y2Y,6843
|
| 519 |
+
torchmetrics/image/vif.py,sha256=_yVSXc0I4OjDqjvs5ljlc0nRzYH16VIRHAaIPF-l6Js,4206
|
| 520 |
+
torchmetrics/metric.py,sha256=jcUIo3QWFG6Dkv3BEBitjIm0GL52VfmiAG4MSBlzoPo,57049
|
| 521 |
+
torchmetrics/multimodal/__init__.py,sha256=GFq8rL-QwcrP4Z4jGc0rIdoSzSMUF6O7a1Ee9hca854,974
|
| 522 |
+
torchmetrics/multimodal/__pycache__/__init__.cpython-310.pyc,,
|
| 523 |
+
torchmetrics/multimodal/__pycache__/clip_iqa.cpython-310.pyc,,
|
| 524 |
+
torchmetrics/multimodal/__pycache__/clip_score.cpython-310.pyc,,
|
| 525 |
+
torchmetrics/multimodal/__pycache__/lve.cpython-310.pyc,,
|
| 526 |
+
torchmetrics/multimodal/clip_iqa.py,sha256=ELuh7dqrvhp3D1wZHv86RKTIzVJUoDGJjwvJL8cOkLU,11924
|
| 527 |
+
torchmetrics/multimodal/clip_score.py,sha256=PmslChrtknb-Qo1kfa5g6Wv4GVQE7bE_CmKB6ryf0vs,10941
|
| 528 |
+
torchmetrics/multimodal/lve.py,sha256=RSZGmjtLUTvKgB19-diBROqsABYJlGrvHJuIItk3IWo,8358
|
| 529 |
+
torchmetrics/nominal/__init__.py,sha256=-AbpLuTpceUjVMJz2AQLMY_nnXJJsry75B0hXk2Zkbo,987
|
| 530 |
+
torchmetrics/nominal/__pycache__/__init__.cpython-310.pyc,,
|
| 531 |
+
torchmetrics/nominal/__pycache__/cramers.cpython-310.pyc,,
|
| 532 |
+
torchmetrics/nominal/__pycache__/fleiss_kappa.cpython-310.pyc,,
|
| 533 |
+
torchmetrics/nominal/__pycache__/pearson.cpython-310.pyc,,
|
| 534 |
+
torchmetrics/nominal/__pycache__/theils_u.cpython-310.pyc,,
|
| 535 |
+
torchmetrics/nominal/__pycache__/tschuprows.cpython-310.pyc,,
|
| 536 |
+
torchmetrics/nominal/cramers.py,sha256=tuSme3YICwkOLBHQfYizF_lls5w8WqN7E5spBhTFPjA,6272
|
| 537 |
+
torchmetrics/nominal/fleiss_kappa.py,sha256=x7v-mzB5bOLLnTdfoQBkjZTeq4g6Bsonc2o-cJ_J7IA,5664
|
| 538 |
+
torchmetrics/nominal/pearson.py,sha256=gocfEjREFXEJCnZu53cht2IV-n7XNmfrITvsKhsxIcI,6567
|
| 539 |
+
torchmetrics/nominal/theils_u.py,sha256=XjSIcRZwjexE8gZYlYd1GQSCshEstGHgNSUx61qUn_U,5798
|
| 540 |
+
torchmetrics/nominal/tschuprows.py,sha256=H0O-m-Zec_dX3ld4JAHzyaNdww93Rg6LXsSKPMEkQIY,6337
|
| 541 |
+
torchmetrics/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 542 |
+
torchmetrics/regression/__init__.py,sha256=SmayrB6S4UstfYTY7HHgaxA2nwMJwMeF-7PvFdyXb2Y,2675
|
| 543 |
+
torchmetrics/regression/__pycache__/__init__.cpython-310.pyc,,
|
| 544 |
+
torchmetrics/regression/__pycache__/concordance.cpython-310.pyc,,
|
| 545 |
+
torchmetrics/regression/__pycache__/cosine_similarity.cpython-310.pyc,,
|
| 546 |
+
torchmetrics/regression/__pycache__/crps.cpython-310.pyc,,
|
| 547 |
+
torchmetrics/regression/__pycache__/csi.cpython-310.pyc,,
|
| 548 |
+
torchmetrics/regression/__pycache__/explained_variance.cpython-310.pyc,,
|
| 549 |
+
torchmetrics/regression/__pycache__/js_divergence.cpython-310.pyc,,
|
| 550 |
+
torchmetrics/regression/__pycache__/kendall.cpython-310.pyc,,
|
| 551 |
+
torchmetrics/regression/__pycache__/kl_divergence.cpython-310.pyc,,
|
| 552 |
+
torchmetrics/regression/__pycache__/log_cosh.cpython-310.pyc,,
|
| 553 |
+
torchmetrics/regression/__pycache__/log_mse.cpython-310.pyc,,
|
| 554 |
+
torchmetrics/regression/__pycache__/mae.cpython-310.pyc,,
|
| 555 |
+
torchmetrics/regression/__pycache__/mape.cpython-310.pyc,,
|
| 556 |
+
torchmetrics/regression/__pycache__/minkowski.cpython-310.pyc,,
|
| 557 |
+
torchmetrics/regression/__pycache__/mse.cpython-310.pyc,,
|
| 558 |
+
torchmetrics/regression/__pycache__/nrmse.cpython-310.pyc,,
|
| 559 |
+
torchmetrics/regression/__pycache__/pearson.cpython-310.pyc,,
|
| 560 |
+
torchmetrics/regression/__pycache__/r2.cpython-310.pyc,,
|
| 561 |
+
torchmetrics/regression/__pycache__/rse.cpython-310.pyc,,
|
| 562 |
+
torchmetrics/regression/__pycache__/spearman.cpython-310.pyc,,
|
| 563 |
+
torchmetrics/regression/__pycache__/symmetric_mape.cpython-310.pyc,,
|
| 564 |
+
torchmetrics/regression/__pycache__/tweedie_deviance.cpython-310.pyc,,
|
| 565 |
+
torchmetrics/regression/__pycache__/wmape.cpython-310.pyc,,
|
| 566 |
+
torchmetrics/regression/concordance.py,sha256=OQBtHYgFxY_qxGxd_lK_WHqK81eszaogMy1INRzVEBY,5841
|
| 567 |
+
torchmetrics/regression/cosine_similarity.py,sha256=a0BEQP0iZY4Qu4CjEW9DqSq4S5_Xuw9Z929SumUltPI,5235
|
| 568 |
+
torchmetrics/regression/crps.py,sha256=Hfhe4_xqmOLFdwJpgChdQohyOqNHUHj5k0VUAqlmrnM,5096
|
| 569 |
+
torchmetrics/regression/csi.py,sha256=RJuh0_bSRyI7cuY4atVuuO7YdDbdEFOshdjdRGpfFRI,4792
|
| 570 |
+
torchmetrics/regression/explained_variance.py,sha256=A5ml_rvQpHUuDcA8wXoMqy2EIi2IvKPE_lkpnEO2J98,6948
|
| 571 |
+
torchmetrics/regression/js_divergence.py,sha256=T36I89jXCsSHYN8SetF0BzqQ5BvV6EnviWgWl8pZkT8,6775
|
| 572 |
+
torchmetrics/regression/kendall.py,sha256=afAcigwQwfuXoGIJoDqMU05Cmwx51wVTy4PIQUvz1Yc,8278
|
| 573 |
+
torchmetrics/regression/kl_divergence.py,sha256=a9_KYNLcMX01gpY4z8Entt1pkuGdFAvnFsbwelzX5Xc,6672
|
| 574 |
+
torchmetrics/regression/log_cosh.py,sha256=5vkae4AqkJtEz_6W4BvtA8tLgHCu3nbvY-Fovxm44wE,5440
|
| 575 |
+
torchmetrics/regression/log_mse.py,sha256=AEyNbkwNrDUQ6ZEAQ7tTbGn5k6asvWR4H3i1NiMEp4c,4720
|
| 576 |
+
torchmetrics/regression/mae.py,sha256=a3tDZxZu_JrIo5-d7SxGlyXsXrIE4reE4fH-Z7flAe0,5307
|
| 577 |
+
torchmetrics/regression/mape.py,sha256=SgekTYO9jJzNDSBJQVOIaROM7DJ8ROFoSm26kkVg2_w,5094
|
| 578 |
+
torchmetrics/regression/minkowski.py,sha256=KnzYJ8jTSwtlPjyNgbYqaBnI4tU7-fTS7G1cGugGgPE,4603
|
| 579 |
+
torchmetrics/regression/mse.py,sha256=wpuUpCfpvnL2-dl0kXHlYzlj8Xz7bNG3VGjsYXHuJUk,5609
|
| 580 |
+
torchmetrics/regression/nrmse.py,sha256=bH7UWG0yJyRNTE2wI9SCrjzCnL8Y5CTX-FRBstTzXoc,10852
|
| 581 |
+
torchmetrics/regression/pearson.py,sha256=u0zeqKtdkoeDaJzyzrKOSd48PvfRBL0b6Ds4AMlHrkI,9769
|
| 582 |
+
torchmetrics/regression/r2.py,sha256=LXCqIE7IAgX3-ScpBYb4ZteQz3nXshZPqnMX83-KCSo,7741
|
| 583 |
+
torchmetrics/regression/rse.py,sha256=EMH0_8wCvULpo1lazBrYZ3BZ3rZA-OVbtGjV9bhA8Ig,5470
|
| 584 |
+
torchmetrics/regression/spearman.py,sha256=dKA9h1qRzp02jtcyFDp-QoeF2FDmfHlCaWswytUwr2E,5810
|
| 585 |
+
torchmetrics/regression/symmetric_mape.py,sha256=Uh_3hQfzGsK6C_feQHeKM718sEKj9paxj-a6K1aEoDg,4855
|
| 586 |
+
torchmetrics/regression/tweedie_deviance.py,sha256=IVHg6nVBEc5j6NuRd9IZlVp5yyxM4ndV3eIlCvdafZ0,5919
|
| 587 |
+
torchmetrics/regression/wmape.py,sha256=205orI6kavTLXE9mdqPuX1bjVtFVazIIhELu8p0g8k0,4848
|
| 588 |
+
torchmetrics/retrieval/__init__.py,sha256=j8ra86FDGJa_lcZDt6VBn45-iQ_Ew3fFVAnYrsedWHY,1566
|
| 589 |
+
torchmetrics/retrieval/__pycache__/__init__.cpython-310.pyc,,
|
| 590 |
+
torchmetrics/retrieval/__pycache__/_deprecated.cpython-310.pyc,,
|
| 591 |
+
torchmetrics/retrieval/__pycache__/auroc.cpython-310.pyc,,
|
| 592 |
+
torchmetrics/retrieval/__pycache__/average_precision.cpython-310.pyc,,
|
| 593 |
+
torchmetrics/retrieval/__pycache__/base.cpython-310.pyc,,
|
| 594 |
+
torchmetrics/retrieval/__pycache__/fall_out.cpython-310.pyc,,
|
| 595 |
+
torchmetrics/retrieval/__pycache__/hit_rate.cpython-310.pyc,,
|
| 596 |
+
torchmetrics/retrieval/__pycache__/ndcg.cpython-310.pyc,,
|
| 597 |
+
torchmetrics/retrieval/__pycache__/precision.cpython-310.pyc,,
|
| 598 |
+
torchmetrics/retrieval/__pycache__/precision_recall_curve.cpython-310.pyc,,
|
| 599 |
+
torchmetrics/retrieval/__pycache__/r_precision.cpython-310.pyc,,
|
| 600 |
+
torchmetrics/retrieval/__pycache__/recall.cpython-310.pyc,,
|
| 601 |
+
torchmetrics/retrieval/__pycache__/reciprocal_rank.cpython-310.pyc,,
|
| 602 |
+
torchmetrics/retrieval/_deprecated.py,sha256=nFRag3cnGTSOfEuk5NhIgIzG0vBIosxCMqJdBxf4yCY,9222
|
| 603 |
+
torchmetrics/retrieval/auroc.py,sha256=r_37wzE7NYsMcW-82UQiDKeHt5Q0bgr52xiqeDBfwqg,7001
|
| 604 |
+
torchmetrics/retrieval/average_precision.py,sha256=JOieRB7hh-oP0Isnazc_UoIbBlKfsK6ixyWjYWJDTqc,6567
|
| 605 |
+
torchmetrics/retrieval/base.py,sha256=Wh5U6kXi0-qSfZyZfWQBt6MKw6OYufZ8-IsRED28FY0,8043
|
| 606 |
+
torchmetrics/retrieval/fall_out.py,sha256=NNbBuhc-nSOxIKfdcoTTr3ABiDI2f2ZaDLA0872c6vE,8186
|
| 607 |
+
torchmetrics/retrieval/hit_rate.py,sha256=yMXY_aMuaTCsnMJADls1rQt6YgjFE56-QeXYnXHGd40,6538
|
| 608 |
+
torchmetrics/retrieval/ndcg.py,sha256=TeT1vWlZ-pdv4PKYEWgff7eqFvOVF3ljfYhgegSdKSM,6664
|
| 609 |
+
torchmetrics/retrieval/precision.py,sha256=E1wFVBNMX4BcYYf0iUxA2Ld3SvnE9WJGPu4Wt4DSoLg,6919
|
| 610 |
+
torchmetrics/retrieval/precision_recall_curve.py,sha256=6z6SMA6SOsox_0gdMwGcp-Kb3uJU7lPgglg4o147TAQ,17893
|
| 611 |
+
torchmetrics/retrieval/r_precision.py,sha256=OV6Q6vyLVjY3nhbyksRD_damTr-a1ljXZq2VlrtkBoU,5627
|
| 612 |
+
torchmetrics/retrieval/recall.py,sha256=-8Xsyxto8e0m8cYuL531PUgjTtwN5U500owDcI5YsBk,6516
|
| 613 |
+
torchmetrics/retrieval/reciprocal_rank.py,sha256=vjee2uUpUXeRt68MsGW8WfwRlO6-bUFM6Ee06LEUMWs,6557
|
| 614 |
+
torchmetrics/segmentation/__init__.py,sha256=3Xht3JWQYpfc3hR8wp-EbxVdTTtm1P9aG6LRz_UoA8c,918
|
| 615 |
+
torchmetrics/segmentation/__pycache__/__init__.cpython-310.pyc,,
|
| 616 |
+
torchmetrics/segmentation/__pycache__/dice.cpython-310.pyc,,
|
| 617 |
+
torchmetrics/segmentation/__pycache__/generalized_dice.cpython-310.pyc,,
|
| 618 |
+
torchmetrics/segmentation/__pycache__/hausdorff_distance.cpython-310.pyc,,
|
| 619 |
+
torchmetrics/segmentation/__pycache__/mean_iou.cpython-310.pyc,,
|
| 620 |
+
torchmetrics/segmentation/dice.py,sha256=d_OWYTGajcooqjP7da1hd__Lo-o12ehEU_LEUTlLccM,9079
|
| 621 |
+
torchmetrics/segmentation/generalized_dice.py,sha256=WoKTcjdGyJNhkhvZxSxzKchyDDkyc31jHT3-hyM_Xtc,8423
|
| 622 |
+
torchmetrics/segmentation/hausdorff_distance.py,sha256=PGTJlIcd5lkqI34sZL4nZOeIQGOEHIUM14SY4Gbpwlo,6989
|
| 623 |
+
torchmetrics/segmentation/mean_iou.py,sha256=SbB2u8VCBDLJc-vDpymYQawrjFbi02IjwMGUrtJKTT4,10539
|
| 624 |
+
torchmetrics/shape/__init__.py,sha256=geZDESOmNmoZ_5IZZofbTJlOorwgBqh6liklsX1Q-0k,675
|
| 625 |
+
torchmetrics/shape/__pycache__/__init__.cpython-310.pyc,,
|
| 626 |
+
torchmetrics/shape/__pycache__/procrustes.cpython-310.pyc,,
|
| 627 |
+
torchmetrics/shape/procrustes.py,sha256=vO6at_AV6d2GV1hrsqyxQ4O5-NcLDJ0HTiQmmJBl9MI,5734
|
| 628 |
+
torchmetrics/text/__init__.py,sha256=5VeA0U0_AF-00-kP-G-PyVDOjnxnsTkgjZu4FI_oBUk,1819
|
| 629 |
+
torchmetrics/text/__pycache__/__init__.cpython-310.pyc,,
|
| 630 |
+
torchmetrics/text/__pycache__/_deprecated.cpython-310.pyc,,
|
| 631 |
+
torchmetrics/text/__pycache__/bert.cpython-310.pyc,,
|
| 632 |
+
torchmetrics/text/__pycache__/bleu.cpython-310.pyc,,
|
| 633 |
+
torchmetrics/text/__pycache__/cer.cpython-310.pyc,,
|
| 634 |
+
torchmetrics/text/__pycache__/chrf.cpython-310.pyc,,
|
| 635 |
+
torchmetrics/text/__pycache__/edit.cpython-310.pyc,,
|
| 636 |
+
torchmetrics/text/__pycache__/eed.cpython-310.pyc,,
|
| 637 |
+
torchmetrics/text/__pycache__/infolm.cpython-310.pyc,,
|
| 638 |
+
torchmetrics/text/__pycache__/mer.cpython-310.pyc,,
|
| 639 |
+
torchmetrics/text/__pycache__/perplexity.cpython-310.pyc,,
|
| 640 |
+
torchmetrics/text/__pycache__/rouge.cpython-310.pyc,,
|
| 641 |
+
torchmetrics/text/__pycache__/sacre_bleu.cpython-310.pyc,,
|
| 642 |
+
torchmetrics/text/__pycache__/squad.cpython-310.pyc,,
|
| 643 |
+
torchmetrics/text/__pycache__/ter.cpython-310.pyc,,
|
| 644 |
+
torchmetrics/text/__pycache__/wer.cpython-310.pyc,,
|
| 645 |
+
torchmetrics/text/__pycache__/wil.cpython-310.pyc,,
|
| 646 |
+
torchmetrics/text/__pycache__/wip.cpython-310.pyc,,
|
| 647 |
+
torchmetrics/text/_deprecated.py,sha256=HGgPtmnq5_2Zqxi3EqfnXvTXXGi6JA3CZntym2xL0ow,8229
|
| 648 |
+
torchmetrics/text/bert.py,sha256=Y4miLqw_I4YmOrKOWjmSq0ssMuO1K_1AUuz0GEgx8tQ,16684
|
| 649 |
+
torchmetrics/text/bleu.py,sha256=WwkBFYVZ6jjoLltbR-djdy9kPFcgB7gC6qIyy-osY4k,5884
|
| 650 |
+
torchmetrics/text/cer.py,sha256=TWRmAvOz6WqqvPgfFKPVPvM7emBoGhpPnBT03XX6O_k,5307
|
| 651 |
+
torchmetrics/text/chrf.py,sha256=C80Jg4l7lhB3eYTe3FDbny62duohgN10sLZSVHLMzbU,10490
|
| 652 |
+
torchmetrics/text/edit.py,sha256=j1fk-57mcP577vj7H23UfHF7HqW4Rhxj1JsGPFsBnrk,7369
|
| 653 |
+
torchmetrics/text/eed.py,sha256=BRIWrDKYgexoZkd-97nmrTrBiekN4ZQpV_DBPMjbbvQ,6381
|
| 654 |
+
torchmetrics/text/infolm.py,sha256=4HzPIahF7sWJ_Bj8WYME18QRD-xEBTc6gKP1qkitF1E,10949
|
| 655 |
+
torchmetrics/text/mer.py,sha256=Rzq6kea3q2K6Te8TxrE6nj-I4I3pp7uI1yagSHS5JX8,5250
|
| 656 |
+
torchmetrics/text/perplexity.py,sha256=RXaUg75kbwGDUIYeicAx7W49deTT1BJbivdGzXCXnwo,5019
|
| 657 |
+
torchmetrics/text/rouge.py,sha256=H_HHPe-ZQ3PyaDgiBbLYCNy_Di-N_8hw6HxXwAxIzI8,9412
|
| 658 |
+
torchmetrics/text/sacre_bleu.py,sha256=PqGRvq9iGexmipUG9hbIVGBYjmPrwJOdublR7dViA2c,7188
|
| 659 |
+
torchmetrics/text/squad.py,sha256=ebACHcgDciqKlJiJuU6NXAFdVmNaUt9n6YR33OX46PQ,6066
|
| 660 |
+
torchmetrics/text/ter.py,sha256=yLpNLa5F-wW5cExjMtocfg48Md9Qw88_aoxeKAEH0fM,6765
|
| 661 |
+
torchmetrics/text/wer.py,sha256=F_54E-BL68GZw0Ni2cMkfyTqX5_56xj7f23Gab0rhes,5232
|
| 662 |
+
torchmetrics/text/wil.py,sha256=zf0xuWcHt5Vsfw8_sUW-THMviRCesyRGTetBtFfj9rM,5359
|
| 663 |
+
torchmetrics/text/wip.py,sha256=dPR8YiszbJesfti30G8JuyZD0yYeW8t7DbEM-cPEW7o,5380
|
| 664 |
+
torchmetrics/utilities/__init__.py,sha256=NM33fJ7MrGne7df6F4OYY9x59IeIWirkdMU5K9Q2Js4,1205
|
| 665 |
+
torchmetrics/utilities/__pycache__/__init__.cpython-310.pyc,,
|
| 666 |
+
torchmetrics/utilities/__pycache__/checks.cpython-310.pyc,,
|
| 667 |
+
torchmetrics/utilities/__pycache__/compute.cpython-310.pyc,,
|
| 668 |
+
torchmetrics/utilities/__pycache__/data.cpython-310.pyc,,
|
| 669 |
+
torchmetrics/utilities/__pycache__/distributed.cpython-310.pyc,,
|
| 670 |
+
torchmetrics/utilities/__pycache__/enums.cpython-310.pyc,,
|
| 671 |
+
torchmetrics/utilities/__pycache__/exceptions.cpython-310.pyc,,
|
| 672 |
+
torchmetrics/utilities/__pycache__/imports.cpython-310.pyc,,
|
| 673 |
+
torchmetrics/utilities/__pycache__/plot.cpython-310.pyc,,
|
| 674 |
+
torchmetrics/utilities/__pycache__/prints.cpython-310.pyc,,
|
| 675 |
+
torchmetrics/utilities/checks.py,sha256=qbrocKIIILEQN7pmy9jWbKcMbdKBBsyL1Sy1qRHGtLc,12885
|
| 676 |
+
torchmetrics/utilities/compute.py,sha256=bv33DfL4Bn3jsv999p0gvSJThhTXnWFzE0I6E2vi-jg,8319
|
| 677 |
+
torchmetrics/utilities/data.py,sha256=p461ppdb5Jxcdc4bHPx4zf1XqMZxh_xsp9zRh-pi6k4,9071
|
| 678 |
+
torchmetrics/utilities/distributed.py,sha256=88GtCrH_xIqg_odhI7_6vz4O3-El9INdvJjHmY3O7yQ,6146
|
| 679 |
+
torchmetrics/utilities/enums.py,sha256=8i7ivcvC5kh8wB10IJZd5q5KkROodKhcYK0c2lIf2aU,3688
|
| 680 |
+
torchmetrics/utilities/exceptions.py,sha256=VMl06AQRg-CjJnkKfWw_XXe11ajlm2I0XiXCi0knZTM,830
|
| 681 |
+
torchmetrics/utilities/imports.py,sha256=59iPLS8g5oh9xc3Alz5UAznFnQ7j8Bnu1IoJ-jmVlpc,3412
|
| 682 |
+
torchmetrics/utilities/plot.py,sha256=AjWBQlXbxDOIpbVZZ0BdXw--OhgUsptGBNpwtRjsKFk,14461
|
| 683 |
+
torchmetrics/utilities/prints.py,sha256=H0kAnHRILObNdOEglHsFS8G6MCJ4uaumyrdzKhpGVKo,2368
|
| 684 |
+
torchmetrics/video/__init__.py,sha256=t6gSl7eQk8zyIFuwxnx01AtxihVMajDK4cSp-71c-Vg,810
|
| 685 |
+
torchmetrics/video/__pycache__/__init__.cpython-310.pyc,,
|
| 686 |
+
torchmetrics/video/__pycache__/vmaf.cpython-310.pyc,,
|
| 687 |
+
torchmetrics/video/vmaf.py,sha256=U8dR_b9jUhgsUIcGnXlQ3D_7437M0RT7WLN_-QpHz80,10016
|
| 688 |
+
torchmetrics/wrappers/__init__.py,sha256=_9AfQDwrHrnm3itZIy7xlw6NB9t6aVLgnIgaGwq4CgQ,1462
|
| 689 |
+
torchmetrics/wrappers/__pycache__/__init__.cpython-310.pyc,,
|
| 690 |
+
torchmetrics/wrappers/__pycache__/abstract.cpython-310.pyc,,
|
| 691 |
+
torchmetrics/wrappers/__pycache__/bootstrapping.cpython-310.pyc,,
|
| 692 |
+
torchmetrics/wrappers/__pycache__/classwise.cpython-310.pyc,,
|
| 693 |
+
torchmetrics/wrappers/__pycache__/feature_share.cpython-310.pyc,,
|
| 694 |
+
torchmetrics/wrappers/__pycache__/minmax.cpython-310.pyc,,
|
| 695 |
+
torchmetrics/wrappers/__pycache__/multioutput.cpython-310.pyc,,
|
| 696 |
+
torchmetrics/wrappers/__pycache__/multitask.cpython-310.pyc,,
|
| 697 |
+
torchmetrics/wrappers/__pycache__/running.cpython-310.pyc,,
|
| 698 |
+
torchmetrics/wrappers/__pycache__/tracker.cpython-310.pyc,,
|
| 699 |
+
torchmetrics/wrappers/__pycache__/transformations.cpython-310.pyc,,
|
| 700 |
+
torchmetrics/wrappers/abstract.py,sha256=W74Qd23mi2qbOaQ6AvfyiZXi3AzEpsFPR5WZOxj_MX4,1855
|
| 701 |
+
torchmetrics/wrappers/bootstrapping.py,sha256=C0ztxgGH2P0k09AzILAgqwx3t0H4lNLbE6zkuB4yDnA,9075
|
| 702 |
+
torchmetrics/wrappers/classwise.py,sha256=saeaD2ZehxWcJH4RATRJ-Ei_soas0Z3oqqAxwyhKt2Q,10520
|
| 703 |
+
torchmetrics/wrappers/feature_share.py,sha256=yVEC15r3qDdT9__5LgQuQe7PCjJcJNd7htXvRU6PJwA,6593
|
| 704 |
+
torchmetrics/wrappers/minmax.py,sha256=D_1EsMeHMZUcfu4qYjzu2PBHj_kAKVFivNymWl38YsU,6262
|
| 705 |
+
torchmetrics/wrappers/multioutput.py,sha256=Z2nUuk8NoYEUDrXxqa4MlESB54Zjl6mW6B-ab3ROogY,9584
|
| 706 |
+
torchmetrics/wrappers/multitask.py,sha256=xIt_8z8LlxdRbhV2EJeacuG8gjuMipeqI7Ekc2qyjTg,18398
|
| 707 |
+
torchmetrics/wrappers/running.py,sha256=K9ZU0eIkOW_fa8YCHiNMK2H_uN91DcTxpM3Gu-OGYZI,8362
|
| 708 |
+
torchmetrics/wrappers/tracker.py,sha256=-OalxU2YI0aXNykoCaK42rAizCQQae0ttPjSC0HVOIY,18135
|
| 709 |
+
torchmetrics/wrappers/transformations.py,sha256=y5THlNsdC1kpfrN9CcxyOd5tNhCc9xBm2ur4qxr1yGE,7083
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (82.0.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright 2020-2022 Lightning-AI team
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics-1.9.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
torchmetrics
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/sam.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
from torchmetrics.utilities.distributed import reduce
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _sam_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
|
| 24 |
+
"""Update and returns variables required to compute Spectral Angle Mapper.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
preds: Predicted tensor
|
| 28 |
+
target: Ground truth tensor
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
if preds.dtype != target.dtype:
|
| 32 |
+
raise TypeError(
|
| 33 |
+
"Expected `preds` and `target` to have the same data type."
|
| 34 |
+
f" Got preds: {preds.dtype} and target: {target.dtype}."
|
| 35 |
+
)
|
| 36 |
+
_check_same_shape(preds, target)
|
| 37 |
+
if len(preds.shape) != 4:
|
| 38 |
+
raise ValueError(
|
| 39 |
+
f"Expected `preds` and `target` to have BxCxHxW shape. Got preds: {preds.shape} and target: {target.shape}."
|
| 40 |
+
)
|
| 41 |
+
if (preds.shape[1] <= 1) or (target.shape[1] <= 1):
|
| 42 |
+
raise ValueError(
|
| 43 |
+
"Expected channel dimension of `preds` and `target` to be larger than 1."
|
| 44 |
+
f" Got preds: {preds.shape[1]} and target: {target.shape[1]}."
|
| 45 |
+
)
|
| 46 |
+
return preds, target
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _sam_compute(
|
| 50 |
+
preds: Tensor,
|
| 51 |
+
target: Tensor,
|
| 52 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 53 |
+
) -> Tensor:
|
| 54 |
+
"""Compute Spectral Angle Mapper.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
preds: estimated image
|
| 58 |
+
target: ground truth image
|
| 59 |
+
reduction: a method to reduce metric score over labels.
|
| 60 |
+
|
| 61 |
+
- ``'elementwise_mean'``: takes the mean (default)
|
| 62 |
+
- ``'sum'``: takes the sum
|
| 63 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 64 |
+
|
| 65 |
+
Example:
|
| 66 |
+
>>> from torch import rand
|
| 67 |
+
>>> preds = rand([16, 3, 16, 16])
|
| 68 |
+
>>> target = rand([16, 3, 16, 16])
|
| 69 |
+
>>> preds, target = _sam_update(preds, target)
|
| 70 |
+
>>> _sam_compute(preds, target)
|
| 71 |
+
tensor(0.5914)
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
dot_product = (preds * target).sum(dim=1)
|
| 75 |
+
preds_norm = preds.norm(dim=1)
|
| 76 |
+
target_norm = target.norm(dim=1)
|
| 77 |
+
sam_score = torch.clamp(dot_product / (preds_norm * target_norm), -1, 1).acos()
|
| 78 |
+
return reduce(sam_score, reduction)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def spectral_angle_mapper(
|
| 82 |
+
preds: Tensor,
|
| 83 |
+
target: Tensor,
|
| 84 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 85 |
+
) -> Tensor:
|
| 86 |
+
"""Universal Spectral Angle Mapper.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
preds: estimated image
|
| 90 |
+
target: ground truth image
|
| 91 |
+
reduction: a method to reduce metric score over labels.
|
| 92 |
+
|
| 93 |
+
- ``'elementwise_mean'``: takes the mean (default)
|
| 94 |
+
- ``'sum'``: takes the sum
|
| 95 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 96 |
+
|
| 97 |
+
Return:
|
| 98 |
+
Tensor with Spectral Angle Mapper score
|
| 99 |
+
|
| 100 |
+
Raises:
|
| 101 |
+
TypeError:
|
| 102 |
+
If ``preds`` and ``target`` don't have the same data type.
|
| 103 |
+
ValueError:
|
| 104 |
+
If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
|
| 105 |
+
|
| 106 |
+
Example:
|
| 107 |
+
>>> from torch import rand
|
| 108 |
+
>>> from torchmetrics.functional.image import spectral_angle_mapper
|
| 109 |
+
>>> preds = rand([16, 3, 16, 16],)
|
| 110 |
+
>>> target = rand([16, 3, 16, 16])
|
| 111 |
+
>>> spectral_angle_mapper(preds, target)
|
| 112 |
+
tensor(0.5914)
|
| 113 |
+
|
| 114 |
+
References:
|
| 115 |
+
[1] Roberta H. Yuhas, Alexander F. H. Goetz and Joe W. Boardman, "Discrimination among semi-arid
|
| 116 |
+
landscape endmembers using the Spectral Angle Mapper (SAM) algorithm" in PL, Summaries of the Third Annual JPL
|
| 117 |
+
Airborne Geoscience Workshop, vol. 1, June 1, 1992.
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
preds, target = _sam_update(preds, target)
|
| 121 |
+
return _sam_compute(preds, target, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/scc.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import math
|
| 15 |
+
from typing import Optional, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor, tensor
|
| 19 |
+
from torch.nn.functional import conv2d, pad
|
| 20 |
+
from typing_extensions import Literal
|
| 21 |
+
|
| 22 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 23 |
+
from torchmetrics.utilities.distributed import reduce
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _scc_update(preds: Tensor, target: Tensor, hp_filter: Tensor, window_size: int) -> tuple[Tensor, Tensor, Tensor]:
|
| 27 |
+
"""Update and returns variables required to compute Spatial Correlation Coefficient.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
preds: Predicted tensor
|
| 31 |
+
target: Ground truth tensor
|
| 32 |
+
hp_filter: High-pass filter tensor
|
| 33 |
+
window_size: Local window size integer
|
| 34 |
+
|
| 35 |
+
Return:
|
| 36 |
+
Tuple of (preds, target, hp_filter) tensors
|
| 37 |
+
|
| 38 |
+
Raises:
|
| 39 |
+
ValueError:
|
| 40 |
+
If ``preds`` and ``target`` have different number of channels
|
| 41 |
+
If ``preds`` and ``target`` have different shapes
|
| 42 |
+
If ``preds`` and ``target`` have invalid shapes
|
| 43 |
+
If ``window_size`` is not a positive integer
|
| 44 |
+
If ``window_size`` is greater than the size of the image
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
if preds.dtype != target.dtype:
|
| 48 |
+
target = target.to(preds.dtype)
|
| 49 |
+
_check_same_shape(preds, target)
|
| 50 |
+
if preds.ndim not in (3, 4):
|
| 51 |
+
raise ValueError(
|
| 52 |
+
"Expected `preds` and `target` to have batch of colored images with BxCxHxW shape"
|
| 53 |
+
" or batch of grayscale images of BxHxW shape."
|
| 54 |
+
f" Got preds: {preds.shape} and target: {target.shape}."
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if len(preds.shape) == 3:
|
| 58 |
+
preds = preds.unsqueeze(1)
|
| 59 |
+
target = target.unsqueeze(1)
|
| 60 |
+
|
| 61 |
+
if not window_size > 0:
|
| 62 |
+
raise ValueError(f"Expected `window_size` to be a positive integer. Got {window_size}.")
|
| 63 |
+
|
| 64 |
+
if window_size > preds.size(2) or window_size > preds.size(3):
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"Expected `window_size` to be less than or equal to the size of the image."
|
| 67 |
+
f" Got window_size: {window_size} and image size: {preds.size(2)}x{preds.size(3)}."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
preds = preds.to(torch.float32)
|
| 71 |
+
target = target.to(torch.float32)
|
| 72 |
+
hp_filter = hp_filter[None, None, :].to(dtype=preds.dtype, device=preds.device)
|
| 73 |
+
return preds, target, hp_filter
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _symmetric_reflect_pad_2d(input_img: Tensor, pad: Union[int, tuple[int, ...]]) -> Tensor:
|
| 77 |
+
"""Applies symmetric padding to the 2D image tensor input using ``reflect`` mode (d c b a | a b c d | d c b a)."""
|
| 78 |
+
if isinstance(pad, int):
|
| 79 |
+
pad = (pad, pad, pad, pad)
|
| 80 |
+
if len(pad) != 4:
|
| 81 |
+
raise ValueError(f"Expected padding to have length 4, but got {len(pad)}")
|
| 82 |
+
|
| 83 |
+
left_pad = input_img[:, :, :, 0 : pad[0]].flip(dims=[3])
|
| 84 |
+
right_pad = input_img[:, :, :, -pad[1] :].flip(dims=[3])
|
| 85 |
+
padded = torch.cat([left_pad, input_img, right_pad], dim=3)
|
| 86 |
+
|
| 87 |
+
top_pad = padded[:, :, 0 : pad[2], :].flip(dims=[2])
|
| 88 |
+
bottom_pad = padded[:, :, -pad[3] :, :].flip(dims=[2])
|
| 89 |
+
return torch.cat([top_pad, padded, bottom_pad], dim=2)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _signal_convolve_2d(input_img: Tensor, kernel: Tensor) -> Tensor:
|
| 93 |
+
"""Applies 2D signal convolution to the input tensor with the given kernel."""
|
| 94 |
+
left_padding = math.floor((kernel.size(3) - 1) / 2)
|
| 95 |
+
right_padding = math.ceil((kernel.size(3) - 1) / 2)
|
| 96 |
+
top_padding = math.floor((kernel.size(2) - 1) / 2)
|
| 97 |
+
bottom_padding = math.ceil((kernel.size(2) - 1) / 2)
|
| 98 |
+
|
| 99 |
+
padded = _symmetric_reflect_pad_2d(input_img, pad=(left_padding, right_padding, top_padding, bottom_padding))
|
| 100 |
+
kernel = kernel.flip([2, 3])
|
| 101 |
+
return conv2d(padded, kernel, stride=1, padding=0)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _hp_2d_laplacian(input_img: Tensor, kernel: Tensor) -> Tensor:
|
| 105 |
+
"""Applies 2-D Laplace filter to the input tensor with the given high pass filter."""
|
| 106 |
+
return _signal_convolve_2d(input_img, kernel) * 2.0
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _local_variance_covariance(preds: Tensor, target: Tensor, window: Tensor) -> tuple[Tensor, Tensor, Tensor]:
|
| 110 |
+
"""Computes local variance and covariance of the input tensors."""
|
| 111 |
+
# This code is inspired by
|
| 112 |
+
# https://github.com/andrewekhalel/sewar/blob/master/sewar/full_ref.py#L187.
|
| 113 |
+
|
| 114 |
+
left_padding = math.ceil((window.size(3) - 1) / 2)
|
| 115 |
+
right_padding = math.floor((window.size(3) - 1) / 2)
|
| 116 |
+
|
| 117 |
+
preds = pad(preds, (left_padding, right_padding, left_padding, right_padding))
|
| 118 |
+
target = pad(target, (left_padding, right_padding, left_padding, right_padding))
|
| 119 |
+
|
| 120 |
+
preds_mean = conv2d(preds, window, stride=1, padding=0)
|
| 121 |
+
target_mean = conv2d(target, window, stride=1, padding=0)
|
| 122 |
+
|
| 123 |
+
preds_var = conv2d(preds**2, window, stride=1, padding=0) - preds_mean**2
|
| 124 |
+
target_var = conv2d(target**2, window, stride=1, padding=0) - target_mean**2
|
| 125 |
+
target_preds_cov = conv2d(target * preds, window, stride=1, padding=0) - target_mean * preds_mean
|
| 126 |
+
|
| 127 |
+
return preds_var, target_var, target_preds_cov
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _scc_per_channel_compute(preds: Tensor, target: Tensor, hp_filter: Tensor, window_size: int) -> Tensor:
|
| 131 |
+
"""Computes per channel Spatial Correlation Coefficient.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
preds: estimated image of Bx1xHxW shape.
|
| 135 |
+
target: ground truth image of Bx1xHxW shape.
|
| 136 |
+
hp_filter: 2D high-pass filter.
|
| 137 |
+
window_size: size of window for local mean calculation.
|
| 138 |
+
|
| 139 |
+
Return:
|
| 140 |
+
Tensor with Spatial Correlation Coefficient score
|
| 141 |
+
|
| 142 |
+
"""
|
| 143 |
+
dtype = preds.dtype
|
| 144 |
+
device = preds.device
|
| 145 |
+
|
| 146 |
+
# This code is inspired by
|
| 147 |
+
# https://github.com/andrewekhalel/sewar/blob/master/sewar/full_ref.py#L187.
|
| 148 |
+
|
| 149 |
+
window = torch.ones(size=(1, 1, window_size, window_size), dtype=dtype, device=device) / (window_size**2)
|
| 150 |
+
|
| 151 |
+
preds_hp = _hp_2d_laplacian(preds, hp_filter)
|
| 152 |
+
target_hp = _hp_2d_laplacian(target, hp_filter)
|
| 153 |
+
|
| 154 |
+
preds_var, target_var, target_preds_cov = _local_variance_covariance(preds_hp, target_hp, window)
|
| 155 |
+
|
| 156 |
+
preds_var[preds_var < 0] = 0
|
| 157 |
+
target_var[target_var < 0] = 0
|
| 158 |
+
|
| 159 |
+
den = torch.sqrt(target_var) * torch.sqrt(preds_var)
|
| 160 |
+
idx = den == 0
|
| 161 |
+
den[den == 0] = 1
|
| 162 |
+
scc = target_preds_cov / den
|
| 163 |
+
scc[idx] = 0
|
| 164 |
+
return scc
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def spatial_correlation_coefficient(
|
| 168 |
+
preds: Tensor,
|
| 169 |
+
target: Tensor,
|
| 170 |
+
hp_filter: Optional[Tensor] = None,
|
| 171 |
+
window_size: int = 8,
|
| 172 |
+
reduction: Optional[Literal["mean", "none", None]] = "mean",
|
| 173 |
+
) -> Tensor:
|
| 174 |
+
"""Compute Spatial Correlation Coefficient (SCC_).
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
preds: predicted images of shape ``(N,C,H,W)`` or ``(N,H,W)``.
|
| 178 |
+
target: ground truth images of shape ``(N,C,H,W)`` or ``(N,H,W)``.
|
| 179 |
+
hp_filter: High-pass filter tensor. default: tensor([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
|
| 180 |
+
window_size: Local window size integer. default: 8,
|
| 181 |
+
reduction: Reduction method for output tensor. If ``None`` or ``"none"``,
|
| 182 |
+
returns a tensor with the per sample results. default: ``"mean"``.
|
| 183 |
+
|
| 184 |
+
Return:
|
| 185 |
+
Tensor with scc score
|
| 186 |
+
|
| 187 |
+
Example:
|
| 188 |
+
>>> from torch import randn
|
| 189 |
+
>>> from torchmetrics.functional.image import spatial_correlation_coefficient as scc
|
| 190 |
+
>>> x = randn(5, 3, 16, 16)
|
| 191 |
+
>>> scc(x, x)
|
| 192 |
+
tensor(1.)
|
| 193 |
+
>>> x = randn(5, 16, 16)
|
| 194 |
+
>>> scc(x, x)
|
| 195 |
+
tensor(1.)
|
| 196 |
+
>>> x = randn(5, 3, 16, 16)
|
| 197 |
+
>>> y = randn(5, 3, 16, 16)
|
| 198 |
+
>>> scc(x, y, reduction="none")
|
| 199 |
+
tensor([0.0223, 0.0256, 0.0616, 0.0159, 0.0170])
|
| 200 |
+
|
| 201 |
+
"""
|
| 202 |
+
if hp_filter is None:
|
| 203 |
+
hp_filter = tensor([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
|
| 204 |
+
if reduction is None:
|
| 205 |
+
reduction = "none"
|
| 206 |
+
if reduction not in ("mean", "none"):
|
| 207 |
+
raise ValueError(f"Expected reduction to be 'mean' or 'none', but got {reduction}")
|
| 208 |
+
preds, target, hp_filter = _scc_update(preds, target, hp_filter, window_size)
|
| 209 |
+
|
| 210 |
+
per_channel = [
|
| 211 |
+
_scc_per_channel_compute(
|
| 212 |
+
preds[:, i, :, :].unsqueeze(1), target[:, i, :, :].unsqueeze(1), hp_filter, window_size
|
| 213 |
+
)
|
| 214 |
+
for i in range(preds.size(1))
|
| 215 |
+
]
|
| 216 |
+
if reduction == "none":
|
| 217 |
+
return torch.mean(torch.cat(per_channel, dim=1), dim=[1, 2, 3])
|
| 218 |
+
if reduction == "mean":
|
| 219 |
+
return reduce(torch.cat(per_channel, dim=1), reduction="elementwise_mean")
|
| 220 |
+
return None
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/ssim.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from collections.abc import Sequence
|
| 15 |
+
from typing import List, Optional, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from torch.nn import functional as F # noqa: N812
|
| 20 |
+
from typing_extensions import Literal
|
| 21 |
+
|
| 22 |
+
from torchmetrics.functional.image.utils import _gaussian_kernel_2d, _gaussian_kernel_3d, _reflection_pad_3d
|
| 23 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 24 |
+
from torchmetrics.utilities.distributed import reduce
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _ssim_check_inputs(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
|
| 28 |
+
"""Update and returns variables required to compute Structural Similarity Index Measure.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
preds: Predicted tensor
|
| 32 |
+
target: Ground truth tensor
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
if preds.dtype != target.dtype:
|
| 36 |
+
target = target.to(preds.dtype)
|
| 37 |
+
_check_same_shape(preds, target)
|
| 38 |
+
if len(preds.shape) not in (4, 5):
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"Expected `preds` and `target` to have BxCxHxW or BxCxDxHxW shape."
|
| 41 |
+
f" Got preds: {preds.shape} and target: {target.shape}."
|
| 42 |
+
)
|
| 43 |
+
return preds, target
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _ssim_update(
|
| 47 |
+
preds: Tensor,
|
| 48 |
+
target: Tensor,
|
| 49 |
+
gaussian_kernel: bool = True,
|
| 50 |
+
sigma: Union[float, Sequence[float]] = 1.5,
|
| 51 |
+
kernel_size: Union[int, Sequence[int]] = 11,
|
| 52 |
+
data_range: Optional[Union[float, tuple[float, float]]] = None,
|
| 53 |
+
k1: float = 0.01,
|
| 54 |
+
k2: float = 0.03,
|
| 55 |
+
return_full_image: bool = False,
|
| 56 |
+
return_contrast_sensitivity: bool = False,
|
| 57 |
+
) -> Union[Tensor, tuple[Tensor, Tensor]]:
|
| 58 |
+
"""Compute Structural Similarity Index Measure.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
preds: estimated image
|
| 62 |
+
target: ground truth image
|
| 63 |
+
gaussian_kernel: If true (default), a gaussian kernel is used, if false a uniform kernel is used
|
| 64 |
+
sigma: Standard deviation of the gaussian kernel, anisotropic kernels are possible.
|
| 65 |
+
Ignored if a uniform kernel is used
|
| 66 |
+
kernel_size: the size of the uniform kernel, anisotropic kernels are possible.
|
| 67 |
+
Ignored if a Gaussian kernel is used
|
| 68 |
+
data_range: Range of the image. If ``None``, it is determined from the image (max - min)
|
| 69 |
+
k1: Parameter of SSIM.
|
| 70 |
+
k2: Parameter of SSIM.
|
| 71 |
+
return_full_image: If true, the full ``ssim`` image is returned as a second argument.
|
| 72 |
+
Mutually exclusive with ``return_contrast_sensitivity``
|
| 73 |
+
return_contrast_sensitivity: If true, the contrast term is returned as a second argument.
|
| 74 |
+
The luminance term can be obtained with luminance=ssim/contrast
|
| 75 |
+
Mutually exclusive with ``return_full_image``
|
| 76 |
+
|
| 77 |
+
"""
|
| 78 |
+
is_3d = preds.ndim == 5
|
| 79 |
+
|
| 80 |
+
if not isinstance(kernel_size, Sequence):
|
| 81 |
+
kernel_size = 3 * [kernel_size] if is_3d else 2 * [kernel_size]
|
| 82 |
+
if not isinstance(sigma, Sequence):
|
| 83 |
+
sigma = 3 * [sigma] if is_3d else 2 * [sigma]
|
| 84 |
+
|
| 85 |
+
if len(kernel_size) != len(target.shape) - 2:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
f"`kernel_size` has dimension {len(kernel_size)}, but expected to be two less that target dimensionality,"
|
| 88 |
+
f" which is: {len(target.shape)}"
|
| 89 |
+
)
|
| 90 |
+
if len(kernel_size) not in (2, 3):
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"Expected `kernel_size` dimension to be 2 or 3. `kernel_size` dimensionality: {len(kernel_size)}"
|
| 93 |
+
)
|
| 94 |
+
if len(sigma) != len(target.shape) - 2:
|
| 95 |
+
raise ValueError(
|
| 96 |
+
f"`kernel_size` has dimension {len(kernel_size)}, but expected to be two less that target dimensionality,"
|
| 97 |
+
f" which is: {len(target.shape)}"
|
| 98 |
+
)
|
| 99 |
+
if len(sigma) not in (2, 3):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
f"Expected `kernel_size` dimension to be 2 or 3. `kernel_size` dimensionality: {len(kernel_size)}"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if return_full_image and return_contrast_sensitivity:
|
| 105 |
+
raise ValueError("Arguments `return_full_image` and `return_contrast_sensitivity` are mutually exclusive.")
|
| 106 |
+
|
| 107 |
+
if any(x % 2 == 0 or x <= 0 for x in kernel_size):
|
| 108 |
+
raise ValueError(f"Expected `kernel_size` to have odd positive number. Got {kernel_size}.")
|
| 109 |
+
|
| 110 |
+
if any(y <= 0 for y in sigma):
|
| 111 |
+
raise ValueError(f"Expected `sigma` to have positive number. Got {sigma}.")
|
| 112 |
+
|
| 113 |
+
if data_range is None:
|
| 114 |
+
data_range = max(preds.max() - preds.min(), target.max() - target.min()) # type: ignore[call-overload]
|
| 115 |
+
elif isinstance(data_range, tuple):
|
| 116 |
+
preds = torch.clamp(preds, min=data_range[0], max=data_range[1])
|
| 117 |
+
target = torch.clamp(target, min=data_range[0], max=data_range[1])
|
| 118 |
+
data_range = data_range[1] - data_range[0]
|
| 119 |
+
|
| 120 |
+
c1 = pow(k1 * data_range, 2) # type: ignore[operator]
|
| 121 |
+
c2 = pow(k2 * data_range, 2) # type: ignore[operator]
|
| 122 |
+
device = preds.device
|
| 123 |
+
|
| 124 |
+
channel = preds.size(1)
|
| 125 |
+
dtype = preds.dtype
|
| 126 |
+
gauss_kernel_size = [int(3.5 * s + 0.5) * 2 + 1 for s in sigma]
|
| 127 |
+
|
| 128 |
+
if gaussian_kernel:
|
| 129 |
+
pad_h = (gauss_kernel_size[0] - 1) // 2
|
| 130 |
+
pad_w = (gauss_kernel_size[1] - 1) // 2
|
| 131 |
+
else:
|
| 132 |
+
pad_h = (kernel_size[0] - 1) // 2
|
| 133 |
+
pad_w = (kernel_size[1] - 1) // 2
|
| 134 |
+
|
| 135 |
+
if is_3d:
|
| 136 |
+
pad_d = (kernel_size[2] - 1) // 2
|
| 137 |
+
preds = _reflection_pad_3d(preds, pad_d, pad_w, pad_h)
|
| 138 |
+
target = _reflection_pad_3d(target, pad_d, pad_w, pad_h)
|
| 139 |
+
if gaussian_kernel:
|
| 140 |
+
kernel = _gaussian_kernel_3d(channel, gauss_kernel_size, sigma, dtype, device)
|
| 141 |
+
else:
|
| 142 |
+
preds = F.pad(preds, (pad_w, pad_w, pad_h, pad_h), mode="reflect")
|
| 143 |
+
target = F.pad(target, (pad_w, pad_w, pad_h, pad_h), mode="reflect")
|
| 144 |
+
if gaussian_kernel:
|
| 145 |
+
kernel = _gaussian_kernel_2d(channel, gauss_kernel_size, sigma, dtype, device)
|
| 146 |
+
|
| 147 |
+
if not gaussian_kernel:
|
| 148 |
+
kernel = torch.ones((channel, 1, *kernel_size), dtype=dtype, device=device) / torch.prod(
|
| 149 |
+
torch.tensor(kernel_size, dtype=dtype, device=device)
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
input_list = torch.cat((preds, target, preds * preds, target * target, preds * target)) # (5 * B, C, H, W)
|
| 153 |
+
|
| 154 |
+
outputs = F.conv3d(input_list, kernel, groups=channel) if is_3d else F.conv2d(input_list, kernel, groups=channel)
|
| 155 |
+
|
| 156 |
+
output_list = outputs.split(preds.shape[0])
|
| 157 |
+
|
| 158 |
+
mu_pred_sq = output_list[0].pow(2)
|
| 159 |
+
mu_target_sq = output_list[1].pow(2)
|
| 160 |
+
mu_pred_target = output_list[0] * output_list[1]
|
| 161 |
+
|
| 162 |
+
# Calculate the variance of the predicted and target images, should be non-negative
|
| 163 |
+
sigma_pred_sq = torch.clamp(output_list[2] - mu_pred_sq, min=0.0)
|
| 164 |
+
sigma_target_sq = torch.clamp(output_list[3] - mu_target_sq, min=0.0)
|
| 165 |
+
sigma_pred_target = output_list[4] - mu_pred_target
|
| 166 |
+
|
| 167 |
+
upper = 2 * sigma_pred_target.to(dtype) + c2
|
| 168 |
+
lower = (sigma_pred_sq + sigma_target_sq).to(dtype) + c2
|
| 169 |
+
|
| 170 |
+
ssim_idx_full_image = ((2 * mu_pred_target + c1) * upper) / ((mu_pred_sq + mu_target_sq + c1) * lower)
|
| 171 |
+
|
| 172 |
+
if return_contrast_sensitivity:
|
| 173 |
+
contrast_sensitivity = upper / lower
|
| 174 |
+
if is_3d:
|
| 175 |
+
contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w, pad_d:-pad_d]
|
| 176 |
+
else:
|
| 177 |
+
contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w]
|
| 178 |
+
|
| 179 |
+
return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), contrast_sensitivity.reshape(
|
| 180 |
+
contrast_sensitivity.shape[0], -1
|
| 181 |
+
).mean(-1)
|
| 182 |
+
|
| 183 |
+
if return_full_image:
|
| 184 |
+
return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), ssim_idx_full_image
|
| 185 |
+
|
| 186 |
+
return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _ssim_compute(
|
| 190 |
+
similarities: Tensor,
|
| 191 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 192 |
+
) -> Tensor:
|
| 193 |
+
"""Apply the specified reduction to pre-computed structural similarity.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
similarities: per image similarities for a batch of images.
|
| 197 |
+
reduction: a method to reduce metric score over individual batch scores
|
| 198 |
+
|
| 199 |
+
- ``'elementwise_mean'``: takes the mean
|
| 200 |
+
- ``'sum'``: takes the sum
|
| 201 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
The reduced SSIM score
|
| 205 |
+
|
| 206 |
+
"""
|
| 207 |
+
return reduce(similarities, reduction)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def structural_similarity_index_measure(
|
| 211 |
+
preds: Tensor,
|
| 212 |
+
target: Tensor,
|
| 213 |
+
gaussian_kernel: bool = True,
|
| 214 |
+
sigma: Union[float, Sequence[float]] = 1.5,
|
| 215 |
+
kernel_size: Union[int, Sequence[int]] = 11,
|
| 216 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 217 |
+
data_range: Optional[Union[float, tuple[float, float]]] = None,
|
| 218 |
+
k1: float = 0.01,
|
| 219 |
+
k2: float = 0.03,
|
| 220 |
+
return_full_image: bool = False,
|
| 221 |
+
return_contrast_sensitivity: bool = False,
|
| 222 |
+
) -> Union[Tensor, tuple[Tensor, Tensor]]:
|
| 223 |
+
"""Compute Structural Similarity Index Measure.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
preds: estimated image
|
| 227 |
+
target: ground truth image
|
| 228 |
+
gaussian_kernel: If true (default), a gaussian kernel is used, if false a uniform kernel is used
|
| 229 |
+
sigma: Standard deviation of the gaussian kernel, anisotropic kernels are possible.
|
| 230 |
+
Ignored if a uniform kernel is used
|
| 231 |
+
kernel_size: the size of the uniform kernel, anisotropic kernels are possible.
|
| 232 |
+
Ignored if a Gaussian kernel is used
|
| 233 |
+
reduction: a method to reduce metric score over labels.
|
| 234 |
+
|
| 235 |
+
- ``'elementwise_mean'``: takes the mean
|
| 236 |
+
- ``'sum'``: takes the sum
|
| 237 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 238 |
+
|
| 239 |
+
data_range:
|
| 240 |
+
the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then
|
| 241 |
+
the range is calculated as the difference and input is clamped between the values.
|
| 242 |
+
k1: Parameter of SSIM.
|
| 243 |
+
k2: Parameter of SSIM.
|
| 244 |
+
return_full_image: If true, the full ``ssim`` image is returned as a second argument.
|
| 245 |
+
Mutually exclusive with ``return_contrast_sensitivity``
|
| 246 |
+
return_contrast_sensitivity: If true, the constant term is returned as a second argument.
|
| 247 |
+
The luminance term can be obtained with luminance=ssim/contrast
|
| 248 |
+
Mutually exclusive with ``return_full_image``
|
| 249 |
+
|
| 250 |
+
Return:
|
| 251 |
+
Tensor with SSIM score
|
| 252 |
+
|
| 253 |
+
Raises:
|
| 254 |
+
TypeError:
|
| 255 |
+
If ``preds`` and ``target`` don't have the same data type.
|
| 256 |
+
ValueError:
|
| 257 |
+
If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
|
| 258 |
+
ValueError:
|
| 259 |
+
If the length of ``kernel_size`` or ``sigma`` is not ``2``.
|
| 260 |
+
ValueError:
|
| 261 |
+
If one of the elements of ``kernel_size`` is not an ``odd positive number``.
|
| 262 |
+
ValueError:
|
| 263 |
+
If one of the elements of ``sigma`` is not a ``positive number``.
|
| 264 |
+
|
| 265 |
+
Example:
|
| 266 |
+
>>> from torchmetrics.functional.image import structural_similarity_index_measure
|
| 267 |
+
>>> preds = torch.rand([3, 3, 256, 256])
|
| 268 |
+
>>> target = preds * 0.75
|
| 269 |
+
>>> structural_similarity_index_measure(preds, target)
|
| 270 |
+
tensor(0.9219)
|
| 271 |
+
|
| 272 |
+
"""
|
| 273 |
+
preds, target = _ssim_check_inputs(preds, target)
|
| 274 |
+
similarity_pack = _ssim_update(
|
| 275 |
+
preds,
|
| 276 |
+
target,
|
| 277 |
+
gaussian_kernel,
|
| 278 |
+
sigma,
|
| 279 |
+
kernel_size,
|
| 280 |
+
data_range,
|
| 281 |
+
k1,
|
| 282 |
+
k2,
|
| 283 |
+
return_full_image,
|
| 284 |
+
return_contrast_sensitivity,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if isinstance(similarity_pack, tuple):
|
| 288 |
+
similarity, image = similarity_pack
|
| 289 |
+
return _ssim_compute(similarity, reduction), image
|
| 290 |
+
|
| 291 |
+
similarity = similarity_pack
|
| 292 |
+
return _ssim_compute(similarity, reduction)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _get_normalized_sim_and_cs(
|
| 296 |
+
preds: Tensor,
|
| 297 |
+
target: Tensor,
|
| 298 |
+
gaussian_kernel: bool = True,
|
| 299 |
+
sigma: Union[float, Sequence[float]] = 1.5,
|
| 300 |
+
kernel_size: Union[int, Sequence[int]] = 11,
|
| 301 |
+
data_range: Optional[Union[float, tuple[float, float]]] = None,
|
| 302 |
+
k1: float = 0.01,
|
| 303 |
+
k2: float = 0.03,
|
| 304 |
+
normalize: Optional[Literal["relu", "simple"]] = None,
|
| 305 |
+
) -> tuple[Tensor, Tensor]:
|
| 306 |
+
sim, contrast_sensitivity = _ssim_update(
|
| 307 |
+
preds,
|
| 308 |
+
target,
|
| 309 |
+
gaussian_kernel,
|
| 310 |
+
sigma,
|
| 311 |
+
kernel_size,
|
| 312 |
+
data_range,
|
| 313 |
+
k1,
|
| 314 |
+
k2,
|
| 315 |
+
return_contrast_sensitivity=True,
|
| 316 |
+
)
|
| 317 |
+
if normalize == "relu":
|
| 318 |
+
sim = torch.relu(sim)
|
| 319 |
+
contrast_sensitivity = torch.relu(contrast_sensitivity)
|
| 320 |
+
return sim, contrast_sensitivity
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _multiscale_ssim_update(
|
| 324 |
+
preds: Tensor,
|
| 325 |
+
target: Tensor,
|
| 326 |
+
gaussian_kernel: bool = True,
|
| 327 |
+
sigma: Union[float, Sequence[float]] = 1.5,
|
| 328 |
+
kernel_size: Union[int, Sequence[int]] = 11,
|
| 329 |
+
data_range: Optional[Union[float, tuple[float, float]]] = None,
|
| 330 |
+
k1: float = 0.01,
|
| 331 |
+
k2: float = 0.03,
|
| 332 |
+
betas: Union[tuple[float, float, float, float, float], tuple[float, ...]] = (
|
| 333 |
+
0.0448,
|
| 334 |
+
0.2856,
|
| 335 |
+
0.3001,
|
| 336 |
+
0.2363,
|
| 337 |
+
0.1333,
|
| 338 |
+
),
|
| 339 |
+
normalize: Optional[Literal["relu", "simple"]] = None,
|
| 340 |
+
) -> Tensor:
|
| 341 |
+
"""Compute Multi-Scale Structural Similarity Index Measure.
|
| 342 |
+
|
| 343 |
+
Adapted from: https://github.com/jorge-pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py.
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
preds: estimated image
|
| 347 |
+
target: ground truth image
|
| 348 |
+
gaussian_kernel: If true, a gaussian kernel is used, if false a uniform kernel is used
|
| 349 |
+
sigma: Standard deviation of the gaussian kernel
|
| 350 |
+
kernel_size: size of the gaussian kernel
|
| 351 |
+
reduction: a method to reduce metric score over labels.
|
| 352 |
+
|
| 353 |
+
- ``'elementwise_mean'``: takes the mean
|
| 354 |
+
- ``'sum'``: takes the sum
|
| 355 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 356 |
+
|
| 357 |
+
data_range: Range of the image. If ``None``, it is determined from the image (max - min)
|
| 358 |
+
k1: Parameter of structural similarity index measure.
|
| 359 |
+
k2: Parameter of structural similarity index measure.
|
| 360 |
+
betas: Exponent parameters for individual similarities and contrastive sensitives returned by different image
|
| 361 |
+
resolutions.
|
| 362 |
+
normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the
|
| 363 |
+
training stability. This `normalize` argument is out of scope of the original implementation [1], and it is
|
| 364 |
+
adapted from https://github.com/jorge-pessoa/pytorch-msssim instead.
|
| 365 |
+
|
| 366 |
+
Raises:
|
| 367 |
+
ValueError:
|
| 368 |
+
If the image height or width is smaller then ``2 ** len(betas)``.
|
| 369 |
+
ValueError:
|
| 370 |
+
If the image height is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``.
|
| 371 |
+
ValueError:
|
| 372 |
+
If the image width is smaller than ``(kernel_size[0] - 1) * max(1, (len(betas) - 1)) ** 2``.
|
| 373 |
+
|
| 374 |
+
"""
|
| 375 |
+
mcs_list: List[Tensor] = []
|
| 376 |
+
|
| 377 |
+
is_3d = preds.ndim == 5
|
| 378 |
+
|
| 379 |
+
if not isinstance(kernel_size, Sequence):
|
| 380 |
+
kernel_size = 3 * [kernel_size] if is_3d else 2 * [kernel_size]
|
| 381 |
+
if not isinstance(sigma, Sequence):
|
| 382 |
+
sigma = 3 * [sigma] if is_3d else 2 * [sigma]
|
| 383 |
+
|
| 384 |
+
if preds.size()[-1] < 2 ** len(betas) or preds.size()[-2] < 2 ** len(betas):
|
| 385 |
+
raise ValueError(
|
| 386 |
+
f"For a given number of `betas` parameters {len(betas)}, the image height and width dimensions must be"
|
| 387 |
+
f" larger than or equal to {2 ** len(betas)}."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
_betas_div = max(1, (len(betas) - 1)) ** 2
|
| 391 |
+
if preds.size()[-2] // _betas_div <= kernel_size[0] - 1:
|
| 392 |
+
raise ValueError(
|
| 393 |
+
f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[0]},"
|
| 394 |
+
f" the image height must be larger than {(kernel_size[0] - 1) * _betas_div}."
|
| 395 |
+
)
|
| 396 |
+
if preds.size()[-1] // _betas_div <= kernel_size[1] - 1:
|
| 397 |
+
raise ValueError(
|
| 398 |
+
f"For a given number of `betas` parameters {len(betas)} and kernel size {kernel_size[1]},"
|
| 399 |
+
f" the image width must be larger than {(kernel_size[1] - 1) * _betas_div}."
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
for _ in range(len(betas)):
|
| 403 |
+
sim, contrast_sensitivity = _get_normalized_sim_and_cs(
|
| 404 |
+
preds, target, gaussian_kernel, sigma, kernel_size, data_range, k1, k2, normalize=normalize
|
| 405 |
+
)
|
| 406 |
+
mcs_list.append(contrast_sensitivity)
|
| 407 |
+
|
| 408 |
+
if len(kernel_size) == 2:
|
| 409 |
+
preds = F.avg_pool2d(preds, (2, 2))
|
| 410 |
+
target = F.avg_pool2d(target, (2, 2))
|
| 411 |
+
elif len(kernel_size) == 3:
|
| 412 |
+
preds = F.avg_pool3d(preds, (2, 2, 2))
|
| 413 |
+
target = F.avg_pool3d(target, (2, 2, 2))
|
| 414 |
+
else:
|
| 415 |
+
raise ValueError("length of kernel_size is neither 2 nor 3")
|
| 416 |
+
|
| 417 |
+
mcs_list[-1] = sim
|
| 418 |
+
mcs_stack = torch.stack(mcs_list)
|
| 419 |
+
|
| 420 |
+
if normalize == "simple":
|
| 421 |
+
mcs_stack = (mcs_stack + 1) / 2
|
| 422 |
+
|
| 423 |
+
betas = torch.tensor(betas, device=mcs_stack.device).view(-1, 1)
|
| 424 |
+
mcs_weighted = mcs_stack**betas
|
| 425 |
+
return torch.prod(mcs_weighted, axis=0) # type: ignore[call-overload]
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def _multiscale_ssim_compute(
|
| 429 |
+
mcs_per_image: Tensor,
|
| 430 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 431 |
+
) -> Tensor:
|
| 432 |
+
"""Apply the specified reduction to pre-computed multi-scale structural similarity.
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
mcs_per_image: per image similarities for a batch of images.
|
| 436 |
+
reduction: a method to reduce metric score over individual batch scores
|
| 437 |
+
|
| 438 |
+
- ``'elementwise_mean'``: takes the mean
|
| 439 |
+
- ``'sum'``: takes the sum
|
| 440 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 441 |
+
|
| 442 |
+
Returns:
|
| 443 |
+
The reduced multi-scale structural similarity
|
| 444 |
+
|
| 445 |
+
"""
|
| 446 |
+
return reduce(mcs_per_image, reduction)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def multiscale_structural_similarity_index_measure(
|
| 450 |
+
preds: Tensor,
|
| 451 |
+
target: Tensor,
|
| 452 |
+
gaussian_kernel: bool = True,
|
| 453 |
+
sigma: Union[float, Sequence[float]] = 1.5,
|
| 454 |
+
kernel_size: Union[int, Sequence[int]] = 11,
|
| 455 |
+
reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
|
| 456 |
+
data_range: Optional[Union[float, tuple[float, float]]] = None,
|
| 457 |
+
k1: float = 0.01,
|
| 458 |
+
k2: float = 0.03,
|
| 459 |
+
betas: tuple[float, ...] = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333),
|
| 460 |
+
normalize: Optional[Literal["relu", "simple"]] = "relu",
|
| 461 |
+
) -> Tensor:
|
| 462 |
+
"""Compute `MultiScaleSSIM`_, Multi-scale Structural Similarity Index Measure.
|
| 463 |
+
|
| 464 |
+
This metric is a generalization of Structural Similarity Index Measure by incorporating image details at different
|
| 465 |
+
resolution scores.
|
| 466 |
+
|
| 467 |
+
Args:
|
| 468 |
+
preds: Predictions from model of shape ``[N, C, H, W]``
|
| 469 |
+
target: Ground truth values of shape ``[N, C, H, W]``
|
| 470 |
+
gaussian_kernel: If true, a gaussian kernel is used, if false a uniform kernel is used
|
| 471 |
+
sigma: Standard deviation of the gaussian kernel
|
| 472 |
+
kernel_size: size of the gaussian kernel
|
| 473 |
+
reduction: a method to reduce metric score over labels.
|
| 474 |
+
|
| 475 |
+
- ``'elementwise_mean'``: takes the mean
|
| 476 |
+
- ``'sum'``: takes the sum
|
| 477 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 478 |
+
|
| 479 |
+
data_range:
|
| 480 |
+
the range of the data. If None, it is determined from the data (max - min). If a tuple is provided then
|
| 481 |
+
the range is calculated as the difference and input is clamped between the values.
|
| 482 |
+
k1: Parameter of structural similarity index measure.
|
| 483 |
+
k2: Parameter of structural similarity index measure.
|
| 484 |
+
betas: Exponent parameters for individual similarities and contrastive sensitivities returned by different image
|
| 485 |
+
resolutions.
|
| 486 |
+
normalize: When MultiScaleSSIM loss is used for training, it is desirable to use normalizes to improve the
|
| 487 |
+
training stability. This `normalize` argument is out of scope of the original implementation [1], and it is
|
| 488 |
+
adapted from https://github.com/jorge-pessoa/pytorch-msssim instead.
|
| 489 |
+
|
| 490 |
+
Return:
|
| 491 |
+
Tensor with Multi-Scale SSIM score
|
| 492 |
+
|
| 493 |
+
Raises:
|
| 494 |
+
TypeError:
|
| 495 |
+
If ``preds`` and ``target`` don't have the same data type.
|
| 496 |
+
ValueError:
|
| 497 |
+
If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
|
| 498 |
+
ValueError:
|
| 499 |
+
If the length of ``kernel_size`` or ``sigma`` is not ``2``.
|
| 500 |
+
ValueError:
|
| 501 |
+
If one of the elements of ``kernel_size`` is not an ``odd positive number``.
|
| 502 |
+
ValueError:
|
| 503 |
+
If one of the elements of ``sigma`` is not a ``positive number``.
|
| 504 |
+
|
| 505 |
+
Example:
|
| 506 |
+
>>> from torch import rand
|
| 507 |
+
>>> from torchmetrics.functional.image import multiscale_structural_similarity_index_measure
|
| 508 |
+
>>> preds = rand([3, 3, 256, 256])
|
| 509 |
+
>>> target = preds * 0.75
|
| 510 |
+
>>> multiscale_structural_similarity_index_measure(preds, target, data_range=1.0)
|
| 511 |
+
tensor(0.9628)
|
| 512 |
+
|
| 513 |
+
References:
|
| 514 |
+
[1] Multi-Scale Structural Similarity For Image Quality Assessment by Zhou Wang, Eero P. Simoncelli and Alan C.
|
| 515 |
+
Bovik `MultiScaleSSIM`_
|
| 516 |
+
|
| 517 |
+
"""
|
| 518 |
+
if not isinstance(betas, tuple):
|
| 519 |
+
raise ValueError("Argument `betas` is expected to be of a type tuple.")
|
| 520 |
+
if isinstance(betas, tuple) and not all(isinstance(beta, float) for beta in betas):
|
| 521 |
+
raise ValueError("Argument `betas` is expected to be a tuple of floats.")
|
| 522 |
+
if normalize and normalize not in ("relu", "simple"):
|
| 523 |
+
raise ValueError("Argument `normalize` to be expected either `None` or one of 'relu' or 'simple'")
|
| 524 |
+
|
| 525 |
+
preds, target = _ssim_check_inputs(preds, target)
|
| 526 |
+
mcs_per_image = _multiscale_ssim_update(
|
| 527 |
+
preds, target, gaussian_kernel, sigma, kernel_size, data_range, k1, k2, betas, normalize
|
| 528 |
+
)
|
| 529 |
+
return _multiscale_ssim_compute(mcs_per_image, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/tv.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional, Union
|
| 15 |
+
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _total_variation_update(img: Tensor) -> tuple[Tensor, int]:
|
| 21 |
+
"""Compute total variation statistics on current batch."""
|
| 22 |
+
if img.ndim != 4:
|
| 23 |
+
raise RuntimeError(f"Expected input `img` to be an 4D tensor, but got {img.shape}")
|
| 24 |
+
diff1 = img[..., 1:, :] - img[..., :-1, :]
|
| 25 |
+
diff2 = img[..., :, 1:] - img[..., :, :-1]
|
| 26 |
+
|
| 27 |
+
res1 = diff1.abs().sum([1, 2, 3])
|
| 28 |
+
res2 = diff2.abs().sum([1, 2, 3])
|
| 29 |
+
score = res1 + res2
|
| 30 |
+
return score, img.shape[0]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _total_variation_compute(
|
| 34 |
+
score: Tensor, num_elements: Union[int, Tensor], reduction: Optional[Literal["mean", "sum", "none"]]
|
| 35 |
+
) -> Tensor:
|
| 36 |
+
"""Compute final total variation score."""
|
| 37 |
+
if reduction == "mean":
|
| 38 |
+
return score.sum() / num_elements
|
| 39 |
+
if reduction == "sum":
|
| 40 |
+
return score.sum()
|
| 41 |
+
if reduction is None or reduction == "none":
|
| 42 |
+
return score
|
| 43 |
+
raise ValueError("Expected argument `reduction` to either be 'sum', 'mean', 'none' or None")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def total_variation(img: Tensor, reduction: Optional[Literal["mean", "sum", "none"]] = "sum") -> Tensor:
|
| 47 |
+
"""Compute total variation loss.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
img: A `Tensor` of shape `(N, C, H, W)` consisting of images
|
| 51 |
+
reduction: a method to reduce metric score over samples.
|
| 52 |
+
|
| 53 |
+
- ``'mean'``: takes the mean over samples
|
| 54 |
+
- ``'sum'``: takes the sum over samples
|
| 55 |
+
- ``None`` or ``'none'``: return the score per sample
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
A loss scalar value containing the total variation
|
| 59 |
+
|
| 60 |
+
Raises:
|
| 61 |
+
ValueError:
|
| 62 |
+
If ``reduction`` is not one of ``'sum'``, ``'mean'``, ``'none'`` or ``None``
|
| 63 |
+
RuntimeError:
|
| 64 |
+
If ``img`` is not 4D tensor
|
| 65 |
+
|
| 66 |
+
Example:
|
| 67 |
+
>>> from torch import rand
|
| 68 |
+
>>> from torchmetrics.functional.image import total_variation
|
| 69 |
+
>>> img = rand(5, 3, 28, 28)
|
| 70 |
+
>>> total_variation(img)
|
| 71 |
+
tensor(7546.8018)
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
# code adapted from:
|
| 75 |
+
# from kornia.losses import total_variation as kornia_total_variation
|
| 76 |
+
score, num_elements = _total_variation_update(img)
|
| 77 |
+
return _total_variation_compute(score, num_elements, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/uqi.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from collections.abc import Sequence
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor, nn
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.image.utils import _gaussian_kernel_2d
|
| 22 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 23 |
+
from torchmetrics.utilities.distributed import reduce
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _uqi_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
|
| 27 |
+
"""Update and returns variables required to compute Universal Image Quality Index.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
preds: Predicted tensor
|
| 31 |
+
target: Ground truth tensor
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
if preds.dtype != target.dtype:
|
| 35 |
+
raise TypeError(
|
| 36 |
+
"Expected `preds` and `target` to have the same data type."
|
| 37 |
+
f" Got preds: {preds.dtype} and target: {target.dtype}."
|
| 38 |
+
)
|
| 39 |
+
_check_same_shape(preds, target)
|
| 40 |
+
if len(preds.shape) != 4:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
f"Expected `preds` and `target` to have BxCxHxW shape. Got preds: {preds.shape} and target: {target.shape}."
|
| 43 |
+
)
|
| 44 |
+
return preds, target
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _uqi_compute(
|
| 48 |
+
preds: Tensor,
|
| 49 |
+
target: Tensor,
|
| 50 |
+
kernel_size: Sequence[int] = (11, 11),
|
| 51 |
+
sigma: Sequence[float] = (1.5, 1.5),
|
| 52 |
+
reduction: Optional[Literal["elementwise_mean", "sum", "none"]] = "elementwise_mean",
|
| 53 |
+
) -> Tensor:
|
| 54 |
+
"""Compute Universal Image Quality Index.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
preds: estimated image
|
| 58 |
+
target: ground truth image
|
| 59 |
+
kernel_size: size of the gaussian kernel
|
| 60 |
+
sigma: Standard deviation of the gaussian kernel
|
| 61 |
+
reduction: a method to reduce metric score over labels.
|
| 62 |
+
|
| 63 |
+
- ``'elementwise_mean'``: takes the mean (default)
|
| 64 |
+
- ``'sum'``: takes the sum
|
| 65 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
>>> preds = torch.rand([16, 1, 16, 16])
|
| 69 |
+
>>> target = preds * 0.75
|
| 70 |
+
>>> preds, target = _uqi_update(preds, target)
|
| 71 |
+
>>> _uqi_compute(preds, target)
|
| 72 |
+
tensor(0.9216)
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
if len(kernel_size) != 2 or len(sigma) != 2:
|
| 76 |
+
raise ValueError(
|
| 77 |
+
"Expected `kernel_size` and `sigma` to have the length of two."
|
| 78 |
+
f" Got kernel_size: {len(kernel_size)} and sigma: {len(sigma)}."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if any(x % 2 == 0 or x <= 0 for x in kernel_size):
|
| 82 |
+
raise ValueError(f"Expected `kernel_size` to have odd positive number. Got {kernel_size}.")
|
| 83 |
+
|
| 84 |
+
if any(y <= 0 for y in sigma):
|
| 85 |
+
raise ValueError(f"Expected `sigma` to have positive number. Got {sigma}.")
|
| 86 |
+
|
| 87 |
+
device = preds.device
|
| 88 |
+
channel = preds.size(1)
|
| 89 |
+
dtype = preds.dtype
|
| 90 |
+
kernel = _gaussian_kernel_2d(channel, kernel_size, sigma, dtype, device)
|
| 91 |
+
pad_h = (kernel_size[0] - 1) // 2
|
| 92 |
+
pad_w = (kernel_size[1] - 1) // 2
|
| 93 |
+
|
| 94 |
+
preds = nn.functional.pad(preds, (pad_h, pad_h, pad_w, pad_w), mode="reflect")
|
| 95 |
+
target = nn.functional.pad(target, (pad_h, pad_h, pad_w, pad_w), mode="reflect")
|
| 96 |
+
|
| 97 |
+
input_list = torch.cat((preds, target, preds * preds, target * target, preds * target)) # (5 * B, C, H, W)
|
| 98 |
+
outputs = nn.functional.conv2d(input_list, kernel, groups=channel)
|
| 99 |
+
output_list = outputs.split(preds.shape[0])
|
| 100 |
+
|
| 101 |
+
mu_pred_sq = output_list[0].pow(2)
|
| 102 |
+
mu_target_sq = output_list[1].pow(2)
|
| 103 |
+
mu_pred_target = output_list[0] * output_list[1]
|
| 104 |
+
|
| 105 |
+
# Calculate the variance of the predicted and target images, should be non-negative
|
| 106 |
+
sigma_pred_sq = torch.clamp(output_list[2] - mu_pred_sq, min=0.0)
|
| 107 |
+
sigma_target_sq = torch.clamp(output_list[3] - mu_target_sq, min=0.0)
|
| 108 |
+
sigma_pred_target = output_list[4] - mu_pred_target
|
| 109 |
+
|
| 110 |
+
upper = 2 * sigma_pred_target
|
| 111 |
+
lower = sigma_pred_sq + sigma_target_sq
|
| 112 |
+
eps = torch.finfo(sigma_pred_sq.dtype).eps
|
| 113 |
+
uqi_idx = ((2 * mu_pred_target) * upper) / ((mu_pred_sq + mu_target_sq) * lower + eps)
|
| 114 |
+
uqi_idx = uqi_idx[..., pad_h:-pad_h, pad_w:-pad_w]
|
| 115 |
+
|
| 116 |
+
return reduce(uqi_idx, reduction)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def universal_image_quality_index(
|
| 120 |
+
preds: Tensor,
|
| 121 |
+
target: Tensor,
|
| 122 |
+
kernel_size: Sequence[int] = (11, 11),
|
| 123 |
+
sigma: Sequence[float] = (1.5, 1.5),
|
| 124 |
+
reduction: Optional[Literal["elementwise_mean", "sum", "none"]] = "elementwise_mean",
|
| 125 |
+
) -> Tensor:
|
| 126 |
+
"""Universal Image Quality Index.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
preds: estimated image
|
| 130 |
+
target: ground truth image
|
| 131 |
+
kernel_size: size of the gaussian kernel
|
| 132 |
+
sigma: Standard deviation of the gaussian kernel
|
| 133 |
+
reduction: a method to reduce metric score over labels.
|
| 134 |
+
|
| 135 |
+
- ``'elementwise_mean'``: takes the mean (default)
|
| 136 |
+
- ``'sum'``: takes the sum
|
| 137 |
+
- ``'none'`` or ``None``: no reduction will be applied
|
| 138 |
+
|
| 139 |
+
Return:
|
| 140 |
+
Tensor with UniversalImageQualityIndex score
|
| 141 |
+
|
| 142 |
+
Raises:
|
| 143 |
+
TypeError:
|
| 144 |
+
If ``preds`` and ``target`` don't have the same data type.
|
| 145 |
+
ValueError:
|
| 146 |
+
If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
|
| 147 |
+
ValueError:
|
| 148 |
+
If the length of ``kernel_size`` or ``sigma`` is not ``2``.
|
| 149 |
+
ValueError:
|
| 150 |
+
If one of the elements of ``kernel_size`` is not an ``odd positive number``.
|
| 151 |
+
ValueError:
|
| 152 |
+
If one of the elements of ``sigma`` is not a ``positive number``.
|
| 153 |
+
|
| 154 |
+
Example:
|
| 155 |
+
>>> from torchmetrics.functional.image import universal_image_quality_index
|
| 156 |
+
>>> preds = torch.rand([16, 1, 16, 16])
|
| 157 |
+
>>> target = preds * 0.75
|
| 158 |
+
>>> universal_image_quality_index(preds, target)
|
| 159 |
+
tensor(0.9216)
|
| 160 |
+
|
| 161 |
+
References:
|
| 162 |
+
[1] Zhou Wang and A. C. Bovik, "A universal image quality index," in IEEE Signal Processing Letters, vol. 9,
|
| 163 |
+
no. 3, pp. 81-84, March 2002, doi: 10.1109/97.995823.
|
| 164 |
+
|
| 165 |
+
[2] Zhou Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli, "Image quality assessment: from error visibility
|
| 166 |
+
to structural similarity," in IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, April 2004,
|
| 167 |
+
doi: 10.1109/TIP.2003.819861.
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
preds, target = _uqi_update(preds, target)
|
| 171 |
+
return _uqi_compute(preds, target, kernel_size, sigma, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from typing import Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.nn import functional as F # noqa: N812
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _gaussian(kernel_size: int, sigma: float, dtype: torch.dtype, device: Union[torch.device, str]) -> Tensor:
|
| 10 |
+
"""Compute 1D gaussian kernel.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
kernel_size: size of the gaussian kernel
|
| 14 |
+
sigma: Standard deviation of the gaussian kernel
|
| 15 |
+
dtype: data type of the output tensor
|
| 16 |
+
device: device of the output tensor
|
| 17 |
+
|
| 18 |
+
Example:
|
| 19 |
+
>>> _gaussian(3, 1, torch.float, 'cpu')
|
| 20 |
+
tensor([[0.2741, 0.4519, 0.2741]])
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
dist = torch.arange(start=(1 - kernel_size) / 2, end=(1 + kernel_size) / 2, step=1, dtype=dtype, device=device)
|
| 24 |
+
gauss = torch.exp(-torch.pow(dist / sigma, 2) / 2)
|
| 25 |
+
return (gauss / gauss.sum()).unsqueeze(dim=0) # (1, kernel_size)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _gaussian_kernel_2d(
|
| 29 |
+
channel: int,
|
| 30 |
+
kernel_size: Sequence[int],
|
| 31 |
+
sigma: Sequence[float],
|
| 32 |
+
dtype: torch.dtype,
|
| 33 |
+
device: Union[torch.device, str],
|
| 34 |
+
) -> Tensor:
|
| 35 |
+
"""Compute 2D gaussian kernel.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
channel: number of channels in the image
|
| 39 |
+
kernel_size: size of the gaussian kernel as a tuple (h, w)
|
| 40 |
+
sigma: Standard deviation of the gaussian kernel
|
| 41 |
+
dtype: data type of the output tensor
|
| 42 |
+
device: device of the output tensor
|
| 43 |
+
|
| 44 |
+
Example:
|
| 45 |
+
>>> _gaussian_kernel_2d(1, (5,5), (1,1), torch.float, "cpu")
|
| 46 |
+
tensor([[[[0.0030, 0.0133, 0.0219, 0.0133, 0.0030],
|
| 47 |
+
[0.0133, 0.0596, 0.0983, 0.0596, 0.0133],
|
| 48 |
+
[0.0219, 0.0983, 0.1621, 0.0983, 0.0219],
|
| 49 |
+
[0.0133, 0.0596, 0.0983, 0.0596, 0.0133],
|
| 50 |
+
[0.0030, 0.0133, 0.0219, 0.0133, 0.0030]]]])
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
gaussian_kernel_x = _gaussian(kernel_size[0], sigma[0], dtype, device)
|
| 54 |
+
gaussian_kernel_y = _gaussian(kernel_size[1], sigma[1], dtype, device)
|
| 55 |
+
kernel = torch.matmul(gaussian_kernel_x.t(), gaussian_kernel_y) # (kernel_size, 1) * (1, kernel_size)
|
| 56 |
+
|
| 57 |
+
return kernel.expand(channel, 1, kernel_size[0], kernel_size[1])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _uniform_weight_bias_conv2d(inputs: Tensor, window_size: int) -> tuple[Tensor, Tensor]:
|
| 61 |
+
"""Construct uniform weight and bias for a 2d convolution.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
inputs: Input image
|
| 65 |
+
window_size: size of convolutional kernel
|
| 66 |
+
|
| 67 |
+
Return:
|
| 68 |
+
The weight and bias for 2d convolution
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
kernel_weight = torch.ones(1, 1, window_size, window_size, dtype=inputs.dtype, device=inputs.device)
|
| 72 |
+
kernel_weight /= window_size**2
|
| 73 |
+
kernel_bias = torch.zeros(1, dtype=inputs.dtype, device=inputs.device)
|
| 74 |
+
return kernel_weight, kernel_bias
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _single_dimension_pad(inputs: Tensor, dim: int, pad: int, outer_pad: int = 0) -> Tensor:
|
| 78 |
+
"""Apply single-dimension reflection padding to match scipy implementation.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
inputs: Input image
|
| 82 |
+
dim: A dimension the image should be padded over
|
| 83 |
+
pad: Number of pads
|
| 84 |
+
outer_pad: Number of outer pads
|
| 85 |
+
|
| 86 |
+
Return:
|
| 87 |
+
Image padded over a single dimension
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
_max = inputs.shape[dim]
|
| 91 |
+
x = torch.index_select(inputs, dim, torch.arange(pad - 1, -1, -1).to(inputs.device))
|
| 92 |
+
y = torch.index_select(inputs, dim, torch.arange(_max - 1, _max - pad - outer_pad, -1).to(inputs.device))
|
| 93 |
+
return torch.cat((x, inputs, y), dim)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _reflection_pad_2d(inputs: Tensor, pad: int, outer_pad: int = 0) -> Tensor:
|
| 97 |
+
"""Apply reflection padding to the input image.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
inputs: Input image
|
| 101 |
+
pad: Number of pads
|
| 102 |
+
outer_pad: Number of outer pads
|
| 103 |
+
|
| 104 |
+
Return:
|
| 105 |
+
Padded image
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
for dim in [2, 3]:
|
| 109 |
+
inputs = _single_dimension_pad(inputs, dim, pad, outer_pad)
|
| 110 |
+
return inputs
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _uniform_filter(inputs: Tensor, window_size: int) -> Tensor:
|
| 114 |
+
"""Apply uniform filter with a window of a given size over the input image.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
inputs: Input image
|
| 118 |
+
window_size: Sliding window used for rmse calculation
|
| 119 |
+
|
| 120 |
+
Return:
|
| 121 |
+
Image transformed with the uniform input
|
| 122 |
+
|
| 123 |
+
"""
|
| 124 |
+
inputs = _reflection_pad_2d(inputs, window_size // 2, window_size % 2)
|
| 125 |
+
kernel_weight, kernel_bias = _uniform_weight_bias_conv2d(inputs, window_size)
|
| 126 |
+
# Iterate over channels
|
| 127 |
+
return torch.cat(
|
| 128 |
+
[
|
| 129 |
+
F.conv2d(inputs[:, channel].unsqueeze(1), kernel_weight, kernel_bias, padding=0)
|
| 130 |
+
for channel in range(inputs.shape[1])
|
| 131 |
+
],
|
| 132 |
+
dim=1,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _gaussian_kernel_3d(
|
| 137 |
+
channel: int, kernel_size: Sequence[int], sigma: Sequence[float], dtype: torch.dtype, device: torch.device
|
| 138 |
+
) -> Tensor:
|
| 139 |
+
"""Compute 3D gaussian kernel.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
channel: number of channels in the image
|
| 143 |
+
kernel_size: size of the gaussian kernel as a tuple (h, w, d)
|
| 144 |
+
sigma: Standard deviation of the gaussian kernel
|
| 145 |
+
dtype: data type of the output tensor
|
| 146 |
+
device: device of the output tensor
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
gaussian_kernel_x = _gaussian(kernel_size[0], sigma[0], dtype, device)
|
| 150 |
+
gaussian_kernel_y = _gaussian(kernel_size[1], sigma[1], dtype, device)
|
| 151 |
+
gaussian_kernel_z = _gaussian(kernel_size[2], sigma[2], dtype, device)
|
| 152 |
+
kernel_xy = torch.matmul(gaussian_kernel_x.t(), gaussian_kernel_y) # (kernel_size, 1) * (1, kernel_size)
|
| 153 |
+
kernel = torch.mul(
|
| 154 |
+
kernel_xy.unsqueeze(-1).repeat(1, 1, kernel_size[2]),
|
| 155 |
+
gaussian_kernel_z.expand(kernel_size[0], kernel_size[1], kernel_size[2]),
|
| 156 |
+
)
|
| 157 |
+
return kernel.expand(channel, 1, kernel_size[0], kernel_size[1], kernel_size[2])
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _reflection_pad_3d(inputs: Tensor, pad_h: int, pad_w: int, pad_d: int) -> Tensor:
|
| 161 |
+
"""Reflective padding of 3d input.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
inputs: tensor to pad, should be a 3D tensor of shape ``[N, C, H, W, D]``
|
| 165 |
+
pad_w: amount of padding in the height dimension
|
| 166 |
+
pad_h: amount of padding in the width dimension
|
| 167 |
+
pad_d: amount of padding in the depth dimension
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
padded input tensor
|
| 171 |
+
|
| 172 |
+
"""
|
| 173 |
+
return F.pad(inputs, (pad_h, pad_h, pad_w, pad_w, pad_d, pad_d), mode="reflect")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/image/vif.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The PyTorch Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
from torch.nn.functional import conv2d
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.data import dim_zero_cat
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _filter(win_size: float, sigma: float, dtype: torch.dtype, device: torch.device) -> Tensor:
|
| 23 |
+
# This code is inspired by
|
| 24 |
+
# https://github.com/andrewekhalel/sewar/blob/ac76e7bc75732fde40bb0d3908f4b6863400cc27/sewar/utils.py#L45
|
| 25 |
+
# https://github.com/photosynthesis-team/piq/blob/01e16b7d8c76bc8765fb6a69560d806148b8046a/piq/functional/filters.py#L38
|
| 26 |
+
# Both links do the same, but the second one is cleaner
|
| 27 |
+
coords = torch.arange(win_size, dtype=dtype, device=device) - (win_size - 1) / 2
|
| 28 |
+
g = coords**2
|
| 29 |
+
g = torch.exp(-(g.unsqueeze(0) + g.unsqueeze(1)) / (2.0 * sigma**2))
|
| 30 |
+
g /= torch.sum(g)
|
| 31 |
+
return g
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _vif_per_channel(preds: Tensor, target: Tensor, sigma_n_sq: float) -> Tensor:
|
| 35 |
+
dtype = preds.dtype
|
| 36 |
+
device = preds.device
|
| 37 |
+
|
| 38 |
+
preds = preds.unsqueeze(1) # Add channel dimension
|
| 39 |
+
target = target.unsqueeze(1)
|
| 40 |
+
# Constant for numerical stability
|
| 41 |
+
eps = torch.tensor(1e-10, dtype=dtype, device=device)
|
| 42 |
+
|
| 43 |
+
sigma_n_sq = torch.tensor(sigma_n_sq, dtype=dtype, device=device)
|
| 44 |
+
|
| 45 |
+
preds_vif = torch.zeros(preds.size(0), dtype=dtype, device=device)
|
| 46 |
+
target_vif = torch.zeros(preds.size(0), dtype=dtype, device=device)
|
| 47 |
+
|
| 48 |
+
for scale in range(4):
|
| 49 |
+
n = 2.0 ** (4 - scale) + 1
|
| 50 |
+
kernel = _filter(n, n / 5, dtype=dtype, device=device)[None, None, :]
|
| 51 |
+
|
| 52 |
+
if scale > 0:
|
| 53 |
+
target = conv2d(target, kernel)[:, :, ::2, ::2]
|
| 54 |
+
preds = conv2d(preds, kernel)[:, :, ::2, ::2]
|
| 55 |
+
|
| 56 |
+
mu_target = conv2d(target, kernel)
|
| 57 |
+
mu_preds = conv2d(preds, kernel)
|
| 58 |
+
mu_target_sq = mu_target**2
|
| 59 |
+
mu_preds_sq = mu_preds**2
|
| 60 |
+
mu_target_preds = mu_target * mu_preds
|
| 61 |
+
|
| 62 |
+
sigma_target_sq = torch.clamp(conv2d(target**2, kernel) - mu_target_sq, min=0.0)
|
| 63 |
+
sigma_preds_sq = torch.clamp(conv2d(preds**2, kernel) - mu_preds_sq, min=0.0)
|
| 64 |
+
sigma_target_preds = conv2d(target * preds, kernel) - mu_target_preds
|
| 65 |
+
|
| 66 |
+
g = sigma_target_preds / (sigma_target_sq + eps)
|
| 67 |
+
sigma_v_sq = sigma_preds_sq - g * sigma_target_preds
|
| 68 |
+
|
| 69 |
+
mask = sigma_target_sq < eps
|
| 70 |
+
g[mask] = 0
|
| 71 |
+
sigma_v_sq[mask] = sigma_preds_sq[mask]
|
| 72 |
+
sigma_target_sq[mask] = 0
|
| 73 |
+
|
| 74 |
+
mask = sigma_preds_sq < eps
|
| 75 |
+
g[mask] = 0
|
| 76 |
+
sigma_v_sq[mask] = 0
|
| 77 |
+
|
| 78 |
+
mask = g < 0
|
| 79 |
+
sigma_v_sq[mask] = sigma_preds_sq[mask]
|
| 80 |
+
g[mask] = 0
|
| 81 |
+
sigma_v_sq = torch.clamp(sigma_v_sq, min=eps)
|
| 82 |
+
|
| 83 |
+
preds_vif += torch.sum(torch.log10(1.0 + (g**2.0) * sigma_target_sq / (sigma_v_sq + sigma_n_sq)), dim=[1, 2, 3])
|
| 84 |
+
target_vif += torch.sum(torch.log10(1.0 + sigma_target_sq / sigma_n_sq), dim=[1, 2, 3])
|
| 85 |
+
|
| 86 |
+
return preds_vif / target_vif
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def visual_information_fidelity(
|
| 90 |
+
preds: Tensor,
|
| 91 |
+
target: Tensor,
|
| 92 |
+
sigma_n_sq: float = 2.0,
|
| 93 |
+
reduction: Literal["mean", "none"] = "mean",
|
| 94 |
+
) -> Tensor:
|
| 95 |
+
"""Compute Pixel-Based Visual Information Fidelity (VIF-P).
|
| 96 |
+
|
| 97 |
+
VIF is a full-reference metric that measures the amount of visual information
|
| 98 |
+
preserved in a distorted image compared to the reference image.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
preds: Predicted images of shape (N, C, H, W). Height and width must be at least 41.
|
| 102 |
+
target: Ground truth images of shape (N, C, H, W). Must match preds in shape.
|
| 103 |
+
sigma_n_sq: Variance of the visual noise. Default: 2.0.
|
| 104 |
+
reduction: Method for reducing the metric across the batch.
|
| 105 |
+
- "mean": Return a tensor average over the batch.
|
| 106 |
+
- "none": Return a VIF score for each sample as a 1D tensor of shape (N,).
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
torch.Tensor: VIF score(s). The shape depends on the `reduction` argument:
|
| 110 |
+
- If ``reduction="mean"``, returns a scalar tensor.
|
| 111 |
+
- If ``reduction="none"``, returns a tensor of shape ``(N,)``.
|
| 112 |
+
|
| 113 |
+
Raises:
|
| 114 |
+
ValueError: If input dimensions are smaller than ``41x41``.
|
| 115 |
+
ValueError: If ``preds`` and ``target`` shapes don't match.
|
| 116 |
+
ValueError: If ``reduction`` is not ``"mean"`` or ``"none"``.
|
| 117 |
+
|
| 118 |
+
Example:
|
| 119 |
+
>>> from torchmetrics.functional.image import visual_information_fidelity
|
| 120 |
+
>>> preds = torch.randn(4, 3, 41, 41, generator=torch.Generator().manual_seed(42))
|
| 121 |
+
>>> target = torch.randn(4, 3, 41, 41, generator=torch.Generator().manual_seed(43))
|
| 122 |
+
>>> visual_information_fidelity(preds, target, reduction="none")
|
| 123 |
+
tensor([0.0040, 0.0049, 0.0017, 0.0039])
|
| 124 |
+
|
| 125 |
+
"""
|
| 126 |
+
# This code is inspired by
|
| 127 |
+
# https://github.com/photosynthesis-team/piq/blob/01e16b7d8c76bc8765fb6a69560d806148b8046a/piq/vif.py and
|
| 128 |
+
# https://github.com/andrewekhalel/sewar/blob/ac76e7bc75732fde40bb0d3908f4b6863400cc27/sewar/full_ref.py#L357.
|
| 129 |
+
|
| 130 |
+
if preds.size(-1) < 41 or preds.size(-2) < 41:
|
| 131 |
+
raise ValueError(f"Invalid size of preds. Expected at least 41x41, but got {preds.size(-1)}x{preds.size(-2)}!")
|
| 132 |
+
|
| 133 |
+
if target.size(-1) < 41 or target.size(-2) < 41:
|
| 134 |
+
raise ValueError(
|
| 135 |
+
f"Invalid size of target. Expected at least 41x41, but got {target.size(-1)}x{target.size(-2)}!"
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
if preds.shape != target.shape:
|
| 139 |
+
raise ValueError(f"`preds` and `target` must have the same shape, but got {preds.shape} vs {target.shape}.")
|
| 140 |
+
|
| 141 |
+
if reduction not in ("mean", "none"):
|
| 142 |
+
raise ValueError(f"Argument `reduction` must be 'mean' or 'none', but got {reduction}")
|
| 143 |
+
|
| 144 |
+
per_channel_scores = [
|
| 145 |
+
_vif_per_channel(preds[:, i, :, :], target[:, i, :, :], sigma_n_sq) for i in range(preds.size(1))
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
vif_per_sample = dim_zero_cat(
|
| 149 |
+
torch.stack(per_channel_scores, dim=0).mean(0) if preds.size(1) > 1 else per_channel_scores[0]
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
if reduction == "mean":
|
| 153 |
+
return vif_per_sample.mean()
|
| 154 |
+
return vif_per_sample
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from torchmetrics.functional.multimodal.lve import lip_vertex_error
|
| 15 |
+
from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_10
|
| 16 |
+
|
| 17 |
+
__all__ = ["lip_vertex_error"]
|
| 18 |
+
|
| 19 |
+
if _TRANSFORMERS_GREATER_EQUAL_4_10:
|
| 20 |
+
from torchmetrics.functional.multimodal.clip_iqa import clip_image_quality_assessment
|
| 21 |
+
from torchmetrics.functional.multimodal.clip_score import clip_score
|
| 22 |
+
|
| 23 |
+
__all__ += ["clip_image_quality_assessment", "clip_score"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_iqa.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING, Literal, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.functional.multimodal.clip_score import _get_clip_model_and_processor
|
| 20 |
+
from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout
|
| 21 |
+
from torchmetrics.utilities.imports import _PIQ_GREATER_EQUAL_0_8, _TRANSFORMERS_GREATER_EQUAL_4_10
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from transformers import CLIPModel as _CLIPModel
|
| 25 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 26 |
+
|
| 27 |
+
if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10:
|
| 28 |
+
from transformers import CLIPModel as _CLIPModel
|
| 29 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 30 |
+
|
| 31 |
+
def _download_clip_for_iqa_metric() -> None:
|
| 32 |
+
_CLIPModel.from_pretrained("openai/clip-vit-base-patch16", resume_download=True)
|
| 33 |
+
_CLIPProcessor.from_pretrained("openai/clip-vit-base-patch16", resume_download=True)
|
| 34 |
+
|
| 35 |
+
if not _try_proceed_with_timeout(_download_clip_for_iqa_metric):
|
| 36 |
+
__doctest_skip__ = ["clip_image_quality_assessment"]
|
| 37 |
+
else:
|
| 38 |
+
__doctest_skip__ = ["clip_image_quality_assessment"]
|
| 39 |
+
|
| 40 |
+
if not _PIQ_GREATER_EQUAL_0_8:
|
| 41 |
+
__doctest_skip__ = ["clip_image_quality_assessment"]
|
| 42 |
+
|
| 43 |
+
_PROMPTS: dict[str, tuple[str, str]] = {
|
| 44 |
+
"quality": ("Good photo.", "Bad photo."),
|
| 45 |
+
"brightness": ("Bright photo.", "Dark photo."),
|
| 46 |
+
"noisiness": ("Clean photo.", "Noisy photo."),
|
| 47 |
+
"colorfullness": ("Colorful photo.", "Dull photo."),
|
| 48 |
+
"sharpness": ("Sharp photo.", "Blurry photo."),
|
| 49 |
+
"contrast": ("High contrast photo.", "Low contrast photo."),
|
| 50 |
+
"complexity": ("Complex photo.", "Simple photo."),
|
| 51 |
+
"natural": ("Natural photo.", "Synthetic photo."),
|
| 52 |
+
"happy": ("Happy photo.", "Sad photo."),
|
| 53 |
+
"scary": ("Scary photo.", "Peaceful photo."),
|
| 54 |
+
"new": ("New photo.", "Old photo."),
|
| 55 |
+
"warm": ("Warm photo.", "Cold photo."),
|
| 56 |
+
"real": ("Real photo.", "Abstract photo."),
|
| 57 |
+
"beautiful": ("Beautiful photo.", "Ugly photo."),
|
| 58 |
+
"lonely": ("Lonely photo.", "Sociable photo."),
|
| 59 |
+
"relaxing": ("Relaxing photo.", "Stressful photo."),
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _get_clip_iqa_model_and_processor(
|
| 64 |
+
model_name_or_path: Literal[
|
| 65 |
+
"clip_iqa",
|
| 66 |
+
"openai/clip-vit-base-patch16",
|
| 67 |
+
"openai/clip-vit-base-patch32",
|
| 68 |
+
"openai/clip-vit-large-patch14-336",
|
| 69 |
+
"openai/clip-vit-large-patch14",
|
| 70 |
+
],
|
| 71 |
+
) -> tuple["_CLIPModel", "_CLIPProcessor"]:
|
| 72 |
+
"""Extract the CLIP model and processor from the model name or path."""
|
| 73 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 74 |
+
|
| 75 |
+
if model_name_or_path == "clip_iqa":
|
| 76 |
+
if not _PIQ_GREATER_EQUAL_0_8:
|
| 77 |
+
raise ValueError(
|
| 78 |
+
"For metric `clip_iqa` to work with argument `model_name_or_path` set to default value `'clip_iqa'`"
|
| 79 |
+
", package `piq` version v0.8.0 or later must be installed. Either install with `pip install piq` or"
|
| 80 |
+
"`pip install torchmetrics[multimodal]`"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
import piq
|
| 84 |
+
|
| 85 |
+
model = piq.clip_iqa.clip.load().eval()
|
| 86 |
+
# any model checkpoint can be used here because the tokenizer is the same for all
|
| 87 |
+
processor = _CLIPProcessor.from_pretrained("openai/clip-vit-base-patch16")
|
| 88 |
+
return model, processor
|
| 89 |
+
return _get_clip_model_and_processor(model_name_or_path)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _clip_iqa_format_prompts(
|
| 93 |
+
prompts: tuple[Union[str, tuple[str, str]], ...] = ("quality",),
|
| 94 |
+
) -> tuple[list[str], list[str]]:
|
| 95 |
+
"""Converts the provided keywords into a list of prompts for the model to calculate the anchor vectors.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
prompts: A string, tuple of strings or nested tuple of strings. If a single string is provided, it must be one
|
| 99 |
+
of the available prompts (see above). Else the input is expected to be a tuple, where each element can
|
| 100 |
+
be one of two things: either a string or a tuple of strings. If a string is provided, it must be one of the
|
| 101 |
+
available prompts (see above). If tuple is provided, it must be of length 2 and the first string must be a
|
| 102 |
+
positive prompt and the second string must be a negative prompt.
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
Tuple containing a list of prompts and a list of the names of the prompts. The first list is double the length
|
| 106 |
+
of the second list.
|
| 107 |
+
|
| 108 |
+
Examples::
|
| 109 |
+
|
| 110 |
+
>>> # single prompt
|
| 111 |
+
>>> _clip_iqa_format_prompts(("quality",))
|
| 112 |
+
(['Good photo.', 'Bad photo.'], ['quality'])
|
| 113 |
+
>>> # multiple prompts
|
| 114 |
+
>>> _clip_iqa_format_prompts(("quality", "brightness"))
|
| 115 |
+
(['Good photo.', 'Bad photo.', 'Bright photo.', 'Dark photo.'], ['quality', 'brightness'])
|
| 116 |
+
>>> # Custom prompts
|
| 117 |
+
>>> _clip_iqa_format_prompts(("quality", ("Super good photo.", "Super bad photo.")))
|
| 118 |
+
(['Good photo.', 'Bad photo.', 'Super good photo.', 'Super bad photo.'], ['quality', 'user_defined_0'])
|
| 119 |
+
|
| 120 |
+
"""
|
| 121 |
+
if not isinstance(prompts, tuple):
|
| 122 |
+
raise ValueError("Argument `prompts` must be a tuple containing strings or tuples of strings")
|
| 123 |
+
|
| 124 |
+
prompts_names: list[str] = []
|
| 125 |
+
prompts_list: list[str] = []
|
| 126 |
+
count = 0
|
| 127 |
+
for p in prompts:
|
| 128 |
+
if not isinstance(p, (str, tuple)):
|
| 129 |
+
raise ValueError("Argument `prompts` must be a tuple containing strings or tuples of strings")
|
| 130 |
+
if isinstance(p, str):
|
| 131 |
+
if p not in _PROMPTS:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"All elements of `prompts` must be one of {_PROMPTS.keys()} if not custom tuple prompts, got {p}."
|
| 134 |
+
)
|
| 135 |
+
prompts_names.append(p)
|
| 136 |
+
prompts_list.extend(_PROMPTS[p])
|
| 137 |
+
if isinstance(p, tuple) and len(p) != 2:
|
| 138 |
+
raise ValueError("If a tuple is provided in argument `prompts`, it must be of length 2")
|
| 139 |
+
if isinstance(p, tuple):
|
| 140 |
+
prompts_names.append(f"user_defined_{count}")
|
| 141 |
+
prompts_list.extend(p)
|
| 142 |
+
count += 1
|
| 143 |
+
|
| 144 |
+
return prompts_list, prompts_names
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _clip_iqa_get_anchor_vectors(
|
| 148 |
+
model_name_or_path: str,
|
| 149 |
+
model: "_CLIPModel",
|
| 150 |
+
processor: "_CLIPProcessor",
|
| 151 |
+
prompts_list: list[str],
|
| 152 |
+
device: Union[str, torch.device],
|
| 153 |
+
) -> Tensor:
|
| 154 |
+
"""Calculates the anchor vectors for the CLIP IQA metric.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
model_name_or_path: string indicating the version of the CLIP model to use.
|
| 158 |
+
model: The CLIP model
|
| 159 |
+
processor: The CLIP processor
|
| 160 |
+
prompts_list: A list of prompts
|
| 161 |
+
device: The device to use for the calculation
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
if model_name_or_path == "clip_iqa":
|
| 165 |
+
text_processed = processor(text=prompts_list)
|
| 166 |
+
anchors_text = torch.zeros(
|
| 167 |
+
len(prompts_list), processor.tokenizer.model_max_length, dtype=torch.long, device=device
|
| 168 |
+
)
|
| 169 |
+
for i, tp in enumerate(text_processed["input_ids"]):
|
| 170 |
+
anchors_text[i, : len(tp)] = torch.tensor(tp, dtype=torch.long, device=device)
|
| 171 |
+
|
| 172 |
+
anchors = model.encode_text(anchors_text).float()
|
| 173 |
+
else:
|
| 174 |
+
text_processed = processor(text=prompts_list, return_tensors="pt", padding=True)
|
| 175 |
+
anchors = model.get_text_features(
|
| 176 |
+
text_processed["input_ids"].to(device), text_processed["attention_mask"].to(device)
|
| 177 |
+
)
|
| 178 |
+
return anchors / anchors.norm(p=2, dim=-1, keepdim=True)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _clip_iqa_update(
|
| 182 |
+
model_name_or_path: str,
|
| 183 |
+
images: Tensor,
|
| 184 |
+
model: "_CLIPModel",
|
| 185 |
+
processor: "_CLIPProcessor",
|
| 186 |
+
data_range: float,
|
| 187 |
+
device: Union[str, torch.device],
|
| 188 |
+
) -> Tensor:
|
| 189 |
+
images = images / float(data_range)
|
| 190 |
+
"""Update function for CLIP IQA."""
|
| 191 |
+
if model_name_or_path == "clip_iqa":
|
| 192 |
+
# default mean and std from clip paper, see:
|
| 193 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/utils/constants.py
|
| 194 |
+
default_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073], device=device).view(1, 3, 1, 1)
|
| 195 |
+
default_std = torch.tensor([0.26862954, 0.26130258, 0.27577711], device=device).view(1, 3, 1, 1)
|
| 196 |
+
images = (images - default_mean) / default_std
|
| 197 |
+
img_features = model.encode_image(images.float(), pos_embedding=False).float()
|
| 198 |
+
else:
|
| 199 |
+
processed_input = processor(images=[i.cpu() for i in images], return_tensors="pt", padding=True)
|
| 200 |
+
img_features = model.get_image_features(processed_input["pixel_values"].to(device))
|
| 201 |
+
return img_features / img_features.norm(p=2, dim=-1, keepdim=True)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _clip_iqa_compute(
|
| 205 |
+
img_features: Tensor,
|
| 206 |
+
anchors: Tensor,
|
| 207 |
+
prompts_names: list[str],
|
| 208 |
+
format_as_dict: bool = True,
|
| 209 |
+
) -> Union[Tensor, dict[str, Tensor]]:
|
| 210 |
+
"""Final computation of CLIP IQA."""
|
| 211 |
+
logits_per_image = 100 * img_features @ anchors.t()
|
| 212 |
+
probs = logits_per_image.reshape(logits_per_image.shape[0], -1, 2).softmax(-1)[:, :, 0]
|
| 213 |
+
if len(prompts_names) == 1:
|
| 214 |
+
return probs.squeeze()
|
| 215 |
+
if format_as_dict:
|
| 216 |
+
return {p: probs[:, i] for i, p in enumerate(prompts_names)}
|
| 217 |
+
return probs
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def clip_image_quality_assessment(
|
| 221 |
+
images: Tensor,
|
| 222 |
+
model_name_or_path: Literal[
|
| 223 |
+
"clip_iqa",
|
| 224 |
+
"openai/clip-vit-base-patch16",
|
| 225 |
+
"openai/clip-vit-base-patch32",
|
| 226 |
+
"openai/clip-vit-large-patch14-336",
|
| 227 |
+
"openai/clip-vit-large-patch14",
|
| 228 |
+
] = "clip_iqa",
|
| 229 |
+
data_range: float = 1.0,
|
| 230 |
+
prompts: tuple[Union[str, tuple[str, str]], ...] = ("quality",),
|
| 231 |
+
) -> Union[Tensor, dict[str, Tensor]]:
|
| 232 |
+
"""Calculates `CLIP-IQA`_, that can be used to measure the visual content of images.
|
| 233 |
+
|
| 234 |
+
The metric is based on the `CLIP`_ model, which is a neural network trained on a variety of (image, text) pairs to
|
| 235 |
+
be able to generate a vector representation of the image and the text that is similar if the image and text are
|
| 236 |
+
semantically similar.
|
| 237 |
+
|
| 238 |
+
The metric works by calculating the cosine similarity between user provided images and pre-defined prompts. The
|
| 239 |
+
prompts always come in pairs of "positive" and "negative" such as "Good photo." and "Bad photo.". By calculating
|
| 240 |
+
the similartity between image embeddings and both the "positive" and "negative" prompt, the metric can determine
|
| 241 |
+
which prompt the image is more similar to. The metric then returns the probability that the image is more similar
|
| 242 |
+
to the first prompt than the second prompt.
|
| 243 |
+
|
| 244 |
+
Build in prompts are:
|
| 245 |
+
* quality: "Good photo." vs "Bad photo."
|
| 246 |
+
* brightness: "Bright photo." vs "Dark photo."
|
| 247 |
+
* noisiness: "Clean photo." vs "Noisy photo."
|
| 248 |
+
* colorfullness: "Colorful photo." vs "Dull photo."
|
| 249 |
+
* sharpness: "Sharp photo." vs "Blurry photo."
|
| 250 |
+
* contrast: "High contrast photo." vs "Low contrast photo."
|
| 251 |
+
* complexity: "Complex photo." vs "Simple photo."
|
| 252 |
+
* natural: "Natural photo." vs "Synthetic photo."
|
| 253 |
+
* happy: "Happy photo." vs "Sad photo."
|
| 254 |
+
* scary: "Scary photo." vs "Peaceful photo."
|
| 255 |
+
* new: "New photo." vs "Old photo."
|
| 256 |
+
* warm: "Warm photo." vs "Cold photo."
|
| 257 |
+
* real: "Real photo." vs "Abstract photo."
|
| 258 |
+
* beautiful: "Beautiful photo." vs "Ugly photo."
|
| 259 |
+
* lonely: "Lonely photo." vs "Sociable photo."
|
| 260 |
+
* relaxing: "Relaxing photo." vs "Stressful photo."
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
images: Either a single ``[N, C, H, W]`` tensor or a list of ``[C, H, W]`` tensors
|
| 264 |
+
model_name_or_path: string indicating the version of the CLIP model to use. By default this argument is set to
|
| 265 |
+
``clip_iqa`` which corresponds to the model used in the original paper. Other available models are
|
| 266 |
+
`"openai/clip-vit-base-patch16"`, `"openai/clip-vit-base-patch32"`, `"openai/clip-vit-large-patch14-336"`
|
| 267 |
+
and `"openai/clip-vit-large-patch14"`
|
| 268 |
+
data_range: The maximum value of the input tensor. For example, if the input images are in range [0, 255],
|
| 269 |
+
data_range should be 255. The images are normalized by this value.
|
| 270 |
+
prompts: A string, tuple of strings or nested tuple of strings. If a single string is provided, it must be one
|
| 271 |
+
of the available prompts (see above). Else the input is expected to be a tuple, where each element can
|
| 272 |
+
be one of two things: either a string or a tuple of strings. If a string is provided, it must be one of the
|
| 273 |
+
available prompts (see above). If tuple is provided, it must be of length 2 and the first string must be a
|
| 274 |
+
positive prompt and the second string must be a negative prompt.
|
| 275 |
+
|
| 276 |
+
.. hint::
|
| 277 |
+
If using the default `clip_iqa` model, the package `piq` must be installed. Either install with
|
| 278 |
+
`pip install piq` or `pip install torchmetrics[multimodal]`.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
A tensor of shape ``(N,)`` if a single prompts is provided. If a list of prompts is provided, a dictionary of
|
| 282 |
+
with the prompts as keys and tensors of shape ``(N,)`` as values.
|
| 283 |
+
|
| 284 |
+
Raises:
|
| 285 |
+
ModuleNotFoundError:
|
| 286 |
+
If transformers package is not installed or version is lower than 4.10.0
|
| 287 |
+
ValueError:
|
| 288 |
+
If not all images have format [C, H, W]
|
| 289 |
+
ValueError:
|
| 290 |
+
If prompts is a tuple and it is not of length 2
|
| 291 |
+
ValueError:
|
| 292 |
+
If prompts is a string and it is not one of the available prompts
|
| 293 |
+
ValueError:
|
| 294 |
+
If prompts is a list of strings and not all strings are one of the available prompts
|
| 295 |
+
|
| 296 |
+
Example::
|
| 297 |
+
Single prompt:
|
| 298 |
+
|
| 299 |
+
>>> from torch import randint
|
| 300 |
+
>>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
|
| 301 |
+
>>> imgs = randint(255, (2, 3, 224, 224)).float()
|
| 302 |
+
>>> clip_image_quality_assessment(imgs, prompts=("quality",))
|
| 303 |
+
tensor([0.8894, 0.8902])
|
| 304 |
+
|
| 305 |
+
Example::
|
| 306 |
+
Multiple prompts:
|
| 307 |
+
|
| 308 |
+
>>> from torch import randint
|
| 309 |
+
>>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
|
| 310 |
+
>>> imgs = randint(255, (2, 3, 224, 224)).float()
|
| 311 |
+
>>> clip_image_quality_assessment(imgs, prompts=("quality", "brightness"))
|
| 312 |
+
{'quality': tensor([0.8693, 0.8705]), 'brightness': tensor([0.5722, 0.4762])}
|
| 313 |
+
|
| 314 |
+
Example::
|
| 315 |
+
Custom prompts. Must always be a tuple of length 2, with a positive and negative prompt.
|
| 316 |
+
|
| 317 |
+
>>> from torch import rand
|
| 318 |
+
>>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
|
| 319 |
+
>>> imgs = randint(255, (2, 3, 224, 224)).float()
|
| 320 |
+
>>> clip_image_quality_assessment(imgs, prompts=(("Super good photo.", "Super bad photo."), "brightness"))
|
| 321 |
+
{'user_defined_0': tensor([0.9578, 0.9654]), 'brightness': tensor([0.5495, 0.5764])}
|
| 322 |
+
|
| 323 |
+
"""
|
| 324 |
+
prompts_list, prompts_names = _clip_iqa_format_prompts(prompts)
|
| 325 |
+
|
| 326 |
+
model, processor = _get_clip_iqa_model_and_processor(model_name_or_path)
|
| 327 |
+
device = images.device
|
| 328 |
+
model = model.to(device)
|
| 329 |
+
|
| 330 |
+
with torch.inference_mode():
|
| 331 |
+
anchors = _clip_iqa_get_anchor_vectors(model_name_or_path, model, processor, prompts_list, device)
|
| 332 |
+
img_features = _clip_iqa_update(model_name_or_path, images, model, processor, data_range, device)
|
| 333 |
+
return _clip_iqa_compute(img_features, anchors, prompts_names)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if TYPE_CHECKING:
|
| 337 |
+
from functools import partial
|
| 338 |
+
from typing import Any, cast
|
| 339 |
+
|
| 340 |
+
images = cast(Any, None)
|
| 341 |
+
|
| 342 |
+
f = partial(clip_image_quality_assessment, images=images)
|
| 343 |
+
f(prompts=("colorfullness",))
|
| 344 |
+
f(
|
| 345 |
+
prompts=("quality", "brightness", "noisiness"),
|
| 346 |
+
)
|
| 347 |
+
f(
|
| 348 |
+
prompts=("quality", "brightness", "noisiness", "colorfullness"),
|
| 349 |
+
)
|
| 350 |
+
f(prompts=(("Photo of a cat", "Photo of a dog"), "quality", ("Colorful photo", "Black and white photo")))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/clip_score.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING, Any, Callable, List, Union, cast
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.utilities import rank_zero_warn
|
| 21 |
+
from torchmetrics.utilities.checks import _SKIP_SLOW_DOCTEST, _try_proceed_with_timeout
|
| 22 |
+
from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_10
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING and _TRANSFORMERS_GREATER_EQUAL_4_10:
|
| 25 |
+
from transformers import CLIPModel as _CLIPModel
|
| 26 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 27 |
+
|
| 28 |
+
if _SKIP_SLOW_DOCTEST and _TRANSFORMERS_GREATER_EQUAL_4_10:
|
| 29 |
+
from transformers import CLIPModel as _CLIPModel
|
| 30 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 31 |
+
|
| 32 |
+
def _download_clip_for_clip_score() -> None:
|
| 33 |
+
_CLIPModel.from_pretrained("openai/clip-vit-large-patch14", resume_download=True)
|
| 34 |
+
_CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14", resume_download=True)
|
| 35 |
+
|
| 36 |
+
if not _try_proceed_with_timeout(_download_clip_for_clip_score):
|
| 37 |
+
__doctest_skip__ = ["clip_score"]
|
| 38 |
+
else:
|
| 39 |
+
__doctest_skip__ = ["clip_score"]
|
| 40 |
+
_CLIPModel = None
|
| 41 |
+
_CLIPProcessor = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class JinaProcessorWrapper:
|
| 45 |
+
"""Wrapper class to convert tensors to PIL images if needed for Jina CLIP model."""
|
| 46 |
+
|
| 47 |
+
def __init__(self, processor: _CLIPProcessor) -> None:
|
| 48 |
+
self.processor = processor
|
| 49 |
+
|
| 50 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 51 |
+
"""Wrap the processor's __call__ method to convert tensors to PIL images if needed."""
|
| 52 |
+
# Check if 'images' is in kwargs and convert tensors to PIL images if needed
|
| 53 |
+
from torchvision.transforms.functional import to_pil_image
|
| 54 |
+
|
| 55 |
+
if "images" in kwargs:
|
| 56 |
+
kwargs["images"] = [
|
| 57 |
+
to_pil_image(img.float().cpu()) if isinstance(img, Tensor) else img for img in kwargs["images"]
|
| 58 |
+
]
|
| 59 |
+
return self.processor(*args, **kwargs)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _detect_modality(input_data: Union[Tensor, List[Tensor], List[str], str]) -> Literal["image", "text"]:
|
| 63 |
+
"""Automatically detect the modality of the input data.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
input_data: Input data that can be either image tensors or text strings
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
str: Either "image" or "text"
|
| 70 |
+
|
| 71 |
+
Raises:
|
| 72 |
+
ValueError: If the input_data is an empty list or modality cannot be determined
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
if isinstance(input_data, Tensor):
|
| 76 |
+
return "image"
|
| 77 |
+
|
| 78 |
+
if isinstance(input_data, list):
|
| 79 |
+
if len(input_data) == 0:
|
| 80 |
+
raise ValueError("Empty input list")
|
| 81 |
+
if isinstance(input_data[0], Tensor):
|
| 82 |
+
return "image"
|
| 83 |
+
if isinstance(input_data[0], str):
|
| 84 |
+
return "text"
|
| 85 |
+
|
| 86 |
+
if isinstance(input_data, str):
|
| 87 |
+
return "text"
|
| 88 |
+
|
| 89 |
+
raise ValueError("Could not automatically determine modality for input_data")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _process_image_data(images: Union[Tensor, List[Tensor]]) -> List[Tensor]:
|
| 93 |
+
"""Helper function to process image data."""
|
| 94 |
+
images = [images] if not isinstance(images, list) and images.ndim == 3 else list(images)
|
| 95 |
+
if not all(i.ndim == 3 for i in images):
|
| 96 |
+
raise ValueError("Expected all images to be 3d but found image that has either more or less")
|
| 97 |
+
return images
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _process_text_data(texts: Union[str, List[str]]) -> List[str]:
|
| 101 |
+
"""Helper function to process text data."""
|
| 102 |
+
if not isinstance(texts, list):
|
| 103 |
+
texts = [texts]
|
| 104 |
+
return texts
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _get_features(
|
| 108 |
+
data: List[Union[Tensor, str]],
|
| 109 |
+
modality: str,
|
| 110 |
+
device: torch.device,
|
| 111 |
+
model: "_CLIPModel",
|
| 112 |
+
processor: "_CLIPProcessor",
|
| 113 |
+
) -> Tensor:
|
| 114 |
+
"""Get features from the CLIP model for either images or text.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
data: List of input data (images or text)
|
| 118 |
+
modality: String indicating the type of input data (must be either "image" or "text")
|
| 119 |
+
device: Device to run the model on
|
| 120 |
+
model: CLIP model instance
|
| 121 |
+
processor: CLIP processor instance
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Tensor of features from the CLIP model
|
| 125 |
+
|
| 126 |
+
Raises:
|
| 127 |
+
ValueError: If modality is not "image" or "text"
|
| 128 |
+
|
| 129 |
+
"""
|
| 130 |
+
if modality == "image":
|
| 131 |
+
image_data = [i for i in data if isinstance(i, Tensor)] # Add type checking for images
|
| 132 |
+
processed = processor(images=[i.cpu() for i in image_data], return_tensors="pt", padding=True)
|
| 133 |
+
return model.get_image_features(processed["pixel_values"].to(device))
|
| 134 |
+
if modality == "text":
|
| 135 |
+
processed = processor(text=data, return_tensors="pt", padding=True)
|
| 136 |
+
if hasattr(model.config, "text_config") and hasattr(model.config.text_config, "max_position_embeddings"):
|
| 137 |
+
max_position_embeddings = model.config.text_config.max_position_embeddings
|
| 138 |
+
if processed["attention_mask"].shape[-1] > max_position_embeddings:
|
| 139 |
+
rank_zero_warn(
|
| 140 |
+
f"Encountered caption longer than {max_position_embeddings=}. Will truncate captions to this"
|
| 141 |
+
"length. If longer captions are needed, initialize argument `model_name_or_path` with a model that"
|
| 142 |
+
"supports longer sequences.",
|
| 143 |
+
UserWarning,
|
| 144 |
+
)
|
| 145 |
+
processed["attention_mask"] = processed["attention_mask"][..., :max_position_embeddings]
|
| 146 |
+
processed["input_ids"] = processed["input_ids"][..., :max_position_embeddings]
|
| 147 |
+
return model.get_text_features(processed["input_ids"].to(device), processed["attention_mask"].to(device))
|
| 148 |
+
raise ValueError(f"invalid modality {modality}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _clip_score_update(
|
| 152 |
+
source: Union[Tensor, List[Tensor], List[str], str],
|
| 153 |
+
target: Union[Tensor, List[Tensor], List[str], str],
|
| 154 |
+
model: _CLIPModel,
|
| 155 |
+
processor: _CLIPProcessor,
|
| 156 |
+
) -> tuple[Tensor, int]:
|
| 157 |
+
"""Update function for CLIP Score."""
|
| 158 |
+
source_modality = _detect_modality(source)
|
| 159 |
+
target_modality = _detect_modality(target)
|
| 160 |
+
|
| 161 |
+
source_data = (
|
| 162 |
+
_process_image_data(cast(Union[Tensor, List[Tensor]], source))
|
| 163 |
+
if source_modality == "image"
|
| 164 |
+
else _process_text_data(cast(Union[str, List[str]], source))
|
| 165 |
+
)
|
| 166 |
+
target_data = (
|
| 167 |
+
_process_image_data(cast(Union[Tensor, List[Tensor]], target))
|
| 168 |
+
if target_modality == "image"
|
| 169 |
+
else _process_text_data(cast(Union[str, List[str]], target))
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if len(source_data) != len(target_data):
|
| 173 |
+
raise ValueError(
|
| 174 |
+
"Expected the number of source and target examples to be the same but got "
|
| 175 |
+
f"{len(source_data)} and {len(target_data)}"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
device = (
|
| 179 |
+
source_data[0].device
|
| 180 |
+
if source_modality == "image" and isinstance(source_data[0], Tensor)
|
| 181 |
+
else target_data[0].device
|
| 182 |
+
if target_modality == "image" and isinstance(target_data[0], Tensor)
|
| 183 |
+
else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 184 |
+
)
|
| 185 |
+
model = model.to(device)
|
| 186 |
+
|
| 187 |
+
source_features = _get_features(
|
| 188 |
+
cast(List[Union[Tensor, str]], source_data), source_modality, device, model, processor
|
| 189 |
+
)
|
| 190 |
+
target_features = _get_features(
|
| 191 |
+
cast(List[Union[Tensor, str]], target_data), target_modality, device, model, processor
|
| 192 |
+
)
|
| 193 |
+
source_features = source_features / source_features.norm(p=2, dim=-1, keepdim=True)
|
| 194 |
+
target_features = target_features / target_features.norm(p=2, dim=-1, keepdim=True)
|
| 195 |
+
|
| 196 |
+
# Calculate cosine similarity
|
| 197 |
+
score = 100 * (source_features * target_features).sum(axis=-1)
|
| 198 |
+
score = score.cpu() if source_modality == "text" and target_modality == "text" else score
|
| 199 |
+
return score, len(source_data)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _get_clip_model_and_processor(
|
| 203 |
+
model_name_or_path: Union[
|
| 204 |
+
Literal[
|
| 205 |
+
"openai/clip-vit-base-patch16",
|
| 206 |
+
"openai/clip-vit-base-patch32",
|
| 207 |
+
"openai/clip-vit-large-patch14-336",
|
| 208 |
+
"openai/clip-vit-large-patch14",
|
| 209 |
+
"jinaai/jina-clip-v2",
|
| 210 |
+
"zer0int/LongCLIP-L-Diffusers",
|
| 211 |
+
"zer0int/LongCLIP-GmP-ViT-L-14",
|
| 212 |
+
],
|
| 213 |
+
Callable[[], tuple[_CLIPModel, _CLIPProcessor]],
|
| 214 |
+
],
|
| 215 |
+
) -> tuple[_CLIPModel, _CLIPProcessor]:
|
| 216 |
+
if callable(model_name_or_path):
|
| 217 |
+
return model_name_or_path()
|
| 218 |
+
|
| 219 |
+
if _TRANSFORMERS_GREATER_EQUAL_4_10:
|
| 220 |
+
from transformers import AutoModel, AutoProcessor
|
| 221 |
+
from transformers import CLIPConfig as _CLIPConfig
|
| 222 |
+
from transformers import CLIPModel as _CLIPModel
|
| 223 |
+
from transformers import CLIPProcessor as _CLIPProcessor
|
| 224 |
+
|
| 225 |
+
if "openai" in model_name_or_path:
|
| 226 |
+
model = _CLIPModel.from_pretrained(model_name_or_path)
|
| 227 |
+
processor = _CLIPProcessor.from_pretrained(model_name_or_path)
|
| 228 |
+
elif "jinaai" in model_name_or_path:
|
| 229 |
+
model = AutoModel.from_pretrained(model_name_or_path, trust_remote_code=True)
|
| 230 |
+
processor = JinaProcessorWrapper(
|
| 231 |
+
processor=AutoProcessor.from_pretrained(model_name_or_path, trust_remote_code=True)
|
| 232 |
+
)
|
| 233 |
+
elif "zer0int" in model_name_or_path:
|
| 234 |
+
config = _CLIPConfig.from_pretrained(model_name_or_path)
|
| 235 |
+
config.text_config.max_position_embeddings = 248
|
| 236 |
+
model = _CLIPModel.from_pretrained(model_name_or_path, config=config)
|
| 237 |
+
processor = _CLIPProcessor.from_pretrained(model_name_or_path, padding="max_length", max_length=248)
|
| 238 |
+
else:
|
| 239 |
+
raise ValueError(f"Invalid model_name_or_path {model_name_or_path}. Not supported by `clip_score` metric.")
|
| 240 |
+
return model, processor
|
| 241 |
+
|
| 242 |
+
raise ModuleNotFoundError(
|
| 243 |
+
"`clip_score` metric requires `transformers` package be installed."
|
| 244 |
+
" Either install with `pip install transformers>=4.10.0` or `pip install torchmetrics[multimodal]`."
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def clip_score(
|
| 249 |
+
source: Union[Tensor, List[Tensor], List[str], str],
|
| 250 |
+
target: Union[Tensor, List[Tensor], List[str], str],
|
| 251 |
+
model_name_or_path: Union[
|
| 252 |
+
Literal[
|
| 253 |
+
"openai/clip-vit-base-patch16",
|
| 254 |
+
"openai/clip-vit-base-patch32",
|
| 255 |
+
"openai/clip-vit-large-patch14-336",
|
| 256 |
+
"openai/clip-vit-large-patch14",
|
| 257 |
+
"jinaai/jina-clip-v2",
|
| 258 |
+
"zer0int/LongCLIP-L-Diffusers",
|
| 259 |
+
"zer0int/LongCLIP-GmP-ViT-L-14",
|
| 260 |
+
],
|
| 261 |
+
Callable[[], tuple[_CLIPModel, _CLIPProcessor]],
|
| 262 |
+
] = "openai/clip-vit-large-patch14",
|
| 263 |
+
) -> Tensor:
|
| 264 |
+
r"""Calculates `CLIP Score`_ which is a text-to-image similarity metric.
|
| 265 |
+
|
| 266 |
+
CLIP Score is a reference free metric that can be used to evaluate the correlation between a generated caption for
|
| 267 |
+
an image and the actual content of the image, as well as the similarity between texts or images. It has been found
|
| 268 |
+
to be highly correlated with human judgement. The metric is defined as:
|
| 269 |
+
|
| 270 |
+
.. math::
|
| 271 |
+
\text{CLIPScore(I, C)} = max(100 * cos(E_I, E_C), 0)
|
| 272 |
+
|
| 273 |
+
which corresponds to the cosine similarity between visual `CLIP`_ embedding :math:`E_i` for an image :math:`i` and
|
| 274 |
+
textual CLIP embedding :math:`E_C` for an caption :math:`C`. The score is bound between 0 and 100 and the closer
|
| 275 |
+
to 100 the better.
|
| 276 |
+
|
| 277 |
+
Additionally, the CLIP Score can be calculated for the same modalities:
|
| 278 |
+
|
| 279 |
+
.. math::
|
| 280 |
+
\text{CLIPScore(I_1, I_2)} = max(100 * cos(E_{I_1}, E_{I_2}), 0)
|
| 281 |
+
|
| 282 |
+
where :math:`E_{I_1}` and :math:`E_{I_2}` are the visual embeddings for images :math:`I_1` and :math:`I_2`.
|
| 283 |
+
|
| 284 |
+
.. math::
|
| 285 |
+
\text{CLIPScore(T_1, T_2)} = max(100 * cos(E_{T_1}, E_{T_2}), 0)
|
| 286 |
+
|
| 287 |
+
where :math:`E_{T_1}` and :math:`E_{T_2}` are the textual embeddings for texts :math:`T_1` and :math:`T_2`.
|
| 288 |
+
|
| 289 |
+
.. note:: Metric is not scriptable
|
| 290 |
+
|
| 291 |
+
.. note::
|
| 292 |
+
The default CLIP and processor used in this implementation has a maximum sequence length of 77 for text
|
| 293 |
+
inputs. If you need to process longer captions, you can use the `zer0int/LongCLIP-L-Diffusers` model which
|
| 294 |
+
has a maximum sequence length of 248.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
source: Source input. This can be:
|
| 298 |
+
- Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors.
|
| 299 |
+
- Text: Either a single caption or a list of captions.
|
| 300 |
+
target: Target input. This can be:
|
| 301 |
+
- Images: Either a single [N, C, H, W] tensor or a list of [C, H, W] tensors.
|
| 302 |
+
- Text: Either a single caption or a list of captions.
|
| 303 |
+
model_name_or_path: String indicating the version of the CLIP model to use. Available models are:
|
| 304 |
+
- `"openai/clip-vit-base-patch16"`
|
| 305 |
+
- `"openai/clip-vit-base-patch32"`
|
| 306 |
+
- `"openai/clip-vit-large-patch14-336"`
|
| 307 |
+
- `"openai/clip-vit-large-patch14"`
|
| 308 |
+
- `"jinaai/jina-clip-v2"`
|
| 309 |
+
- `"zer0int/LongCLIP-L-Diffusers"`
|
| 310 |
+
- `"zer0int/LongCLIP-GmP-ViT-L-14"`
|
| 311 |
+
|
| 312 |
+
Alternatively, a callable function that returns a tuple of CLIP compatible model and processor instances
|
| 313 |
+
can be passed in. By compatible, we mean that the processors `__call__` method should accept a list of
|
| 314 |
+
strings and list of images and that the model should have a `get_image_features` and `get_text_features`
|
| 315 |
+
methods.
|
| 316 |
+
|
| 317 |
+
Raises:
|
| 318 |
+
ModuleNotFoundError:
|
| 319 |
+
If transformers package is not installed or version is lower than 4.10.0
|
| 320 |
+
ValueError:
|
| 321 |
+
If not all images have format [C, H, W]
|
| 322 |
+
ValueError:
|
| 323 |
+
If the number of images and captions do not match
|
| 324 |
+
|
| 325 |
+
Example:
|
| 326 |
+
>>> from torchmetrics.functional.multimodal import clip_score
|
| 327 |
+
>>> image = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42))
|
| 328 |
+
>>> score = clip_score(image, "a photo of a cat", "openai/clip-vit-base-patch16")
|
| 329 |
+
>>> score.detach().round(decimals=3)
|
| 330 |
+
tensor(24.4260)
|
| 331 |
+
|
| 332 |
+
Example:
|
| 333 |
+
>>> from torchmetrics.functional.multimodal import clip_score
|
| 334 |
+
>>> image1 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(42))
|
| 335 |
+
>>> image2 = torch.randint(255, (3, 224, 224), generator=torch.Generator().manual_seed(43))
|
| 336 |
+
>>> score = clip_score(image1, image2, "openai/clip-vit-base-patch16")
|
| 337 |
+
>>> score.detach().round(decimals=3)
|
| 338 |
+
tensor(99.4860)
|
| 339 |
+
|
| 340 |
+
Example:
|
| 341 |
+
>>> from torchmetrics.functional.multimodal import clip_score
|
| 342 |
+
>>> score = clip_score(
|
| 343 |
+
... "28-year-old chef found dead in San Francisco mall",
|
| 344 |
+
... "A 28-year-old chef who recently moved to San Francisco was found dead.",
|
| 345 |
+
... "openai/clip-vit-base-patch16"
|
| 346 |
+
... )
|
| 347 |
+
>>> score.detach().round(decimals=3)
|
| 348 |
+
tensor(91.3950)
|
| 349 |
+
|
| 350 |
+
"""
|
| 351 |
+
model, processor = _get_clip_model_and_processor(model_name_or_path)
|
| 352 |
+
score, _ = _clip_score_update(source, target, model, processor)
|
| 353 |
+
score = score.mean(0)
|
| 354 |
+
return torch.max(score, torch.zeros_like(score))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/multimodal/lve.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import List
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def lip_vertex_error(
|
| 21 |
+
vertices_pred: Tensor,
|
| 22 |
+
vertices_gt: Tensor,
|
| 23 |
+
mouth_map: List[int],
|
| 24 |
+
validate_args: bool = True,
|
| 25 |
+
) -> Tensor:
|
| 26 |
+
r"""Compute Lip Vertex Error (LVE) for 3D talking head evaluation.
|
| 27 |
+
|
| 28 |
+
The Lip Vertex Error (LVE) metric evaluates the quality of lip synchronization in 3D facial animations by measuring
|
| 29 |
+
the maximum Euclidean distance (L2 error) between corresponding lip vertices of the generated and ground truth
|
| 30 |
+
meshes for each frame. The metric is defined as:
|
| 31 |
+
|
| 32 |
+
.. math::
|
| 33 |
+
\text{LVE} = \frac{1}{N} \sum_{i=1}^{N} \max_{v \in \text{lip}} \|x_{i,v} - \hat{x}_{i,v}\|_2^2
|
| 34 |
+
|
| 35 |
+
where :math:`N` is the number of frames, :math:`x_{i,v}` represents the 3D coordinates of vertex :math:`v` in the
|
| 36 |
+
lip region of the ground truth frame :math:`i`, and :math:`\hat{x}_{i,v}` represents the corresponding vertex in
|
| 37 |
+
the predicted frame. The metric computes the maximum squared L2 distance between corresponding lip vertices for each
|
| 38 |
+
frame and averages across all frames. A lower LVE value indicates better lip synchronization quality.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vertices_pred: Predicted vertices tensor of shape (T, V, 3) where T is number of frames,
|
| 42 |
+
V is number of vertices, and 3 represents XYZ coordinates
|
| 43 |
+
vertices_gt: Ground truth vertices tensor of shape (T', V, 3) where T' can be different from T
|
| 44 |
+
mouth_map: List of vertex indices corresponding to the mouth region
|
| 45 |
+
validate_args: bool indicating if input arguments and tensors should be validated for correctness.
|
| 46 |
+
Set to ``False`` for faster computations.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
torch.Tensor: Scalar tensor containing the mean LVE value across all frames
|
| 50 |
+
|
| 51 |
+
Raises:
|
| 52 |
+
ValueError:
|
| 53 |
+
If the number of dimensions of `vertices_pred` or `vertices_gt` is not 3.
|
| 54 |
+
If vertex dimensions (V) or coordinate dimensions (3) don't match
|
| 55 |
+
If ``mouth_map`` is empty or contains invalid indices
|
| 56 |
+
|
| 57 |
+
Example:
|
| 58 |
+
>>> import torch
|
| 59 |
+
>>> from torchmetrics.functional.multimodal import lip_vertex_error
|
| 60 |
+
>>> vertices_pred = torch.randn(10, 100, 3, generator=torch.manual_seed(42))
|
| 61 |
+
>>> vertices_gt = torch.randn(10, 100, 3, generator=torch.manual_seed(43))
|
| 62 |
+
>>> mouth_map = [0, 1, 2, 3, 4]
|
| 63 |
+
>>> lip_vertex_error(vertices_pred, vertices_gt, mouth_map)
|
| 64 |
+
tensor(12.7688)
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
if validate_args:
|
| 68 |
+
if vertices_pred.ndim != 3 or vertices_gt.ndim != 3:
|
| 69 |
+
raise ValueError(
|
| 70 |
+
f"Expected both vertices_pred and vertices_gt to have 3 dimensions but got "
|
| 71 |
+
f"{vertices_pred.ndim} and {vertices_gt.ndim} dimensions respectively."
|
| 72 |
+
)
|
| 73 |
+
if vertices_pred.shape[1:] != vertices_gt.shape[1:]:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
f"Expected vertices_pred and vertices_gt to have same vertex and coordinate dimensions but got "
|
| 76 |
+
f"shapes {vertices_pred.shape} and {vertices_gt.shape}."
|
| 77 |
+
)
|
| 78 |
+
if not mouth_map:
|
| 79 |
+
raise ValueError("mouth_map cannot be empty.")
|
| 80 |
+
if max(mouth_map) >= vertices_pred.shape[1]:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
f"mouth_map contains invalid vertex indices. Max index {max(mouth_map)} is larger than "
|
| 83 |
+
f"number of vertices {vertices_pred.shape[1]}."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
min_frames = min(vertices_pred.shape[0], vertices_gt.shape[0])
|
| 87 |
+
vertices_pred = vertices_pred[:min_frames]
|
| 88 |
+
vertices_gt = vertices_gt[:min_frames]
|
| 89 |
+
|
| 90 |
+
diff = vertices_gt[:, mouth_map, :] - vertices_pred[:, mouth_map, :] # Shape: (T, M, 3)
|
| 91 |
+
sq_dist = torch.sum(diff**2, dim=-1) # Shape: (T, M)
|
| 92 |
+
max_per_frame = torch.max(sq_dist, dim=1).values # Shape: (T,)
|
| 93 |
+
return torch.mean(max_per_frame)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from torchmetrics.functional.nominal.cramers import cramers_v, cramers_v_matrix
|
| 16 |
+
from torchmetrics.functional.nominal.fleiss_kappa import fleiss_kappa
|
| 17 |
+
from torchmetrics.functional.nominal.pearson import (
|
| 18 |
+
pearsons_contingency_coefficient,
|
| 19 |
+
pearsons_contingency_coefficient_matrix,
|
| 20 |
+
)
|
| 21 |
+
from torchmetrics.functional.nominal.theils_u import theils_u, theils_u_matrix
|
| 22 |
+
from torchmetrics.functional.nominal.tschuprows import tschuprows_t, tschuprows_t_matrix
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"cramers_v",
|
| 26 |
+
"cramers_v_matrix",
|
| 27 |
+
"fleiss_kappa",
|
| 28 |
+
"pearsons_contingency_coefficient",
|
| 29 |
+
"pearsons_contingency_coefficient_matrix",
|
| 30 |
+
"theils_u",
|
| 31 |
+
"theils_u_matrix",
|
| 32 |
+
"tschuprows_t",
|
| 33 |
+
"tschuprows_t_matrix",
|
| 34 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/cramers.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import itertools
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update
|
| 22 |
+
from torchmetrics.functional.nominal.utils import (
|
| 23 |
+
_compute_bias_corrected_values,
|
| 24 |
+
_compute_chi_squared,
|
| 25 |
+
_drop_empty_rows_and_cols,
|
| 26 |
+
_handle_nan_in_data,
|
| 27 |
+
_nominal_input_validation,
|
| 28 |
+
_unable_to_use_bias_correction_warning,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _cramers_v_update(
|
| 33 |
+
preds: Tensor,
|
| 34 |
+
target: Tensor,
|
| 35 |
+
num_classes: int,
|
| 36 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 37 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 38 |
+
) -> Tensor:
|
| 39 |
+
"""Compute the bins to update the confusion matrix with for Cramer's V calculation.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 43 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 44 |
+
num_classes: Integer specifying the number of classes
|
| 45 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 46 |
+
nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
Non-reduced confusion matrix
|
| 50 |
+
|
| 51 |
+
"""
|
| 52 |
+
preds = preds.argmax(1) if preds.ndim == 2 else preds
|
| 53 |
+
target = target.argmax(1) if target.ndim == 2 else target
|
| 54 |
+
preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
|
| 55 |
+
return _multiclass_confusion_matrix_update(preds, target, num_classes)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _cramers_v_compute(confmat: Tensor, bias_correction: bool) -> Tensor:
|
| 59 |
+
"""Compute Cramers' V statistic based on a pre-computed confusion matrix.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
confmat: Confusion matrix for observed data
|
| 63 |
+
bias_correction: Indication of whether to use bias correction.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Cramer's V statistic
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
confmat = _drop_empty_rows_and_cols(confmat)
|
| 70 |
+
cm_sum = confmat.sum()
|
| 71 |
+
chi_squared = _compute_chi_squared(confmat, bias_correction)
|
| 72 |
+
phi_squared = chi_squared / cm_sum
|
| 73 |
+
num_rows, num_cols = confmat.shape
|
| 74 |
+
|
| 75 |
+
if bias_correction:
|
| 76 |
+
phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values(
|
| 77 |
+
phi_squared, num_rows, num_cols, cm_sum
|
| 78 |
+
)
|
| 79 |
+
if torch.min(rows_corrected, cols_corrected) == 1:
|
| 80 |
+
_unable_to_use_bias_correction_warning(metric_name="Cramer's V")
|
| 81 |
+
return torch.tensor(float("nan"), device=confmat.device)
|
| 82 |
+
cramers_v_value = torch.sqrt(phi_squared_corrected / torch.min(rows_corrected - 1, cols_corrected - 1))
|
| 83 |
+
else:
|
| 84 |
+
cramers_v_value = torch.sqrt(phi_squared / min(num_rows - 1, num_cols - 1))
|
| 85 |
+
return cramers_v_value.clamp(0.0, 1.0)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def cramers_v(
|
| 89 |
+
preds: Tensor,
|
| 90 |
+
target: Tensor,
|
| 91 |
+
bias_correction: bool = True,
|
| 92 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 93 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 94 |
+
) -> Tensor:
|
| 95 |
+
r"""Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series.
|
| 96 |
+
|
| 97 |
+
.. math::
|
| 98 |
+
V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}}
|
| 99 |
+
|
| 100 |
+
where
|
| 101 |
+
|
| 102 |
+
.. math::
|
| 103 |
+
\chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
|
| 104 |
+
|
| 105 |
+
where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
|
| 106 |
+
represent frequencies of values in ``preds`` and ``target``, respectively.
|
| 107 |
+
|
| 108 |
+
Cramer's V is a symmetric coefficient, i.e. :math:`V(preds, target) = V(target, preds)`.
|
| 109 |
+
|
| 110 |
+
The output values lies in [0, 1] with 1 meaning the perfect association.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 114 |
+
- 1D shape: (batch_size,)
|
| 115 |
+
- 2D shape: (batch_size, num_classes)
|
| 116 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 117 |
+
- 1D shape: (batch_size,)
|
| 118 |
+
- 2D shape: (batch_size, num_classes)
|
| 119 |
+
bias_correction: Indication of whether to use bias correction.
|
| 120 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 121 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Cramer's V statistic
|
| 125 |
+
|
| 126 |
+
Example:
|
| 127 |
+
>>> from torch import randint, round
|
| 128 |
+
>>> from torchmetrics.functional.nominal import cramers_v
|
| 129 |
+
>>> preds = randint(0, 4, (100,))
|
| 130 |
+
>>> target = round(preds + torch.randn(100)).clamp(0, 4)
|
| 131 |
+
>>> cramers_v(preds, target)
|
| 132 |
+
tensor(0.5284)
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 136 |
+
num_classes = len(torch.cat([preds, target]).unique())
|
| 137 |
+
confmat = _cramers_v_update(preds, target, num_classes, nan_strategy, nan_replace_value)
|
| 138 |
+
return _cramers_v_compute(confmat, bias_correction)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def cramers_v_matrix(
|
| 142 |
+
matrix: Tensor,
|
| 143 |
+
bias_correction: bool = True,
|
| 144 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 145 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 146 |
+
) -> Tensor:
|
| 147 |
+
r"""Compute `Cramer's V`_ statistic between a set of multiple variables.
|
| 148 |
+
|
| 149 |
+
This can serve as a convenient tool to compute Cramer's V statistic for analyses of correlation between categorical
|
| 150 |
+
variables in your dataset.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
matrix: A tensor of categorical (nominal) data, where:
|
| 154 |
+
- rows represent a number of data points
|
| 155 |
+
- columns represent a number of categorical (nominal) features
|
| 156 |
+
bias_correction: Indication of whether to use bias correction.
|
| 157 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 158 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
Cramer's V statistic for a dataset of categorical variables
|
| 162 |
+
|
| 163 |
+
Example:
|
| 164 |
+
>>> from torch import randint
|
| 165 |
+
>>> from torchmetrics.functional.nominal import cramers_v_matrix
|
| 166 |
+
>>> matrix = randint(0, 4, (200, 5))
|
| 167 |
+
>>> cramers_v_matrix(matrix)
|
| 168 |
+
tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
|
| 169 |
+
[0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
|
| 170 |
+
[0.0000, 0.0000, 1.0000, 0.0000, 0.0649],
|
| 171 |
+
[0.0542, 0.0000, 0.0000, 1.0000, 0.1100],
|
| 172 |
+
[0.1337, 0.0000, 0.0649, 0.1100, 1.0000]])
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 176 |
+
num_variables = matrix.shape[1]
|
| 177 |
+
cramers_v_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
|
| 178 |
+
for i, j in itertools.combinations(range(num_variables), 2):
|
| 179 |
+
x, y = matrix[:, i], matrix[:, j]
|
| 180 |
+
num_classes = len(torch.cat([x, y]).unique())
|
| 181 |
+
confmat = _cramers_v_update(x, y, num_classes, nan_strategy, nan_replace_value)
|
| 182 |
+
cramers_v_matrix_value[i, j] = cramers_v_matrix_value[j, i] = _cramers_v_compute(confmat, bias_correction)
|
| 183 |
+
return cramers_v_matrix_value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/fleiss_kappa.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
from typing_extensions import Literal
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _fleiss_kappa_update(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor:
|
| 20 |
+
"""Updates the counts for fleiss kappa metric.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
ratings: ratings matrix
|
| 24 |
+
mode: whether ratings are provided as counts or probabilities
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
if mode == "probs":
|
| 28 |
+
if ratings.ndim != 3 or not ratings.is_floating_point():
|
| 29 |
+
raise ValueError(
|
| 30 |
+
"If argument ``mode`` is 'probs', ratings must have 3 dimensions with the format"
|
| 31 |
+
" [n_samples, n_categories, n_raters] and be floating point."
|
| 32 |
+
)
|
| 33 |
+
ratings = ratings.argmax(dim=1)
|
| 34 |
+
one_hot = torch.nn.functional.one_hot(ratings, num_classes=ratings.shape[1]).permute(0, 2, 1)
|
| 35 |
+
ratings = one_hot.sum(dim=-1)
|
| 36 |
+
elif mode == "counts" and (ratings.ndim != 2 or ratings.is_floating_point()):
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"If argument ``mode`` is `counts`, ratings must have 2 dimensions with the format"
|
| 39 |
+
" [n_samples, n_categories] and be none floating point."
|
| 40 |
+
)
|
| 41 |
+
return ratings
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _fleiss_kappa_compute(counts: Tensor) -> Tensor:
|
| 45 |
+
"""Computes fleiss kappa from counts matrix.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
counts: counts matrix of shape [n_samples, n_categories]
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
total = counts.shape[0]
|
| 52 |
+
num_raters = counts.sum(1).max()
|
| 53 |
+
|
| 54 |
+
p_i = counts.sum(dim=0) / (total * num_raters)
|
| 55 |
+
p_j = ((counts**2).sum(dim=1) - num_raters) / (num_raters * (num_raters - 1))
|
| 56 |
+
p_bar = p_j.mean()
|
| 57 |
+
pe_bar = (p_i**2).sum()
|
| 58 |
+
return (p_bar - pe_bar) / (1 - pe_bar + 1e-5)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def fleiss_kappa(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -> Tensor:
|
| 62 |
+
r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
|
| 63 |
+
|
| 64 |
+
.. math::
|
| 65 |
+
\kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
|
| 66 |
+
|
| 67 |
+
where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
|
| 68 |
+
agreement probability over all raters if they were randomly assigned. If the raters are in complete agreement then
|
| 69 |
+
the score 1 is returned, if there is no agreement among the raters (other than what would be expected by chance)
|
| 70 |
+
then a score smaller than 0 is returned.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
ratings: Ratings of shape [n_samples, n_categories] or [n_samples, n_categories, n_raters] depedenent on `mode`.
|
| 74 |
+
If `mode` is `counts`, `ratings` must be integer and contain the number of raters that chose each category.
|
| 75 |
+
If `mode` is `probs`, `ratings` must be floating point and contain the probability/logits that each rater
|
| 76 |
+
chose each category.
|
| 77 |
+
mode: Whether `ratings` will be provided as counts or probabilities.
|
| 78 |
+
|
| 79 |
+
Example:
|
| 80 |
+
>>> # Ratings are provided as counts
|
| 81 |
+
>>> from torch import randint
|
| 82 |
+
>>> from torchmetrics.functional.nominal import fleiss_kappa
|
| 83 |
+
>>> ratings = randint(0, 10, size=(100, 5)).long() # 100 samples, 5 categories, 10 raters
|
| 84 |
+
>>> fleiss_kappa(ratings)
|
| 85 |
+
tensor(0.0089)
|
| 86 |
+
|
| 87 |
+
Example:
|
| 88 |
+
>>> # Ratings are provided as probabilities
|
| 89 |
+
>>> from torch import randn
|
| 90 |
+
>>> from torchmetrics.functional.nominal import fleiss_kappa
|
| 91 |
+
>>> ratings = randn(100, 5, 10).softmax(dim=1) # 100 samples, 5 categories, 10 raters
|
| 92 |
+
>>> fleiss_kappa(ratings, mode='probs')
|
| 93 |
+
tensor(-0.0075)
|
| 94 |
+
|
| 95 |
+
"""
|
| 96 |
+
if mode not in ["counts", "probs"]:
|
| 97 |
+
raise ValueError("Argument ``mode`` must be one of ['counts', 'probs'].")
|
| 98 |
+
counts = _fleiss_kappa_update(ratings, mode)
|
| 99 |
+
return _fleiss_kappa_compute(counts)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/pearson.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import itertools
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update
|
| 22 |
+
from torchmetrics.functional.nominal.utils import (
|
| 23 |
+
_compute_chi_squared,
|
| 24 |
+
_drop_empty_rows_and_cols,
|
| 25 |
+
_handle_nan_in_data,
|
| 26 |
+
_nominal_input_validation,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _pearsons_contingency_coefficient_update(
|
| 31 |
+
preds: Tensor,
|
| 32 |
+
target: Tensor,
|
| 33 |
+
num_classes: int,
|
| 34 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 35 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 36 |
+
) -> Tensor:
|
| 37 |
+
"""Compute the bins to update the confusion matrix with for Pearson's Contingency Coefficient calculation.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 41 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 42 |
+
num_classes: Integer specifying the number of classes
|
| 43 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 44 |
+
nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
Non-reduced confusion matrix
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
preds = preds.argmax(1) if preds.ndim == 2 else preds
|
| 51 |
+
target = target.argmax(1) if target.ndim == 2 else target
|
| 52 |
+
preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
|
| 53 |
+
return _multiclass_confusion_matrix_update(preds, target, num_classes)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _pearsons_contingency_coefficient_compute(confmat: Tensor) -> Tensor:
|
| 57 |
+
"""Compute Pearson's Contingency Coefficient based on a pre-computed confusion matrix.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
confmat: Confusion matrix for observed data
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
Pearson's Contingency Coefficient
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
confmat = _drop_empty_rows_and_cols(confmat)
|
| 67 |
+
cm_sum = confmat.sum()
|
| 68 |
+
chi_squared = _compute_chi_squared(confmat, bias_correction=False)
|
| 69 |
+
phi_squared = chi_squared / cm_sum
|
| 70 |
+
|
| 71 |
+
tschuprows_t_value = torch.sqrt(phi_squared / (1 + phi_squared))
|
| 72 |
+
return tschuprows_t_value.clamp(0.0, 1.0)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def pearsons_contingency_coefficient(
|
| 76 |
+
preds: Tensor,
|
| 77 |
+
target: Tensor,
|
| 78 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 79 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 80 |
+
) -> Tensor:
|
| 81 |
+
r"""Compute `Pearson's Contingency Coefficient`_ for measuring the association between two categorical data series.
|
| 82 |
+
|
| 83 |
+
.. math::
|
| 84 |
+
Pearson = \sqrt{\frac{\chi^2 / n}{1 + \chi^2 / n}}
|
| 85 |
+
|
| 86 |
+
where
|
| 87 |
+
|
| 88 |
+
.. math::
|
| 89 |
+
\chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
|
| 90 |
+
|
| 91 |
+
where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
|
| 92 |
+
represent frequencies of values in ``preds`` and ``target``, respectively.
|
| 93 |
+
|
| 94 |
+
Pearson's Contingency Coefficient is a symmetric coefficient, i.e.
|
| 95 |
+
:math:`Pearson(preds, target) = Pearson(target, preds)`.
|
| 96 |
+
|
| 97 |
+
The output values lies in [0, 1] with 1 meaning the perfect association.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
preds: 1D or 2D tensor of categorical (nominal) data:
|
| 101 |
+
|
| 102 |
+
- 1D shape: (batch_size,)
|
| 103 |
+
- 2D shape: (batch_size, num_classes)
|
| 104 |
+
|
| 105 |
+
target: 1D or 2D tensor of categorical (nominal) data:
|
| 106 |
+
|
| 107 |
+
- 1D shape: (batch_size,)
|
| 108 |
+
- 2D shape: (batch_size, num_classes)
|
| 109 |
+
|
| 110 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 111 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
Pearson's Contingency Coefficient
|
| 115 |
+
|
| 116 |
+
Example:
|
| 117 |
+
>>> from torch import randint, round
|
| 118 |
+
>>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient
|
| 119 |
+
>>> preds = randint(0, 4, (100,))
|
| 120 |
+
>>> target = round(preds + torch.randn(100)).clamp(0, 4)
|
| 121 |
+
>>> pearsons_contingency_coefficient(preds, target)
|
| 122 |
+
tensor(0.6948)
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 126 |
+
num_classes = len(torch.cat([preds, target]).unique())
|
| 127 |
+
confmat = _pearsons_contingency_coefficient_update(preds, target, num_classes, nan_strategy, nan_replace_value)
|
| 128 |
+
return _pearsons_contingency_coefficient_compute(confmat)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def pearsons_contingency_coefficient_matrix(
|
| 132 |
+
matrix: Tensor,
|
| 133 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 134 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 135 |
+
) -> Tensor:
|
| 136 |
+
r"""Compute `Pearson's Contingency Coefficient`_ statistic between a set of multiple variables.
|
| 137 |
+
|
| 138 |
+
This can serve as a convenient tool to compute Pearson's Contingency Coefficient for analyses
|
| 139 |
+
of correlation between categorical variables in your dataset.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
matrix: A tensor of categorical (nominal) data, where:
|
| 143 |
+
|
| 144 |
+
- rows represent a number of data points
|
| 145 |
+
- columns represent a number of categorical (nominal) features
|
| 146 |
+
|
| 147 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 148 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
Pearson's Contingency Coefficient statistic for a dataset of categorical variables
|
| 152 |
+
|
| 153 |
+
Example:
|
| 154 |
+
>>> from torch import randint
|
| 155 |
+
>>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient_matrix
|
| 156 |
+
>>> matrix = randint(0, 4, (200, 5))
|
| 157 |
+
>>> pearsons_contingency_coefficient_matrix(matrix)
|
| 158 |
+
tensor([[1.0000, 0.2326, 0.1959, 0.2262, 0.2989],
|
| 159 |
+
[0.2326, 1.0000, 0.1386, 0.1895, 0.1329],
|
| 160 |
+
[0.1959, 0.1386, 1.0000, 0.1840, 0.2335],
|
| 161 |
+
[0.2262, 0.1895, 0.1840, 1.0000, 0.2737],
|
| 162 |
+
[0.2989, 0.1329, 0.2335, 0.2737, 1.0000]])
|
| 163 |
+
|
| 164 |
+
"""
|
| 165 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 166 |
+
num_variables = matrix.shape[1]
|
| 167 |
+
pearsons_cont_coef_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
|
| 168 |
+
for i, j in itertools.combinations(range(num_variables), 2):
|
| 169 |
+
x, y = matrix[:, i], matrix[:, j]
|
| 170 |
+
num_classes = len(torch.cat([x, y]).unique())
|
| 171 |
+
confmat = _pearsons_contingency_coefficient_update(x, y, num_classes, nan_strategy, nan_replace_value)
|
| 172 |
+
val = _pearsons_contingency_coefficient_compute(confmat)
|
| 173 |
+
pearsons_cont_coef_matrix_value[i, j] = pearsons_cont_coef_matrix_value[j, i] = val
|
| 174 |
+
return pearsons_cont_coef_matrix_value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/theils_u.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import itertools
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update
|
| 22 |
+
from torchmetrics.functional.nominal.utils import (
|
| 23 |
+
_drop_empty_rows_and_cols,
|
| 24 |
+
_handle_nan_in_data,
|
| 25 |
+
_nominal_input_validation,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _conditional_entropy_compute(confmat: Tensor) -> Tensor:
|
| 30 |
+
r"""Compute Conditional Entropy Statistic based on a pre-computed confusion matrix.
|
| 31 |
+
|
| 32 |
+
.. math::
|
| 33 |
+
H(X|Y) = \sum_{x, y ~ (X, Y)} p(x, y)\frac{p(y)}{p(x, y)}
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
confmat: Confusion matrix for observed data
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
Conditional Entropy Value
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
confmat = _drop_empty_rows_and_cols(confmat)
|
| 43 |
+
total_occurrences = confmat.sum()
|
| 44 |
+
# iterate over all i, j combinations
|
| 45 |
+
p_xy_m = confmat / total_occurrences
|
| 46 |
+
# get p_y by summing over x dim (=1)
|
| 47 |
+
p_y = confmat.sum(1) / total_occurrences
|
| 48 |
+
# repeat over rows (shape = p_xy_m.shape[1]) for tensor multiplication
|
| 49 |
+
p_y_m = p_y.unsqueeze(1).repeat(1, p_xy_m.shape[1])
|
| 50 |
+
|
| 51 |
+
# entropy calculated as p_xy * log (p_xy / p_y)
|
| 52 |
+
return torch.nansum(p_xy_m * torch.log(p_y_m / p_xy_m))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _theils_u_update(
|
| 56 |
+
preds: Tensor,
|
| 57 |
+
target: Tensor,
|
| 58 |
+
num_classes: int,
|
| 59 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 60 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 61 |
+
) -> Tensor:
|
| 62 |
+
"""Compute the bins to update the confusion matrix with for Theil's U calculation.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 66 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 67 |
+
num_classes: Integer specifying the number of classes
|
| 68 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 69 |
+
nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
Non-reduced confusion matrix
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
preds = preds.argmax(1) if preds.ndim == 2 else preds
|
| 76 |
+
target = target.argmax(1) if target.ndim == 2 else target
|
| 77 |
+
preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
|
| 78 |
+
return _multiclass_confusion_matrix_update(preds, target, num_classes)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _theils_u_compute(confmat: Tensor) -> Tensor:
|
| 82 |
+
"""Compute Theil's U statistic based on a pre-computed confusion matrix.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
confmat: Confusion matrix for observed data
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
Theil's U statistic
|
| 89 |
+
|
| 90 |
+
"""
|
| 91 |
+
confmat = _drop_empty_rows_and_cols(confmat)
|
| 92 |
+
|
| 93 |
+
# compute conditional entropy
|
| 94 |
+
s_xy = _conditional_entropy_compute(confmat)
|
| 95 |
+
|
| 96 |
+
# compute H(x)
|
| 97 |
+
total_occurrences = confmat.sum()
|
| 98 |
+
p_x = confmat.sum(0) / total_occurrences
|
| 99 |
+
s_x = -torch.sum(p_x * torch.log(p_x))
|
| 100 |
+
|
| 101 |
+
# compute u statistic
|
| 102 |
+
if s_x == 0:
|
| 103 |
+
return torch.tensor(0, device=confmat.device)
|
| 104 |
+
|
| 105 |
+
return (s_x - s_xy) / s_x
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def theils_u(
|
| 109 |
+
preds: Tensor,
|
| 110 |
+
target: Tensor,
|
| 111 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 112 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 113 |
+
) -> Tensor:
|
| 114 |
+
r"""Compute `Theils Uncertainty coefficient`_ statistic measuring the association between two nominal data series.
|
| 115 |
+
|
| 116 |
+
.. math::
|
| 117 |
+
U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)}
|
| 118 |
+
|
| 119 |
+
where :math:`H(X)` is entropy of variable :math:`X` while :math:`H(X|Y)` is the conditional entropy of :math:`X`
|
| 120 |
+
given :math:`Y`.
|
| 121 |
+
|
| 122 |
+
Theils's U is an asymmetric coefficient, i.e. :math:`TheilsU(preds, target) \neq TheilsU(target, preds)`.
|
| 123 |
+
|
| 124 |
+
The output values lies in [0, 1]. 0 means y has no information about x while value 1 means y has complete
|
| 125 |
+
information about x.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 129 |
+
- 1D shape: (batch_size,)
|
| 130 |
+
- 2D shape: (batch_size, num_classes)
|
| 131 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 132 |
+
- 1D shape: (batch_size,)
|
| 133 |
+
- 2D shape: (batch_size, num_classes)
|
| 134 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 135 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
Tensor containing Theil's U statistic
|
| 139 |
+
|
| 140 |
+
Example:
|
| 141 |
+
>>> from torch import randint
|
| 142 |
+
>>> from torchmetrics.functional.nominal import theils_u
|
| 143 |
+
>>> preds = randint(10, (10,))
|
| 144 |
+
>>> target = randint(10, (10,))
|
| 145 |
+
>>> theils_u(preds, target)
|
| 146 |
+
tensor(0.8530)
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
num_classes = len(torch.cat([preds, target]).unique())
|
| 150 |
+
confmat = _theils_u_update(preds, target, num_classes, nan_strategy, nan_replace_value)
|
| 151 |
+
return _theils_u_compute(confmat)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def theils_u_matrix(
|
| 155 |
+
matrix: Tensor,
|
| 156 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 157 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 158 |
+
) -> Tensor:
|
| 159 |
+
r"""Compute `Theil's U`_ statistic between a set of multiple variables.
|
| 160 |
+
|
| 161 |
+
This can serve as a convenient tool to compute Theil's U statistic for analyses of correlation between categorical
|
| 162 |
+
variables in your dataset.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
matrix: A tensor of categorical (nominal) data, where:
|
| 166 |
+
- rows represent a number of data points
|
| 167 |
+
- columns represent a number of categorical (nominal) features
|
| 168 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 169 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Theil's U statistic for a dataset of categorical variables
|
| 173 |
+
|
| 174 |
+
Example:
|
| 175 |
+
>>> from torch import randint
|
| 176 |
+
>>> from torchmetrics.functional.nominal import theils_u_matrix
|
| 177 |
+
>>> matrix = randint(0, 4, (200, 5))
|
| 178 |
+
>>> theils_u_matrix(matrix)
|
| 179 |
+
tensor([[1.0000, 0.0202, 0.0142, 0.0196, 0.0353],
|
| 180 |
+
[0.0202, 1.0000, 0.0070, 0.0136, 0.0065],
|
| 181 |
+
[0.0143, 0.0070, 1.0000, 0.0125, 0.0206],
|
| 182 |
+
[0.0198, 0.0137, 0.0125, 1.0000, 0.0312],
|
| 183 |
+
[0.0352, 0.0065, 0.0204, 0.0308, 1.0000]])
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 187 |
+
num_variables = matrix.shape[1]
|
| 188 |
+
theils_u_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
|
| 189 |
+
for i, j in itertools.combinations(range(num_variables), 2):
|
| 190 |
+
x, y = matrix[:, i], matrix[:, j]
|
| 191 |
+
num_classes = len(torch.cat([x, y]).unique())
|
| 192 |
+
confmat = _theils_u_update(x, y, num_classes, nan_strategy, nan_replace_value)
|
| 193 |
+
theils_u_matrix_value[i, j] = _theils_u_compute(confmat)
|
| 194 |
+
theils_u_matrix_value[j, i] = _theils_u_compute(confmat.T)
|
| 195 |
+
return theils_u_matrix_value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/tschuprows.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import itertools
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.classification.confusion_matrix import _multiclass_confusion_matrix_update
|
| 22 |
+
from torchmetrics.functional.nominal.utils import (
|
| 23 |
+
_compute_bias_corrected_values,
|
| 24 |
+
_compute_chi_squared,
|
| 25 |
+
_drop_empty_rows_and_cols,
|
| 26 |
+
_handle_nan_in_data,
|
| 27 |
+
_nominal_input_validation,
|
| 28 |
+
_unable_to_use_bias_correction_warning,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _tschuprows_t_update(
|
| 33 |
+
preds: Tensor,
|
| 34 |
+
target: Tensor,
|
| 35 |
+
num_classes: int,
|
| 36 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 37 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 38 |
+
) -> Tensor:
|
| 39 |
+
"""Compute the bins to update the confusion matrix with for Tschuprow's T calculation.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
preds: 1D or 2D tensor of categorical (nominal) data
|
| 43 |
+
target: 1D or 2D tensor of categorical (nominal) data
|
| 44 |
+
num_classes: Integer specifying the number of classes
|
| 45 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 46 |
+
nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
Non-reduced confusion matrix
|
| 50 |
+
|
| 51 |
+
"""
|
| 52 |
+
preds = preds.argmax(1) if preds.ndim == 2 else preds
|
| 53 |
+
target = target.argmax(1) if target.ndim == 2 else target
|
| 54 |
+
preds, target = _handle_nan_in_data(preds, target, nan_strategy, nan_replace_value)
|
| 55 |
+
return _multiclass_confusion_matrix_update(preds, target, num_classes)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _tschuprows_t_compute(confmat: Tensor, bias_correction: bool) -> Tensor:
|
| 59 |
+
"""Compute Tschuprow's T statistic based on a pre-computed confusion matrix.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
confmat: Confusion matrix for observed data
|
| 63 |
+
bias_correction: Indication of whether to use bias correction.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Tschuprow's T statistic
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
confmat = _drop_empty_rows_and_cols(confmat)
|
| 70 |
+
cm_sum = confmat.sum()
|
| 71 |
+
chi_squared = _compute_chi_squared(confmat, bias_correction)
|
| 72 |
+
phi_squared = chi_squared / cm_sum
|
| 73 |
+
num_rows, num_cols = confmat.shape
|
| 74 |
+
|
| 75 |
+
if bias_correction:
|
| 76 |
+
phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values(
|
| 77 |
+
phi_squared, num_rows, num_cols, cm_sum
|
| 78 |
+
)
|
| 79 |
+
if torch.min(rows_corrected, cols_corrected) == 1:
|
| 80 |
+
_unable_to_use_bias_correction_warning(metric_name="Tschuprow's T")
|
| 81 |
+
return torch.tensor(float("nan"), device=confmat.device)
|
| 82 |
+
tschuprows_t_value = torch.sqrt(phi_squared_corrected / torch.sqrt((rows_corrected - 1) * (cols_corrected - 1)))
|
| 83 |
+
else:
|
| 84 |
+
n_rows_tensor = torch.tensor(num_rows, device=phi_squared.device)
|
| 85 |
+
n_cols_tensor = torch.tensor(num_cols, device=phi_squared.device)
|
| 86 |
+
tschuprows_t_value = torch.sqrt(phi_squared / torch.sqrt((n_rows_tensor - 1) * (n_cols_tensor - 1)))
|
| 87 |
+
return tschuprows_t_value.clamp(0.0, 1.0)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def tschuprows_t(
|
| 91 |
+
preds: Tensor,
|
| 92 |
+
target: Tensor,
|
| 93 |
+
bias_correction: bool = True,
|
| 94 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 95 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 96 |
+
) -> Tensor:
|
| 97 |
+
r"""Compute `Tschuprow's T`_ statistic measuring the association between two categorical (nominal) data series.
|
| 98 |
+
|
| 99 |
+
.. math::
|
| 100 |
+
T = \sqrt{\frac{\chi^2 / n}{\sqrt{(r - 1) * (k - 1)}}}
|
| 101 |
+
|
| 102 |
+
where
|
| 103 |
+
|
| 104 |
+
.. math::
|
| 105 |
+
\chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}
|
| 106 |
+
|
| 107 |
+
where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
|
| 108 |
+
represent frequencies of values in ``preds`` and ``target``, respectively.
|
| 109 |
+
|
| 110 |
+
Tschuprow's T is a symmetric coefficient, i.e. :math:`T(preds, target) = T(target, preds)`.
|
| 111 |
+
|
| 112 |
+
The output values lies in [0, 1] with 1 meaning the perfect association.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
preds: 1D or 2D tensor of categorical (nominal) data:
|
| 116 |
+
|
| 117 |
+
- 1D shape: (batch_size,)
|
| 118 |
+
- 2D shape: (batch_size, num_classes)
|
| 119 |
+
|
| 120 |
+
target: 1D or 2D tensor of categorical (nominal) data:
|
| 121 |
+
|
| 122 |
+
- 1D shape: (batch_size,)
|
| 123 |
+
- 2D shape: (batch_size, num_classes)
|
| 124 |
+
|
| 125 |
+
bias_correction: Indication of whether to use bias correction.
|
| 126 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 127 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Tschuprow's T statistic
|
| 131 |
+
|
| 132 |
+
Example:
|
| 133 |
+
>>> from torch import randint, round
|
| 134 |
+
>>> from torchmetrics.functional.nominal import tschuprows_t
|
| 135 |
+
>>> preds = randint(0, 4, (100,))
|
| 136 |
+
>>> target = round(preds + torch.randn(100)).clamp(0, 4)
|
| 137 |
+
>>> tschuprows_t(preds, target)
|
| 138 |
+
tensor(0.4930)
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 142 |
+
num_classes = len(torch.cat([preds, target]).unique())
|
| 143 |
+
confmat = _tschuprows_t_update(preds, target, num_classes, nan_strategy, nan_replace_value)
|
| 144 |
+
return _tschuprows_t_compute(confmat, bias_correction)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def tschuprows_t_matrix(
|
| 148 |
+
matrix: Tensor,
|
| 149 |
+
bias_correction: bool = True,
|
| 150 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 151 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 152 |
+
) -> Tensor:
|
| 153 |
+
r"""Compute `Tschuprow's T`_ statistic between a set of multiple variables.
|
| 154 |
+
|
| 155 |
+
This can serve as a convenient tool to compute Tschuprow's T statistic for analyses of correlation between
|
| 156 |
+
categorical variables in your dataset.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
matrix: A tensor of categorical (nominal) data, where:
|
| 160 |
+
|
| 161 |
+
- rows represent a number of data points
|
| 162 |
+
- columns represent a number of categorical (nominal) features
|
| 163 |
+
|
| 164 |
+
bias_correction: Indication of whether to use bias correction.
|
| 165 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 166 |
+
nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Tschuprow's T statistic for a dataset of categorical variables
|
| 170 |
+
|
| 171 |
+
Example:
|
| 172 |
+
>>> from torch import randint
|
| 173 |
+
>>> from torchmetrics.functional.nominal import tschuprows_t_matrix
|
| 174 |
+
>>> matrix = randint(0, 4, (200, 5))
|
| 175 |
+
>>> tschuprows_t_matrix(matrix)
|
| 176 |
+
tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
|
| 177 |
+
[0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
|
| 178 |
+
[0.0000, 0.0000, 1.0000, 0.0000, 0.0649],
|
| 179 |
+
[0.0542, 0.0000, 0.0000, 1.0000, 0.1100],
|
| 180 |
+
[0.1337, 0.0000, 0.0649, 0.1100, 1.0000]])
|
| 181 |
+
|
| 182 |
+
"""
|
| 183 |
+
_nominal_input_validation(nan_strategy, nan_replace_value)
|
| 184 |
+
num_variables = matrix.shape[1]
|
| 185 |
+
tschuprows_t_matrix_value = torch.ones(num_variables, num_variables, device=matrix.device)
|
| 186 |
+
for i, j in itertools.combinations(range(num_variables), 2):
|
| 187 |
+
x, y = matrix[:, i], matrix[:, j]
|
| 188 |
+
num_classes = len(torch.cat([x, y]).unique())
|
| 189 |
+
confmat = _tschuprows_t_update(x, y, num_classes, nan_strategy, nan_replace_value)
|
| 190 |
+
tschuprows_t_matrix_value[i, j] = tschuprows_t_matrix_value[j, i] = _tschuprows_t_compute(
|
| 191 |
+
confmat, bias_correction
|
| 192 |
+
)
|
| 193 |
+
return tschuprows_t_matrix_value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/nominal/utils.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.utilities.prints import rank_zero_warn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _nominal_input_validation(nan_strategy: str, nan_replace_value: Optional[float]) -> None:
|
| 24 |
+
if nan_strategy not in ["replace", "drop"]:
|
| 25 |
+
raise ValueError(
|
| 26 |
+
f"Argument `nan_strategy` is expected to be one of `['replace', 'drop']`, but got {nan_strategy}"
|
| 27 |
+
)
|
| 28 |
+
if nan_strategy == "replace" and not isinstance(nan_replace_value, (float, int)):
|
| 29 |
+
raise ValueError(
|
| 30 |
+
"Argument `nan_replace` is expected to be of a type `int` or `float` when `nan_strategy = 'replace`, "
|
| 31 |
+
f"but got {nan_replace_value}"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _compute_expected_freqs(confmat: Tensor) -> Tensor:
|
| 36 |
+
"""Compute the expected frequenceis from the provided confusion matrix."""
|
| 37 |
+
margin_sum_rows, margin_sum_cols = confmat.sum(1), confmat.sum(0)
|
| 38 |
+
return torch.einsum("r, c -> rc", margin_sum_rows, margin_sum_cols) / confmat.sum()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _compute_chi_squared(confmat: Tensor, bias_correction: bool) -> Tensor:
|
| 42 |
+
"""Chi-square test of independenc of variables in a confusion matrix table.
|
| 43 |
+
|
| 44 |
+
Adapted from: https://github.com/scipy/scipy/blob/v1.9.2/scipy/stats/contingency.py.
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
expected_freqs = _compute_expected_freqs(confmat)
|
| 48 |
+
# Get degrees of freedom
|
| 49 |
+
df = expected_freqs.numel() - sum(expected_freqs.shape) + expected_freqs.ndim - 1
|
| 50 |
+
if df == 0:
|
| 51 |
+
return torch.tensor(0.0, device=confmat.device)
|
| 52 |
+
|
| 53 |
+
if df == 1 and bias_correction:
|
| 54 |
+
diff = expected_freqs - confmat
|
| 55 |
+
direction = diff.sign()
|
| 56 |
+
confmat += direction * torch.minimum(0.5 * torch.ones_like(direction), direction.abs())
|
| 57 |
+
|
| 58 |
+
return torch.sum((confmat - expected_freqs) ** 2 / expected_freqs)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _drop_empty_rows_and_cols(confmat: Tensor) -> Tensor:
|
| 62 |
+
"""Drop all rows and columns containing only zeros.
|
| 63 |
+
|
| 64 |
+
Example:
|
| 65 |
+
>>> from torch import randint
|
| 66 |
+
>>> from torchmetrics.functional.nominal.utils import _drop_empty_rows_and_cols
|
| 67 |
+
>>> matrix = randint(10, size=(4, 3))
|
| 68 |
+
>>> matrix[1, :] = matrix[:, 1] = 0
|
| 69 |
+
>>> matrix
|
| 70 |
+
tensor([[2, 0, 6],
|
| 71 |
+
[0, 0, 0],
|
| 72 |
+
[0, 0, 0],
|
| 73 |
+
[3, 0, 4]])
|
| 74 |
+
>>> _drop_empty_rows_and_cols(matrix)
|
| 75 |
+
tensor([[2, 6],
|
| 76 |
+
[3, 4]])
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
confmat = confmat[confmat.sum(1) != 0]
|
| 80 |
+
return confmat[:, confmat.sum(0) != 0]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _compute_phi_squared_corrected(
|
| 84 |
+
phi_squared: Tensor,
|
| 85 |
+
num_rows: int,
|
| 86 |
+
num_cols: int,
|
| 87 |
+
confmat_sum: Tensor,
|
| 88 |
+
) -> Tensor:
|
| 89 |
+
"""Compute bias-corrected Phi Squared."""
|
| 90 |
+
return torch.max(
|
| 91 |
+
torch.tensor(0.0, device=phi_squared.device),
|
| 92 |
+
phi_squared - ((num_rows - 1) * (num_cols - 1)) / (confmat_sum - 1),
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _compute_rows_and_cols_corrected(num_rows: int, num_cols: int, confmat_sum: Tensor) -> tuple[Tensor, Tensor]:
|
| 97 |
+
"""Compute bias-corrected number of rows and columns."""
|
| 98 |
+
rows_corrected = num_rows - (num_rows - 1) ** 2 / (confmat_sum - 1)
|
| 99 |
+
cols_corrected = num_cols - (num_cols - 1) ** 2 / (confmat_sum - 1)
|
| 100 |
+
return rows_corrected, cols_corrected
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _compute_bias_corrected_values(
|
| 104 |
+
phi_squared: Tensor, num_rows: int, num_cols: int, confmat_sum: Tensor
|
| 105 |
+
) -> tuple[Tensor, Tensor, Tensor]:
|
| 106 |
+
"""Compute bias-corrected Phi Squared and number of rows and columns."""
|
| 107 |
+
phi_squared_corrected = _compute_phi_squared_corrected(phi_squared, num_rows, num_cols, confmat_sum)
|
| 108 |
+
rows_corrected, cols_corrected = _compute_rows_and_cols_corrected(num_rows, num_cols, confmat_sum)
|
| 109 |
+
return phi_squared_corrected, rows_corrected, cols_corrected
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _handle_nan_in_data(
|
| 113 |
+
preds: Tensor,
|
| 114 |
+
target: Tensor,
|
| 115 |
+
nan_strategy: Literal["replace", "drop"] = "replace",
|
| 116 |
+
nan_replace_value: Optional[float] = 0.0,
|
| 117 |
+
) -> tuple[Tensor, Tensor]:
|
| 118 |
+
"""Handle ``NaN`` values in input data.
|
| 119 |
+
|
| 120 |
+
If ``nan_strategy = 'replace'``, all ``NaN`` values are replaced with ``nan_replace_value``.
|
| 121 |
+
If ``nan_strategy = 'drop'``, all rows containing ``NaN`` in any of two vectors are dropped.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
preds: 1D tensor of categorical (nominal) data
|
| 125 |
+
target: 1D tensor of categorical (nominal) data
|
| 126 |
+
nan_strategy: Indication of whether to replace or drop ``NaN`` values
|
| 127 |
+
nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Updated ``preds`` and ``target`` tensors which contain no ``Nan``
|
| 131 |
+
|
| 132 |
+
Raises:
|
| 133 |
+
ValueError: If ``nan_strategy`` is not from ``['replace', 'drop']``.
|
| 134 |
+
ValueError: If ``nan_strategy = replace`` and ``nan_replace_value`` is not of a type ``int`` or ``float``.
|
| 135 |
+
|
| 136 |
+
"""
|
| 137 |
+
if nan_strategy == "replace":
|
| 138 |
+
return preds.nan_to_num(nan_replace_value), target.nan_to_num(nan_replace_value)
|
| 139 |
+
rows_contain_nan = torch.logical_or(preds.isnan(), target.isnan())
|
| 140 |
+
return preds[~rows_contain_nan], target[~rows_contain_nan]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _unable_to_use_bias_correction_warning(metric_name: str) -> None:
|
| 144 |
+
rank_zero_warn(
|
| 145 |
+
f"Unable to compute {metric_name} using bias correction. Please consider to set `bias_correction=False`."
|
| 146 |
+
)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from torchmetrics.functional.pairwise.cosine import pairwise_cosine_similarity
|
| 15 |
+
from torchmetrics.functional.pairwise.euclidean import pairwise_euclidean_distance
|
| 16 |
+
from torchmetrics.functional.pairwise.linear import pairwise_linear_similarity
|
| 17 |
+
from torchmetrics.functional.pairwise.manhattan import pairwise_manhattan_distance
|
| 18 |
+
from torchmetrics.functional.pairwise.minkowski import pairwise_minkowski_distance
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"pairwise_cosine_similarity",
|
| 22 |
+
"pairwise_euclidean_distance",
|
| 23 |
+
"pairwise_linear_similarity",
|
| 24 |
+
"pairwise_manhattan_distance",
|
| 25 |
+
"pairwise_minkowski_distance",
|
| 26 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/cosine.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
|
| 21 |
+
from torchmetrics.utilities.compute import _safe_matmul
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _pairwise_cosine_similarity_update(
|
| 25 |
+
x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
|
| 26 |
+
) -> Tensor:
|
| 27 |
+
"""Calculate the pairwise cosine similarity matrix.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
x: tensor of shape ``[N,d]``
|
| 31 |
+
y: tensor of shape ``[M,d]``
|
| 32 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
|
| 36 |
+
|
| 37 |
+
norm = torch.norm(x, p=2, dim=1)
|
| 38 |
+
x = x / norm.unsqueeze(1)
|
| 39 |
+
norm = torch.norm(y, p=2, dim=1)
|
| 40 |
+
y = y / norm.unsqueeze(1)
|
| 41 |
+
|
| 42 |
+
distance = _safe_matmul(x, y)
|
| 43 |
+
if zero_diagonal:
|
| 44 |
+
distance.fill_diagonal_(0)
|
| 45 |
+
return distance
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pairwise_cosine_similarity(
|
| 49 |
+
x: Tensor,
|
| 50 |
+
y: Optional[Tensor] = None,
|
| 51 |
+
reduction: Literal["mean", "sum", "none", None] = None,
|
| 52 |
+
zero_diagonal: Optional[bool] = None,
|
| 53 |
+
) -> Tensor:
|
| 54 |
+
r"""Calculate pairwise cosine similarity.
|
| 55 |
+
|
| 56 |
+
.. math::
|
| 57 |
+
s_{cos}(x,y) = \frac{<x,y>}{||x|| \cdot ||y||}
|
| 58 |
+
= \frac{\sum_{d=1}^D x_d \cdot y_d }{\sqrt{\sum_{d=1}^D x_i^2} \cdot \sqrt{\sum_{d=1}^D y_i^2}}
|
| 59 |
+
|
| 60 |
+
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise
|
| 61 |
+
between the rows of :math:`x` and :math:`y`.
|
| 62 |
+
If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
x: Tensor with shape ``[N, d]``
|
| 66 |
+
y: Tensor with shape ``[M, d]``, optional
|
| 67 |
+
reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
|
| 68 |
+
(applied along column dimension) or `'none'`, `None` for no reduction
|
| 69 |
+
zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only :math:`x` is given
|
| 70 |
+
this defaults to ``True`` else if :math:`y` is also given it defaults to ``False``
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
|
| 74 |
+
|
| 75 |
+
Example:
|
| 76 |
+
>>> import torch
|
| 77 |
+
>>> from torchmetrics.functional.pairwise import pairwise_cosine_similarity
|
| 78 |
+
>>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
|
| 79 |
+
>>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
|
| 80 |
+
>>> pairwise_cosine_similarity(x, y)
|
| 81 |
+
tensor([[0.5547, 0.8682],
|
| 82 |
+
[0.5145, 0.8437],
|
| 83 |
+
[0.5300, 0.8533]])
|
| 84 |
+
>>> pairwise_cosine_similarity(x)
|
| 85 |
+
tensor([[0.0000, 0.9989, 0.9996],
|
| 86 |
+
[0.9989, 0.0000, 0.9998],
|
| 87 |
+
[0.9996, 0.9998, 0.0000]])
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
distance = _pairwise_cosine_similarity_update(x, y, zero_diagonal)
|
| 91 |
+
return _reduce_distance_matrix(distance, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/euclidean.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _pairwise_euclidean_distance_update(
|
| 24 |
+
x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
|
| 25 |
+
) -> Tensor:
|
| 26 |
+
"""Calculate the pairwise euclidean distance matrix.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
x: tensor of shape ``[N,d]``
|
| 30 |
+
y: tensor of shape ``[M,d]``
|
| 31 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
|
| 35 |
+
# upcast to float64 to prevent precision issues
|
| 36 |
+
_orig_dtype = x.dtype
|
| 37 |
+
x = x.to(torch.float64)
|
| 38 |
+
y = y.to(torch.float64)
|
| 39 |
+
x_norm = (x * x).sum(dim=1, keepdim=True)
|
| 40 |
+
y_norm = (y * y).sum(dim=1)
|
| 41 |
+
distance = (x_norm + y_norm - 2 * x.mm(y.T)).to(_orig_dtype)
|
| 42 |
+
if zero_diagonal:
|
| 43 |
+
distance.fill_diagonal_(0)
|
| 44 |
+
return distance.sqrt()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def pairwise_euclidean_distance(
|
| 48 |
+
x: Tensor,
|
| 49 |
+
y: Optional[Tensor] = None,
|
| 50 |
+
reduction: Literal["mean", "sum", "none", None] = None,
|
| 51 |
+
zero_diagonal: Optional[bool] = None,
|
| 52 |
+
) -> Tensor:
|
| 53 |
+
r"""Calculate pairwise euclidean distances.
|
| 54 |
+
|
| 55 |
+
.. math::
|
| 56 |
+
d_{euc}(x,y) = ||x - y||_2 = \sqrt{\sum_{d=1}^D (x_d - y_d)^2}
|
| 57 |
+
|
| 58 |
+
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
|
| 59 |
+
the rows of :math:`x` and :math:`y`.
|
| 60 |
+
If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
x: Tensor with shape ``[N, d]``
|
| 64 |
+
y: Tensor with shape ``[M, d]``, optional
|
| 65 |
+
reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
|
| 66 |
+
(applied along column dimension) or `'none'`, `None` for no reduction
|
| 67 |
+
zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
|
| 68 |
+
this defaults to `True` else if `y` is also given it defaults to `False`
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
|
| 72 |
+
|
| 73 |
+
Example:
|
| 74 |
+
>>> import torch
|
| 75 |
+
>>> from torchmetrics.functional.pairwise import pairwise_euclidean_distance
|
| 76 |
+
>>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
|
| 77 |
+
>>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
|
| 78 |
+
>>> pairwise_euclidean_distance(x, y)
|
| 79 |
+
tensor([[3.1623, 2.0000],
|
| 80 |
+
[5.3852, 4.1231],
|
| 81 |
+
[8.9443, 7.6158]])
|
| 82 |
+
>>> pairwise_euclidean_distance(x)
|
| 83 |
+
tensor([[0.0000, 2.2361, 5.8310],
|
| 84 |
+
[2.2361, 0.0000, 3.6056],
|
| 85 |
+
[5.8310, 3.6056, 0.0000]])
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
distance = _pairwise_euclidean_distance_update(x, y, zero_diagonal)
|
| 89 |
+
return _reduce_distance_matrix(distance, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/helpers.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _check_input(
|
| 20 |
+
x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
|
| 21 |
+
) -> tuple[Tensor, Tensor, bool]:
|
| 22 |
+
"""Check that input has the right dimensionality and sets the ``zero_diagonal`` argument if user has not set it.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
x: tensor of shape ``[N,d]``
|
| 26 |
+
y: if provided, a tensor of shape ``[M,d]``
|
| 27 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
if x.ndim != 2:
|
| 31 |
+
raise ValueError(f"Expected argument `x` to be a 2D tensor of shape `[N, d]` but got {x.shape}")
|
| 32 |
+
|
| 33 |
+
if y is not None:
|
| 34 |
+
if y.ndim != 2 or y.shape[1] != x.shape[1]:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
"Expected argument `y` to be a 2D tensor of shape `[M, d]` where"
|
| 37 |
+
" `d` should be same as the last dimension of `x`"
|
| 38 |
+
)
|
| 39 |
+
zero_diagonal = False if zero_diagonal is None else zero_diagonal
|
| 40 |
+
else:
|
| 41 |
+
y = x.clone()
|
| 42 |
+
zero_diagonal = True if zero_diagonal is None else zero_diagonal
|
| 43 |
+
return x, y, zero_diagonal
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _reduce_distance_matrix(distmat: Tensor, reduction: Optional[str] = None) -> Tensor:
|
| 47 |
+
"""Reduction of distance matrix.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
distmat: a ``[N,M]`` matrix
|
| 51 |
+
reduction: string determining how to reduce along last dimension
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
if reduction == "mean":
|
| 55 |
+
return distmat.mean(dim=-1)
|
| 56 |
+
if reduction == "sum":
|
| 57 |
+
return distmat.sum(dim=-1)
|
| 58 |
+
if reduction is None or reduction == "none":
|
| 59 |
+
return distmat
|
| 60 |
+
raise ValueError(f"Expected reduction to be one of `['mean', 'sum', None]` but got {reduction}")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/linear.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
|
| 20 |
+
from torchmetrics.utilities.compute import _safe_matmul
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _pairwise_linear_similarity_update(
|
| 24 |
+
x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
|
| 25 |
+
) -> Tensor:
|
| 26 |
+
"""Calculate the pairwise linear similarity matrix.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
x: tensor of shape ``[N,d]``
|
| 30 |
+
y: tensor of shape ``[M,d]``
|
| 31 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
|
| 35 |
+
|
| 36 |
+
distance = _safe_matmul(x, y)
|
| 37 |
+
if zero_diagonal:
|
| 38 |
+
distance.fill_diagonal_(0)
|
| 39 |
+
return distance
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def pairwise_linear_similarity(
|
| 43 |
+
x: Tensor,
|
| 44 |
+
y: Optional[Tensor] = None,
|
| 45 |
+
reduction: Literal["mean", "sum", "none", None] = None,
|
| 46 |
+
zero_diagonal: Optional[bool] = None,
|
| 47 |
+
) -> Tensor:
|
| 48 |
+
r"""Calculate pairwise linear similarity.
|
| 49 |
+
|
| 50 |
+
.. math::
|
| 51 |
+
s_{lin}(x,y) = <x,y> = \sum_{d=1}^D x_d \cdot y_d
|
| 52 |
+
|
| 53 |
+
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
|
| 54 |
+
the rows of :math:`x` and :math:`y`.
|
| 55 |
+
If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
x: Tensor with shape ``[N, d]``
|
| 59 |
+
y: Tensor with shape ``[M, d]``, optional
|
| 60 |
+
reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
|
| 61 |
+
(applied along column dimension) or `'none'`, `None` for no reduction
|
| 62 |
+
zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
|
| 63 |
+
this defaults to `True` else if `y` is also given it defaults to `False`
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
>>> import torch
|
| 70 |
+
>>> from torchmetrics.functional.pairwise import pairwise_linear_similarity
|
| 71 |
+
>>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
|
| 72 |
+
>>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
|
| 73 |
+
>>> pairwise_linear_similarity(x, y)
|
| 74 |
+
tensor([[ 2., 7.],
|
| 75 |
+
[ 3., 11.],
|
| 76 |
+
[ 5., 18.]])
|
| 77 |
+
>>> pairwise_linear_similarity(x)
|
| 78 |
+
tensor([[ 0., 21., 34.],
|
| 79 |
+
[21., 0., 55.],
|
| 80 |
+
[34., 55., 0.]])
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
distance = _pairwise_linear_similarity_update(x, y, zero_diagonal)
|
| 84 |
+
return _reduce_distance_matrix(distance, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/manhattan.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _pairwise_manhattan_distance_update(
|
| 23 |
+
x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
|
| 24 |
+
) -> Tensor:
|
| 25 |
+
"""Calculate the pairwise manhattan similarity matrix.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
x: tensor of shape ``[N,d]``
|
| 29 |
+
y: if provided, a tensor of shape ``[M,d]``
|
| 30 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
|
| 34 |
+
|
| 35 |
+
distance = (x.unsqueeze(1) - y.unsqueeze(0).repeat(x.shape[0], 1, 1)).abs().sum(dim=-1)
|
| 36 |
+
if zero_diagonal:
|
| 37 |
+
distance.fill_diagonal_(0)
|
| 38 |
+
return distance
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def pairwise_manhattan_distance(
|
| 42 |
+
x: Tensor,
|
| 43 |
+
y: Optional[Tensor] = None,
|
| 44 |
+
reduction: Literal["mean", "sum", "none", None] = None,
|
| 45 |
+
zero_diagonal: Optional[bool] = None,
|
| 46 |
+
) -> Tensor:
|
| 47 |
+
r"""Calculate pairwise manhattan distance.
|
| 48 |
+
|
| 49 |
+
.. math::
|
| 50 |
+
d_{man}(x,y) = ||x-y||_1 = \sum_{d=1}^D |x_d - y_d|
|
| 51 |
+
|
| 52 |
+
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
|
| 53 |
+
the rows of :math:`x` and :math:`y`.
|
| 54 |
+
If only :math:`x` is passed in, the calculation will be performed between the rows of :math:`x`.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
x: Tensor with shape ``[N, d]``
|
| 58 |
+
y: Tensor with shape ``[M, d]``, optional
|
| 59 |
+
reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
|
| 60 |
+
(applied along column dimension) or `'none'`, `None` for no reduction
|
| 61 |
+
zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
|
| 62 |
+
this defaults to `True` else if `y` is also given it defaults to `False`
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
>>> import torch
|
| 69 |
+
>>> from torchmetrics.functional.pairwise import pairwise_manhattan_distance
|
| 70 |
+
>>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
|
| 71 |
+
>>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
|
| 72 |
+
>>> pairwise_manhattan_distance(x, y)
|
| 73 |
+
tensor([[ 4., 2.],
|
| 74 |
+
[ 7., 5.],
|
| 75 |
+
[12., 10.]])
|
| 76 |
+
>>> pairwise_manhattan_distance(x)
|
| 77 |
+
tensor([[0., 3., 8.],
|
| 78 |
+
[3., 0., 5.],
|
| 79 |
+
[8., 5., 0.]])
|
| 80 |
+
|
| 81 |
+
"""
|
| 82 |
+
distance = _pairwise_manhattan_distance_update(x, y, zero_diagonal)
|
| 83 |
+
return _reduce_distance_matrix(distance, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/pairwise/minkowski.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The PyTorch Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.functional.pairwise.helpers import _check_input, _reduce_distance_matrix
|
| 21 |
+
from torchmetrics.utilities.exceptions import TorchMetricsUserError
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _pairwise_minkowski_distance_update(
|
| 25 |
+
x: Tensor, y: Optional[Tensor] = None, exponent: float = 2, zero_diagonal: Optional[bool] = None
|
| 26 |
+
) -> Tensor:
|
| 27 |
+
"""Calculate the pairwise minkowski distance matrix.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
x: tensor of shape ``[N,d]``
|
| 31 |
+
y: tensor of shape ``[M,d]``
|
| 32 |
+
exponent: int or float larger than 1, exponent to which the difference between preds and target is to be raised
|
| 33 |
+
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
|
| 37 |
+
if not (isinstance(exponent, (float, int)) and exponent >= 1):
|
| 38 |
+
raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {exponent}")
|
| 39 |
+
# upcast to float64 to prevent precision issues
|
| 40 |
+
_orig_dtype = x.dtype
|
| 41 |
+
x = x.to(torch.float64)
|
| 42 |
+
y = y.to(torch.float64)
|
| 43 |
+
distance = (x.unsqueeze(1) - y.unsqueeze(0)).abs().pow(exponent).sum(-1).pow(1.0 / exponent)
|
| 44 |
+
if zero_diagonal:
|
| 45 |
+
distance.fill_diagonal_(0)
|
| 46 |
+
return distance.to(_orig_dtype)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def pairwise_minkowski_distance(
|
| 50 |
+
x: Tensor,
|
| 51 |
+
y: Optional[Tensor] = None,
|
| 52 |
+
exponent: float = 2,
|
| 53 |
+
reduction: Literal["mean", "sum", "none", None] = None,
|
| 54 |
+
zero_diagonal: Optional[bool] = None,
|
| 55 |
+
) -> Tensor:
|
| 56 |
+
r"""Calculate pairwise minkowski distances.
|
| 57 |
+
|
| 58 |
+
.. math::
|
| 59 |
+
d_{minkowski}(x,y,p) = ||x - y||_p = \sqrt[p]{\sum_{d=1}^D (x_d - y_d)^p}
|
| 60 |
+
|
| 61 |
+
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between the rows of
|
| 62 |
+
:math:`x` and :math:`y`. If only :math:`x` is passed in, the calculation will be performed between the rows
|
| 63 |
+
of :math:`x`.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
x: Tensor with shape ``[N, d]``
|
| 67 |
+
y: Tensor with shape ``[M, d]``, optional
|
| 68 |
+
exponent: int or float larger than 1, exponent to which the difference between preds and target is to be raised
|
| 69 |
+
reduction: reduction to apply along the last dimension. Choose between `'mean'`, `'sum'`
|
| 70 |
+
(applied along column dimension) or `'none'`, `None` for no reduction
|
| 71 |
+
zero_diagonal: if the diagonal of the distance matrix should be set to 0. If only `x` is given
|
| 72 |
+
this defaults to `True` else if `y` is also given it defaults to `False`
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
A ``[N,N]`` matrix of distances if only ``x`` is given, else a ``[N,M]`` matrix
|
| 76 |
+
|
| 77 |
+
Example:
|
| 78 |
+
>>> import torch
|
| 79 |
+
>>> from torchmetrics.functional.pairwise import pairwise_minkowski_distance
|
| 80 |
+
>>> x = torch.tensor([[2, 3], [3, 5], [5, 8]], dtype=torch.float32)
|
| 81 |
+
>>> y = torch.tensor([[1, 0], [2, 1]], dtype=torch.float32)
|
| 82 |
+
>>> pairwise_minkowski_distance(x, y, exponent=4)
|
| 83 |
+
tensor([[3.0092, 2.0000],
|
| 84 |
+
[5.0317, 4.0039],
|
| 85 |
+
[8.1222, 7.0583]])
|
| 86 |
+
>>> pairwise_minkowski_distance(x, exponent=4)
|
| 87 |
+
tensor([[0.0000, 2.0305, 5.1547],
|
| 88 |
+
[2.0305, 0.0000, 3.1383],
|
| 89 |
+
[5.1547, 3.1383, 0.0000]])
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
distance = _pairwise_minkowski_distance_update(x, y, exponent, zero_diagonal)
|
| 93 |
+
return _reduce_distance_matrix(distance, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from torchmetrics.functional.regression.concordance import concordance_corrcoef
|
| 15 |
+
from torchmetrics.functional.regression.cosine_similarity import cosine_similarity
|
| 16 |
+
from torchmetrics.functional.regression.crps import continuous_ranked_probability_score
|
| 17 |
+
from torchmetrics.functional.regression.csi import critical_success_index
|
| 18 |
+
from torchmetrics.functional.regression.explained_variance import explained_variance
|
| 19 |
+
from torchmetrics.functional.regression.js_divergence import jensen_shannon_divergence
|
| 20 |
+
from torchmetrics.functional.regression.kendall import kendall_rank_corrcoef
|
| 21 |
+
from torchmetrics.functional.regression.kl_divergence import kl_divergence
|
| 22 |
+
from torchmetrics.functional.regression.log_cosh import log_cosh_error
|
| 23 |
+
from torchmetrics.functional.regression.log_mse import mean_squared_log_error
|
| 24 |
+
from torchmetrics.functional.regression.mae import mean_absolute_error
|
| 25 |
+
from torchmetrics.functional.regression.mape import mean_absolute_percentage_error
|
| 26 |
+
from torchmetrics.functional.regression.minkowski import minkowski_distance
|
| 27 |
+
from torchmetrics.functional.regression.mse import mean_squared_error
|
| 28 |
+
from torchmetrics.functional.regression.nrmse import normalized_root_mean_squared_error
|
| 29 |
+
from torchmetrics.functional.regression.pearson import pearson_corrcoef
|
| 30 |
+
from torchmetrics.functional.regression.r2 import r2_score
|
| 31 |
+
from torchmetrics.functional.regression.rse import relative_squared_error
|
| 32 |
+
from torchmetrics.functional.regression.spearman import spearman_corrcoef
|
| 33 |
+
from torchmetrics.functional.regression.symmetric_mape import symmetric_mean_absolute_percentage_error
|
| 34 |
+
from torchmetrics.functional.regression.tweedie_deviance import tweedie_deviance_score
|
| 35 |
+
from torchmetrics.functional.regression.wmape import weighted_mean_absolute_percentage_error
|
| 36 |
+
|
| 37 |
+
__all__ = [
|
| 38 |
+
"concordance_corrcoef",
|
| 39 |
+
"continuous_ranked_probability_score",
|
| 40 |
+
"cosine_similarity",
|
| 41 |
+
"critical_success_index",
|
| 42 |
+
"explained_variance",
|
| 43 |
+
"jensen_shannon_divergence",
|
| 44 |
+
"kendall_rank_corrcoef",
|
| 45 |
+
"kl_divergence",
|
| 46 |
+
"log_cosh_error",
|
| 47 |
+
"mean_absolute_error",
|
| 48 |
+
"mean_absolute_percentage_error",
|
| 49 |
+
"mean_absolute_percentage_error",
|
| 50 |
+
"mean_squared_error",
|
| 51 |
+
"mean_squared_log_error",
|
| 52 |
+
"minkowski_distance",
|
| 53 |
+
"normalized_root_mean_squared_error",
|
| 54 |
+
"pearson_corrcoef",
|
| 55 |
+
"r2_score",
|
| 56 |
+
"relative_squared_error",
|
| 57 |
+
"spearman_corrcoef",
|
| 58 |
+
"symmetric_mean_absolute_percentage_error",
|
| 59 |
+
"tweedie_deviance_score",
|
| 60 |
+
"weighted_mean_absolute_percentage_error",
|
| 61 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/concordance.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
|
| 17 |
+
from torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _concordance_corrcoef_compute(
|
| 21 |
+
max_abs_dev_x: Tensor,
|
| 22 |
+
max_abs_dev_y: Tensor,
|
| 23 |
+
mean_x: Tensor,
|
| 24 |
+
mean_y: Tensor,
|
| 25 |
+
var_x: Tensor,
|
| 26 |
+
var_y: Tensor,
|
| 27 |
+
corr_xy: Tensor,
|
| 28 |
+
nb: Tensor,
|
| 29 |
+
) -> Tensor:
|
| 30 |
+
"""Compute the final concordance correlation coefficient based on accumulated statistics."""
|
| 31 |
+
pearson = _pearson_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb)
|
| 32 |
+
var_x = var_x / (nb - 1)
|
| 33 |
+
var_y = var_y / (nb - 1)
|
| 34 |
+
return 2.0 * pearson * var_x.sqrt() * var_y.sqrt() / (var_x + var_y + (mean_x - mean_y) ** 2)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def concordance_corrcoef(preds: Tensor, target: Tensor) -> Tensor:
|
| 38 |
+
r"""Compute concordance correlation coefficient that measures the agreement between two variables.
|
| 39 |
+
|
| 40 |
+
.. math::
|
| 41 |
+
\rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2}
|
| 42 |
+
|
| 43 |
+
where :math:`\mu_x, \mu_y` is the means for the two variables, :math:`\sigma_x^2, \sigma_y^2` are the corresponding
|
| 44 |
+
variances and \rho is the pearson correlation coefficient between the two variables.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
preds: estimated scores
|
| 48 |
+
target: ground truth scores
|
| 49 |
+
|
| 50 |
+
Example (single output regression):
|
| 51 |
+
>>> from torchmetrics.functional.regression import concordance_corrcoef
|
| 52 |
+
>>> target = torch.tensor([3, -0.5, 2, 7])
|
| 53 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 54 |
+
>>> concordance_corrcoef(preds, target)
|
| 55 |
+
tensor([0.9777])
|
| 56 |
+
|
| 57 |
+
Example (multi output regression):
|
| 58 |
+
>>> from torchmetrics.functional.regression import concordance_corrcoef
|
| 59 |
+
>>> target = torch.tensor([[3, -0.5], [2, 7]])
|
| 60 |
+
>>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
|
| 61 |
+
>>> concordance_corrcoef(preds, target)
|
| 62 |
+
tensor([0.7273, 0.9887])
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
d = preds.shape[1] if preds.ndim == 2 else 1
|
| 66 |
+
_temp = torch.zeros(d, dtype=preds.dtype, device=preds.device)
|
| 67 |
+
mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone()
|
| 68 |
+
var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone()
|
| 69 |
+
max_abs_dev_x, max_abs_dev_y = _temp.clone(), _temp.clone()
|
| 70 |
+
mean_x, mean_y, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update(
|
| 71 |
+
preds=preds,
|
| 72 |
+
target=target,
|
| 73 |
+
mean_x=mean_x,
|
| 74 |
+
mean_y=mean_y,
|
| 75 |
+
max_abs_dev_x=max_abs_dev_x,
|
| 76 |
+
max_abs_dev_y=max_abs_dev_y,
|
| 77 |
+
var_x=var_x,
|
| 78 |
+
var_y=var_y,
|
| 79 |
+
corr_xy=corr_xy,
|
| 80 |
+
num_prior=nb,
|
| 81 |
+
num_outputs=1 if preds.ndim == 1 else preds.shape[-1],
|
| 82 |
+
)
|
| 83 |
+
return _concordance_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, mean_x, mean_y, var_x, var_y, corr_xy, nb)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/cosine_similarity.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _cosine_similarity_update(
|
| 23 |
+
preds: Tensor,
|
| 24 |
+
target: Tensor,
|
| 25 |
+
) -> tuple[Tensor, Tensor]:
|
| 26 |
+
"""Update and returns variables required to compute Cosine Similarity. Checks for same shape of input tensors.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
preds: Predicted tensor
|
| 30 |
+
target: Ground truth tensor
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
_check_same_shape(preds, target)
|
| 34 |
+
if preds.ndim != 2:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
"Expected input to cosine similarity to be 2D tensors of shape `[N,D]` where `N` is the number of samples"
|
| 37 |
+
f" and `D` is the number of dimensions, but got tensor of shape {preds.shape}"
|
| 38 |
+
)
|
| 39 |
+
preds = preds.float()
|
| 40 |
+
target = target.float()
|
| 41 |
+
|
| 42 |
+
return preds, target
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor:
|
| 46 |
+
"""Compute Cosine Similarity.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
preds: Predicted tensor
|
| 50 |
+
target: Ground truth tensor
|
| 51 |
+
reduction:
|
| 52 |
+
The method of reducing along the batch dimension using sum, mean or taking the individual scores
|
| 53 |
+
|
| 54 |
+
Example:
|
| 55 |
+
>>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]])
|
| 56 |
+
>>> preds = torch.tensor([[1, 2, 3, 4], [-1, -2, -3, -4]])
|
| 57 |
+
>>> preds, target = _cosine_similarity_update(preds, target)
|
| 58 |
+
>>> _cosine_similarity_compute(preds, target, 'none')
|
| 59 |
+
tensor([ 1.0000, -1.0000])
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
dot_product = (preds * target).sum(dim=-1)
|
| 63 |
+
preds_norm = preds.norm(dim=-1)
|
| 64 |
+
target_norm = target.norm(dim=-1)
|
| 65 |
+
similarity = dot_product / (preds_norm * target_norm)
|
| 66 |
+
reduction_mapping = {
|
| 67 |
+
"sum": torch.sum,
|
| 68 |
+
"mean": torch.mean,
|
| 69 |
+
"none": lambda x: x,
|
| 70 |
+
None: lambda x: x,
|
| 71 |
+
}
|
| 72 |
+
return reduction_mapping[reduction](similarity) # type: ignore[operator]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def cosine_similarity(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor:
|
| 76 |
+
r"""Compute the `Cosine Similarity`_.
|
| 77 |
+
|
| 78 |
+
.. math::
|
| 79 |
+
cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
|
| 80 |
+
\frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
|
| 81 |
+
|
| 82 |
+
where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
preds: Predicted tensor with shape ``(N,d)``
|
| 86 |
+
target: Ground truth tensor with shape ``(N,d)``
|
| 87 |
+
reduction:
|
| 88 |
+
The method of reducing along the batch dimension using sum, mean or taking the individual scores
|
| 89 |
+
|
| 90 |
+
Example:
|
| 91 |
+
>>> from torchmetrics.functional.regression import cosine_similarity
|
| 92 |
+
>>> target = torch.tensor([[1, 2, 3, 4],
|
| 93 |
+
... [1, 2, 3, 4]])
|
| 94 |
+
>>> preds = torch.tensor([[1, 2, 3, 4],
|
| 95 |
+
... [-1, -2, -3, -4]])
|
| 96 |
+
>>> cosine_similarity(preds, target, 'none')
|
| 97 |
+
tensor([ 1.0000, -1.0000])
|
| 98 |
+
|
| 99 |
+
"""
|
| 100 |
+
preds, target = _cosine_similarity_update(preds, target)
|
| 101 |
+
return _cosine_similarity_compute(preds, target, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/crps.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Tuple
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
|
| 20 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _crps_update(preds: Tensor, target: Tensor) -> Tuple[int, Tensor, Tensor]:
|
| 24 |
+
"""Compute intermediate CRPS values before aggregation.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
preds: Tensor of shape (batch_size, ensemble_members)
|
| 28 |
+
target: Tensor of shape (batch_size,)
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
batch_size: int
|
| 32 |
+
diff: Tensor (batch-wise absolute error term)
|
| 33 |
+
ensemble_sum: Tensor (pairwise ensemble term)
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
# Only second dimension should deviate in shape (the ensemble members)
|
| 37 |
+
_check_same_shape(preds[:, 0], target)
|
| 38 |
+
|
| 39 |
+
batch_size, n_ensemble_members = preds.shape
|
| 40 |
+
if n_ensemble_members < 2:
|
| 41 |
+
raise ValueError(f"CRPS requires at least 2 ensemble members, but you provided {preds.shape}.")
|
| 42 |
+
|
| 43 |
+
# sort forecasts
|
| 44 |
+
preds = torch.sort(preds, dim=1)[0]
|
| 45 |
+
|
| 46 |
+
# inflate observations:
|
| 47 |
+
observation_inflated = target.unsqueeze(1).expand_as(preds)
|
| 48 |
+
|
| 49 |
+
# Compute mean absolute difference between predictions and target
|
| 50 |
+
diff = torch.sum(torch.abs(preds - observation_inflated), dim=1) / n_ensemble_members
|
| 51 |
+
|
| 52 |
+
# Compute ensemble term using the reference implementation formula
|
| 53 |
+
ensemble_diffs = torch.abs(preds.unsqueeze(2) - preds.unsqueeze(1))
|
| 54 |
+
ensemble_sum = torch.sum(ensemble_diffs, dim=(1, 2)) / (2 * n_ensemble_members * n_ensemble_members)
|
| 55 |
+
|
| 56 |
+
return batch_size, diff, ensemble_sum
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _crps_compute(batch_size: int, diff: Tensor, ensemble_sum: Tensor) -> Tensor:
|
| 60 |
+
"""Final CRPS computation."""
|
| 61 |
+
return torch.mean(diff - ensemble_sum) # Changed from sum to mean
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def continuous_ranked_probability_score(preds: Tensor, target: Tensor) -> Tensor:
|
| 65 |
+
r"""Computes continuous ranked probability score.
|
| 66 |
+
|
| 67 |
+
.. math::
|
| 68 |
+
CRPS(F, y) = \int_{-\infty}^{\infty} (F(x) - 1_{x \geq y})^2 dx
|
| 69 |
+
|
| 70 |
+
where :math:`F` is the predicted cumulative distribution function and :math:`y` is the true target. The metric is
|
| 71 |
+
usually used to evaluate probabilistic regression models, such as forecasting models. A lower CRPS indicates a
|
| 72 |
+
better forecast, meaning that forecasted probabilities are closer to the true observed values. CRPS can also be
|
| 73 |
+
seen as a generalization of the brier score for non binary classification problems.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
preds: a 2d tensor of shape (batch_size, ensemble_members) with predictions. The second dimension represents
|
| 77 |
+
the ensemble members.
|
| 78 |
+
target: a 1d tensor of shape (batch_size) with the target values.
|
| 79 |
+
|
| 80 |
+
Return:
|
| 81 |
+
Tensor with CRPS
|
| 82 |
+
|
| 83 |
+
Raises:
|
| 84 |
+
ValueError:
|
| 85 |
+
If the number of ensemble members is less than 2.
|
| 86 |
+
ValueError:
|
| 87 |
+
If the first dimension of preds and target do not match.
|
| 88 |
+
|
| 89 |
+
Example::
|
| 90 |
+
>>> from torchmetrics.functional.regression import continuous_ranked_probability_score
|
| 91 |
+
>>> from torch import randn
|
| 92 |
+
>>> preds = randn(10, 5)
|
| 93 |
+
>>> target = randn(10)
|
| 94 |
+
>>> continuous_ranked_probability_score(preds, target)
|
| 95 |
+
tensor(0.7731)
|
| 96 |
+
|
| 97 |
+
"""
|
| 98 |
+
batch_size, diff, ensemble_sum = _crps_update(preds, target)
|
| 99 |
+
return _crps_compute(batch_size, diff, ensemble_sum)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/csi.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
from torchmetrics.utilities.compute import _safe_divide
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _critical_success_index_update(
|
| 24 |
+
preds: Tensor, target: Tensor, threshold: float, keep_sequence_dim: Optional[int] = None
|
| 25 |
+
) -> tuple[Tensor, Tensor, Tensor]:
|
| 26 |
+
"""Update and return variables required to compute Critical Success Index. Checks for same shape of tensors.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
preds: Predicted tensor
|
| 30 |
+
target: Ground truth tensor
|
| 31 |
+
threshold: Values above or equal to threshold are replaced with 1, below by 0
|
| 32 |
+
keep_sequence_dim: Index of the sequence dimension if the inputs are sequences of images. If specified,
|
| 33 |
+
the score will be calculated separately for each image in the sequence. If ``None``, the score will be
|
| 34 |
+
calculated across all dimensions.
|
| 35 |
+
|
| 36 |
+
"""
|
| 37 |
+
_check_same_shape(preds, target)
|
| 38 |
+
|
| 39 |
+
if keep_sequence_dim is None:
|
| 40 |
+
sum_dims = None
|
| 41 |
+
elif not 0 <= keep_sequence_dim < preds.ndim:
|
| 42 |
+
raise ValueError(f"Expected keep_sequence dim to be in range [0, {preds.ndim}] but got {keep_sequence_dim}")
|
| 43 |
+
else:
|
| 44 |
+
sum_dims = tuple(i for i in range(preds.ndim) if i != keep_sequence_dim)
|
| 45 |
+
|
| 46 |
+
# binarize the tensors with the threshold
|
| 47 |
+
preds_bin = (preds >= threshold).bool()
|
| 48 |
+
target_bin = (target >= threshold).bool()
|
| 49 |
+
|
| 50 |
+
if keep_sequence_dim is None:
|
| 51 |
+
hits = torch.sum(preds_bin & target_bin).int()
|
| 52 |
+
misses = torch.sum((preds_bin ^ target_bin) & target_bin).int()
|
| 53 |
+
false_alarms = torch.sum((preds_bin ^ target_bin) & preds_bin).int()
|
| 54 |
+
else:
|
| 55 |
+
hits = torch.sum(preds_bin & target_bin, dim=sum_dims).int()
|
| 56 |
+
misses = torch.sum((preds_bin ^ target_bin) & target_bin, dim=sum_dims).int()
|
| 57 |
+
false_alarms = torch.sum((preds_bin ^ target_bin) & preds_bin, dim=sum_dims).int()
|
| 58 |
+
return hits, misses, false_alarms
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _critical_success_index_compute(hits: Tensor, misses: Tensor, false_alarms: Tensor) -> Tensor:
|
| 62 |
+
"""Compute critical success index.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
hits: Number of true positives after binarization
|
| 66 |
+
misses: Number of false negatives after binarization
|
| 67 |
+
false_alarms: Number of false positives after binarization
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
If input tensors are 5-dimensional and ``keep_sequence_dim=True``, the metric returns a ``(S,)`` vector
|
| 71 |
+
with CSI scores for each image in the sequence. Otherwise, it returns a scalar tensor with the CSI score.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
return _safe_divide(hits, hits + misses + false_alarms)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def critical_success_index(
|
| 78 |
+
preds: Tensor, target: Tensor, threshold: float, keep_sequence_dim: Optional[int] = None
|
| 79 |
+
) -> Tensor:
|
| 80 |
+
"""Compute critical success index.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
preds: Predicted tensor
|
| 84 |
+
target: Ground truth tensor
|
| 85 |
+
threshold: Values above or equal to threshold are replaced with 1, below by 0
|
| 86 |
+
keep_sequence_dim: Index of the sequence dimension if the inputs are sequences of images. If specified,
|
| 87 |
+
the score will be calculated separately for each image in the sequence. If ``None``, the score will be
|
| 88 |
+
calculated across all dimensions.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
If ``keep_sequence_dim`` is specified, the metric returns a vector of with CSI scores for each image
|
| 92 |
+
in the sequence. Otherwise, it returns a scalar tensor with the CSI score.
|
| 93 |
+
|
| 94 |
+
Example:
|
| 95 |
+
>>> import torch
|
| 96 |
+
>>> from torchmetrics.functional.regression import critical_success_index
|
| 97 |
+
>>> x = torch.Tensor([[0.2, 0.7], [0.9, 0.3]])
|
| 98 |
+
>>> y = torch.Tensor([[0.4, 0.2], [0.8, 0.6]])
|
| 99 |
+
>>> critical_success_index(x, y, 0.5)
|
| 100 |
+
tensor(0.3333)
|
| 101 |
+
|
| 102 |
+
Example:
|
| 103 |
+
>>> import torch
|
| 104 |
+
>>> from torchmetrics.functional.regression import critical_success_index
|
| 105 |
+
>>> x = torch.Tensor([[[0.2, 0.7], [0.9, 0.3]], [[0.2, 0.7], [0.9, 0.3]]])
|
| 106 |
+
>>> y = torch.Tensor([[[0.4, 0.2], [0.8, 0.6]], [[0.4, 0.2], [0.8, 0.6]]])
|
| 107 |
+
>>> critical_success_index(x, y, 0.5, keep_sequence_dim=0)
|
| 108 |
+
tensor([0.3333, 0.3333])
|
| 109 |
+
|
| 110 |
+
"""
|
| 111 |
+
hits, misses, false_alarms = _critical_success_index_update(preds, target, threshold, keep_sequence_dim)
|
| 112 |
+
return _critical_success_index_compute(hits, misses, false_alarms)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/explained_variance.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from collections.abc import Sequence
|
| 15 |
+
from typing import Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 22 |
+
|
| 23 |
+
ALLOWED_MULTIOUTPUT = ("raw_values", "uniform_average", "variance_weighted")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _explained_variance_update(preds: Tensor, target: Tensor) -> tuple[int, Tensor, Tensor, Tensor, Tensor]:
|
| 27 |
+
"""Update and returns variables required to compute Explained Variance. Checks for same shape of input tensors.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
preds: Predicted tensor
|
| 31 |
+
target: Ground truth tensor
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
_check_same_shape(preds, target)
|
| 35 |
+
|
| 36 |
+
num_obs = preds.size(0)
|
| 37 |
+
sum_error = torch.sum(target - preds, dim=0)
|
| 38 |
+
diff = target - preds
|
| 39 |
+
sum_squared_error = torch.sum(diff * diff, dim=0)
|
| 40 |
+
|
| 41 |
+
sum_target = torch.sum(target, dim=0)
|
| 42 |
+
sum_squared_target = torch.sum(target * target, dim=0)
|
| 43 |
+
|
| 44 |
+
return num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _explained_variance_compute(
|
| 48 |
+
num_obs: Union[int, Tensor],
|
| 49 |
+
sum_error: Tensor,
|
| 50 |
+
sum_squared_error: Tensor,
|
| 51 |
+
sum_target: Tensor,
|
| 52 |
+
sum_squared_target: Tensor,
|
| 53 |
+
multioutput: Literal["raw_values", "uniform_average", "variance_weighted"] = "uniform_average",
|
| 54 |
+
) -> Tensor:
|
| 55 |
+
"""Compute Explained Variance.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
num_obs: Number of predictions or observations
|
| 59 |
+
sum_error: Sum of errors over all observations
|
| 60 |
+
sum_squared_error: Sum of square of errors over all observations
|
| 61 |
+
sum_target: Sum of target values
|
| 62 |
+
sum_squared_target: Sum of squares of target values
|
| 63 |
+
multioutput: Defines aggregation in the case of multiple output scores. Can be one
|
| 64 |
+
of the following strings:
|
| 65 |
+
|
| 66 |
+
* ``'raw_values'`` returns full set of scores
|
| 67 |
+
* ``'uniform_average'`` scores are uniformly averaged
|
| 68 |
+
* ``'variance_weighted'`` scores are weighted by their individual variances
|
| 69 |
+
|
| 70 |
+
Example:
|
| 71 |
+
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
|
| 72 |
+
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
|
| 73 |
+
>>> num_obs, sum_error, ss_error, sum_target, ss_target = _explained_variance_update(preds, target)
|
| 74 |
+
>>> _explained_variance_compute(num_obs, sum_error, ss_error, sum_target, ss_target, multioutput='raw_values')
|
| 75 |
+
tensor([0.9677, 1.0000])
|
| 76 |
+
|
| 77 |
+
"""
|
| 78 |
+
diff_avg = sum_error / num_obs
|
| 79 |
+
numerator = sum_squared_error / num_obs - (diff_avg * diff_avg)
|
| 80 |
+
|
| 81 |
+
target_avg = sum_target / num_obs
|
| 82 |
+
denominator = sum_squared_target / num_obs - (target_avg * target_avg)
|
| 83 |
+
|
| 84 |
+
# Take care of division by zero
|
| 85 |
+
nonzero_numerator = numerator != 0
|
| 86 |
+
nonzero_denominator = denominator != 0
|
| 87 |
+
valid_score = nonzero_numerator & nonzero_denominator
|
| 88 |
+
output_scores = torch.ones_like(diff_avg)
|
| 89 |
+
output_scores[valid_score] = 1.0 - (numerator[valid_score] / denominator[valid_score])
|
| 90 |
+
output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0
|
| 91 |
+
|
| 92 |
+
# Decide what to do in multioutput case
|
| 93 |
+
# Todo: allow user to pass in tensor with weights
|
| 94 |
+
if multioutput == "raw_values":
|
| 95 |
+
return output_scores
|
| 96 |
+
if multioutput == "uniform_average":
|
| 97 |
+
return torch.mean(output_scores)
|
| 98 |
+
denom_sum = torch.sum(denominator)
|
| 99 |
+
return torch.sum(denominator / denom_sum * output_scores)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def explained_variance(
|
| 103 |
+
preds: Tensor,
|
| 104 |
+
target: Tensor,
|
| 105 |
+
multioutput: Literal["raw_values", "uniform_average", "variance_weighted"] = "uniform_average",
|
| 106 |
+
) -> Union[Tensor, Sequence[Tensor]]:
|
| 107 |
+
"""Compute explained variance.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
preds: estimated labels
|
| 111 |
+
target: ground truth labels
|
| 112 |
+
multioutput: Defines aggregation in the case of multiple output scores. Can be one
|
| 113 |
+
of the following strings):
|
| 114 |
+
|
| 115 |
+
* ``'raw_values'`` returns full set of scores
|
| 116 |
+
* ``'uniform_average'`` scores are uniformly averaged
|
| 117 |
+
* ``'variance_weighted'`` scores are weighted by their individual variances
|
| 118 |
+
|
| 119 |
+
Example:
|
| 120 |
+
>>> from torchmetrics.functional.regression import explained_variance
|
| 121 |
+
>>> target = torch.tensor([3, -0.5, 2, 7])
|
| 122 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 123 |
+
>>> explained_variance(preds, target)
|
| 124 |
+
tensor(0.9572)
|
| 125 |
+
|
| 126 |
+
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
|
| 127 |
+
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
|
| 128 |
+
>>> explained_variance(preds, target, multioutput='raw_values')
|
| 129 |
+
tensor([0.9677, 1.0000])
|
| 130 |
+
|
| 131 |
+
"""
|
| 132 |
+
if multioutput not in ALLOWED_MULTIOUTPUT:
|
| 133 |
+
raise ValueError(f"Invalid input to argument `multioutput`. Choose one of the following: {ALLOWED_MULTIOUTPUT}")
|
| 134 |
+
num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update(preds, target)
|
| 135 |
+
return _explained_variance_compute(
|
| 136 |
+
num_obs,
|
| 137 |
+
sum_error,
|
| 138 |
+
sum_squared_error,
|
| 139 |
+
sum_target,
|
| 140 |
+
sum_squared_target,
|
| 141 |
+
multioutput,
|
| 142 |
+
)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/js_divergence.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.functional.regression.kl_divergence import kl_divergence
|
| 22 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _jsd_update(p: Tensor, q: Tensor, log_prob: bool) -> tuple[Tensor, int]:
|
| 26 |
+
"""Update and returns jensen-shannon divergence scores for each observation and the total number of observations.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
p: data distribution with shape ``[N, d]``
|
| 30 |
+
q: prior or approximate distribution with shape ``[N, d]``
|
| 31 |
+
log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
|
| 32 |
+
will normalize to make sure the distributes sum to 1
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
_check_same_shape(p, q)
|
| 36 |
+
if p.ndim != 2 or q.ndim != 2:
|
| 37 |
+
raise ValueError(f"Expected both p and q distribution to be 2D but got {p.ndim} and {q.ndim} respectively")
|
| 38 |
+
|
| 39 |
+
total = p.shape[0]
|
| 40 |
+
if log_prob:
|
| 41 |
+
mean = torch.logsumexp(torch.stack([p, q]), dim=0) - torch.log(torch.tensor(2.0))
|
| 42 |
+
measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence(
|
| 43 |
+
q, mean, log_prob=log_prob, reduction=None
|
| 44 |
+
)
|
| 45 |
+
else:
|
| 46 |
+
p = p / p.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
|
| 47 |
+
q = q / q.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
|
| 48 |
+
mean = (p + q) / 2
|
| 49 |
+
measures = 0.5 * kl_divergence(p, mean, log_prob=log_prob, reduction=None) + 0.5 * kl_divergence(
|
| 50 |
+
q, mean, log_prob=log_prob, reduction=None
|
| 51 |
+
)
|
| 52 |
+
return measures, total
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _jsd_compute(
|
| 56 |
+
measures: Tensor, total: Union[int, Tensor], reduction: Literal["mean", "sum", "none", None] = "mean"
|
| 57 |
+
) -> Tensor:
|
| 58 |
+
"""Compute and reduce the Jensen-Shannon divergence based on the type of reduction."""
|
| 59 |
+
if reduction == "sum":
|
| 60 |
+
return measures.sum()
|
| 61 |
+
if reduction == "mean":
|
| 62 |
+
return measures.sum() / total
|
| 63 |
+
if reduction is None or reduction == "none":
|
| 64 |
+
return measures
|
| 65 |
+
return measures / total
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def jensen_shannon_divergence(
|
| 69 |
+
p: Tensor, q: Tensor, log_prob: bool = False, reduction: Literal["mean", "sum", "none", None] = "mean"
|
| 70 |
+
) -> Tensor:
|
| 71 |
+
r"""Compute `Jensen-Shannon divergence`_.
|
| 72 |
+
|
| 73 |
+
.. math::
|
| 74 |
+
D_{JS}(P||Q) = \frac{1}{2} D_{KL}(P||M) + \frac{1}{2} D_{KL}(Q||M)
|
| 75 |
+
|
| 76 |
+
Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
|
| 77 |
+
over data and :math:`Q` is often a prior or approximation of :math:`P`. :math:`D_{KL}` is the `KL divergence`_ and
|
| 78 |
+
:math:`M` is the average of the two distributions. It should be noted that the Jensen-Shannon divergence is a
|
| 79 |
+
symmetrical metric i.e. :math:`D_{JS}(P||Q) = D_{JS}(Q||P)`.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
p: data distribution with shape ``[N, d]``
|
| 83 |
+
q: prior or approximate distribution with shape ``[N, d]``
|
| 84 |
+
log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
|
| 85 |
+
will normalize to make sure the distributes sum to 1
|
| 86 |
+
reduction:
|
| 87 |
+
Determines how to reduce over the ``N``/batch dimension:
|
| 88 |
+
|
| 89 |
+
- ``'mean'`` [default]: Averages score across samples
|
| 90 |
+
- ``'sum'``: Sum score across samples
|
| 91 |
+
- ``'none'`` or ``None``: Returns score per sample
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
>>> from torch import tensor
|
| 95 |
+
>>> p = tensor([[0.36, 0.48, 0.16]])
|
| 96 |
+
>>> q = tensor([[1/3, 1/3, 1/3]])
|
| 97 |
+
>>> jensen_shannon_divergence(p, q)
|
| 98 |
+
tensor(0.0225)
|
| 99 |
+
|
| 100 |
+
"""
|
| 101 |
+
measures, total = _jsd_update(p, q, log_prob)
|
| 102 |
+
return _jsd_compute(measures, total, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kendall.py
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import List, Optional, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs
|
| 21 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 22 |
+
from torchmetrics.utilities.data import _bincount, _cumsum, dim_zero_cat
|
| 23 |
+
from torchmetrics.utilities.enums import EnumStr
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class _MetricVariant(EnumStr):
|
| 27 |
+
"""Enumerate for metric variants."""
|
| 28 |
+
|
| 29 |
+
A = "a"
|
| 30 |
+
B = "b"
|
| 31 |
+
C = "c"
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def _name() -> str:
|
| 35 |
+
return "variant"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class _TestAlternative(EnumStr):
|
| 39 |
+
"""Enumerate for test alternative options."""
|
| 40 |
+
|
| 41 |
+
TWO_SIDED = "two-sided"
|
| 42 |
+
LESS = "less"
|
| 43 |
+
GREATER = "greater"
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def _name() -> str:
|
| 47 |
+
return "alternative"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _sort_on_first_sequence(x: Tensor, y: Tensor) -> tuple[Tensor, Tensor]:
|
| 51 |
+
"""Sort sequences in an ascent order according to the sequence ``x``."""
|
| 52 |
+
# We need to clone `y` tensor not to change an object in memory
|
| 53 |
+
y = torch.clone(y)
|
| 54 |
+
x, y = x.T, y.T
|
| 55 |
+
x, perm = x.sort()
|
| 56 |
+
for i in range(x.shape[0]):
|
| 57 |
+
y[i] = y[i][perm[i]]
|
| 58 |
+
return x.T, y.T
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _concordant_element_sum(x: Tensor, y: Tensor, i: int) -> Tensor:
|
| 62 |
+
"""Count a total number of concordant pairs in a single sequence."""
|
| 63 |
+
return torch.logical_and(x[i] < x[(i + 1) :], y[i] < y[(i + 1) :]).sum(0).unsqueeze(0)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _count_concordant_pairs(preds: Tensor, target: Tensor) -> Tensor:
|
| 67 |
+
"""Count a total number of concordant pairs in given sequences."""
|
| 68 |
+
return torch.cat([_concordant_element_sum(preds, target, i) for i in range(preds.shape[0])]).sum(0)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _discordant_element_sum(x: Tensor, y: Tensor, i: int) -> Tensor:
|
| 72 |
+
"""Count a total number of discordant pairs in a single sequences."""
|
| 73 |
+
return (
|
| 74 |
+
torch.logical_or(
|
| 75 |
+
torch.logical_and(x[i] > x[(i + 1) :], y[i] < y[(i + 1) :]),
|
| 76 |
+
torch.logical_and(x[i] < x[(i + 1) :], y[i] > y[(i + 1) :]),
|
| 77 |
+
)
|
| 78 |
+
.sum(0)
|
| 79 |
+
.unsqueeze(0)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _count_discordant_pairs(preds: Tensor, target: Tensor) -> Tensor:
|
| 84 |
+
"""Count a total number of discordant pairs in given sequences."""
|
| 85 |
+
return torch.cat([_discordant_element_sum(preds, target, i) for i in range(preds.shape[0])]).sum(0)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _convert_sequence_to_dense_rank(x: Tensor, sort: bool = False) -> Tensor:
|
| 89 |
+
"""Convert a sequence to the rank tensor."""
|
| 90 |
+
# Sort if a sequence has not been sorted before
|
| 91 |
+
if sort:
|
| 92 |
+
x = x.sort(dim=0).values
|
| 93 |
+
_ones = torch.zeros(1, x.shape[1], dtype=torch.int32, device=x.device)
|
| 94 |
+
return _cumsum(torch.cat([_ones, (x[1:] != x[:-1]).int()], dim=0), dim=0)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _get_ties(x: Tensor) -> tuple[Tensor, Tensor, Tensor]:
|
| 98 |
+
"""Get a total number of ties and staistics for p-value calculation for a given sequence."""
|
| 99 |
+
ties = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device)
|
| 100 |
+
ties_p1 = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device)
|
| 101 |
+
ties_p2 = torch.zeros(x.shape[1], dtype=x.dtype, device=x.device)
|
| 102 |
+
for dim in range(x.shape[1]):
|
| 103 |
+
n_ties = _bincount(x[:, dim])
|
| 104 |
+
n_ties = n_ties[n_ties > 1]
|
| 105 |
+
ties[dim] = (n_ties * (n_ties - 1) // 2).sum()
|
| 106 |
+
ties_p1[dim] = (n_ties * (n_ties - 1.0) * (n_ties - 2)).sum()
|
| 107 |
+
ties_p2[dim] = (n_ties * (n_ties - 1.0) * (2 * n_ties + 5)).sum()
|
| 108 |
+
|
| 109 |
+
return ties, ties_p1, ties_p2
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _get_metric_metadata(
|
| 113 |
+
preds: Tensor, target: Tensor, variant: _MetricVariant
|
| 114 |
+
) -> tuple[
|
| 115 |
+
Tensor,
|
| 116 |
+
Tensor,
|
| 117 |
+
Optional[Tensor],
|
| 118 |
+
Optional[Tensor],
|
| 119 |
+
Optional[Tensor],
|
| 120 |
+
Optional[Tensor],
|
| 121 |
+
Optional[Tensor],
|
| 122 |
+
Optional[Tensor],
|
| 123 |
+
Tensor,
|
| 124 |
+
]:
|
| 125 |
+
"""Obtain statistics to calculate metric value."""
|
| 126 |
+
preds, target = _sort_on_first_sequence(preds, target)
|
| 127 |
+
|
| 128 |
+
concordant_pairs = _count_concordant_pairs(preds, target)
|
| 129 |
+
discordant_pairs = _count_discordant_pairs(preds, target)
|
| 130 |
+
|
| 131 |
+
n_total = torch.tensor(preds.shape[0], device=preds.device)
|
| 132 |
+
preds_ties = target_ties = None
|
| 133 |
+
preds_ties_p1 = preds_ties_p2 = target_ties_p1 = target_ties_p2 = None
|
| 134 |
+
if variant != _MetricVariant.A:
|
| 135 |
+
preds = _convert_sequence_to_dense_rank(preds)
|
| 136 |
+
target = _convert_sequence_to_dense_rank(target, sort=True)
|
| 137 |
+
preds_ties, preds_ties_p1, preds_ties_p2 = _get_ties(preds)
|
| 138 |
+
target_ties, target_ties_p1, target_ties_p2 = _get_ties(target)
|
| 139 |
+
return (
|
| 140 |
+
concordant_pairs,
|
| 141 |
+
discordant_pairs,
|
| 142 |
+
preds_ties,
|
| 143 |
+
preds_ties_p1,
|
| 144 |
+
preds_ties_p2,
|
| 145 |
+
target_ties,
|
| 146 |
+
target_ties_p1,
|
| 147 |
+
target_ties_p2,
|
| 148 |
+
n_total,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _calculate_tau(
|
| 153 |
+
preds: Tensor,
|
| 154 |
+
target: Tensor,
|
| 155 |
+
concordant_pairs: Tensor,
|
| 156 |
+
discordant_pairs: Tensor,
|
| 157 |
+
con_min_dis_pairs: Tensor,
|
| 158 |
+
n_total: Tensor,
|
| 159 |
+
preds_ties: Optional[Tensor],
|
| 160 |
+
target_ties: Optional[Tensor],
|
| 161 |
+
variant: _MetricVariant,
|
| 162 |
+
) -> Tensor:
|
| 163 |
+
"""Calculate Kendall's tau from metric metadata."""
|
| 164 |
+
if variant == _MetricVariant.A:
|
| 165 |
+
return con_min_dis_pairs / (concordant_pairs + discordant_pairs)
|
| 166 |
+
if variant == _MetricVariant.B:
|
| 167 |
+
total_combinations: Tensor = n_total * (n_total - 1) // 2
|
| 168 |
+
if preds_ties is None:
|
| 169 |
+
preds_ties = torch.tensor(0.0, dtype=total_combinations.dtype, device=total_combinations.device)
|
| 170 |
+
if target_ties is None:
|
| 171 |
+
target_ties = torch.tensor(0.0, dtype=total_combinations.dtype, device=total_combinations.device)
|
| 172 |
+
denominator = (total_combinations - preds_ties) * (total_combinations - target_ties)
|
| 173 |
+
return con_min_dis_pairs / torch.sqrt(denominator)
|
| 174 |
+
|
| 175 |
+
preds_unique = torch.tensor([len(p.unique()) for p in preds.T], dtype=preds.dtype, device=preds.device)
|
| 176 |
+
target_unique = torch.tensor([len(t.unique()) for t in target.T], dtype=target.dtype, device=target.device)
|
| 177 |
+
min_classes = torch.minimum(preds_unique, target_unique)
|
| 178 |
+
return 2 * con_min_dis_pairs / ((min_classes - 1) / min_classes * n_total**2)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _get_p_value_for_t_value_from_dist(t_value: Tensor) -> Tensor:
|
| 182 |
+
"""Obtain p-value for a given Tensor of t-values. Handle ``nan`` which cannot be passed into torch distributions.
|
| 183 |
+
|
| 184 |
+
When t-value is ``nan``, a resulted p-value should be alson ``nan``.
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
device = t_value
|
| 188 |
+
normal_dist = torch.distributions.normal.Normal(torch.tensor([0.0]).to(device), torch.tensor([1.0]).to(device))
|
| 189 |
+
|
| 190 |
+
is_nan = t_value.isnan()
|
| 191 |
+
t_value = t_value.nan_to_num()
|
| 192 |
+
p_value = normal_dist.cdf(t_value)
|
| 193 |
+
return p_value.where(~is_nan, torch.tensor(float("nan"), dtype=p_value.dtype, device=p_value.device))
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _calculate_p_value(
|
| 197 |
+
con_min_dis_pairs: Tensor,
|
| 198 |
+
n_total: Tensor,
|
| 199 |
+
preds_ties: Optional[Tensor],
|
| 200 |
+
preds_ties_p1: Optional[Tensor],
|
| 201 |
+
preds_ties_p2: Optional[Tensor],
|
| 202 |
+
target_ties: Optional[Tensor],
|
| 203 |
+
target_ties_p1: Optional[Tensor],
|
| 204 |
+
target_ties_p2: Optional[Tensor],
|
| 205 |
+
variant: _MetricVariant,
|
| 206 |
+
alternative: Optional[_TestAlternative],
|
| 207 |
+
) -> Tensor:
|
| 208 |
+
"""Calculate p-value for Kendall's tau from metric metadata."""
|
| 209 |
+
t_value_denominator_base = n_total * (n_total - 1) * (2 * n_total + 5)
|
| 210 |
+
if variant == _MetricVariant.A:
|
| 211 |
+
t_value = 3 * con_min_dis_pairs / torch.sqrt(t_value_denominator_base / 2)
|
| 212 |
+
else:
|
| 213 |
+
m = n_total * (n_total - 1)
|
| 214 |
+
t_value_denominator: Tensor = (
|
| 215 |
+
t_value_denominator_base
|
| 216 |
+
- (preds_ties_p2 if preds_ties_p2 is not None else 0)
|
| 217 |
+
- (target_ties_p2 if target_ties_p2 is not None else 0)
|
| 218 |
+
) / 18
|
| 219 |
+
t_value_denominator += (
|
| 220 |
+
2 * (preds_ties if preds_ties is not None else 0) * (target_ties if target_ties is not None else 0)
|
| 221 |
+
) / m
|
| 222 |
+
t_value_denominator += (
|
| 223 |
+
(preds_ties_p1 if preds_ties_p1 is not None else 0)
|
| 224 |
+
* (target_ties_p1 if target_ties_p1 is not None else 0)
|
| 225 |
+
/ (9 * m * (n_total - 2))
|
| 226 |
+
)
|
| 227 |
+
t_value = con_min_dis_pairs / torch.sqrt(t_value_denominator)
|
| 228 |
+
|
| 229 |
+
if alternative == _TestAlternative.TWO_SIDED:
|
| 230 |
+
t_value = torch.abs(t_value)
|
| 231 |
+
if alternative in [_TestAlternative.TWO_SIDED, _TestAlternative.GREATER]:
|
| 232 |
+
t_value *= -1
|
| 233 |
+
p_value = _get_p_value_for_t_value_from_dist(t_value)
|
| 234 |
+
if alternative == _TestAlternative.TWO_SIDED:
|
| 235 |
+
p_value *= 2
|
| 236 |
+
return p_value
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _kendall_corrcoef_update(
|
| 240 |
+
preds: Tensor,
|
| 241 |
+
target: Tensor,
|
| 242 |
+
concat_preds: Optional[List[Tensor]] = None,
|
| 243 |
+
concat_target: Optional[List[Tensor]] = None,
|
| 244 |
+
num_outputs: int = 1,
|
| 245 |
+
) -> tuple[List[Tensor], List[Tensor]]:
|
| 246 |
+
"""Update variables required to compute Kendall rank correlation coefficient.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
preds: Sequence of data
|
| 250 |
+
target: Sequence of data
|
| 251 |
+
concat_preds: List of batches of preds sequence to be concatenated
|
| 252 |
+
concat_target: List of batches of target sequence to be concatenated
|
| 253 |
+
num_outputs: Number of outputs in multioutput setting
|
| 254 |
+
|
| 255 |
+
Raises:
|
| 256 |
+
RuntimeError: If ``preds`` and ``target`` do not have the same shape
|
| 257 |
+
|
| 258 |
+
"""
|
| 259 |
+
concat_preds = concat_preds or []
|
| 260 |
+
concat_target = concat_target or []
|
| 261 |
+
# Data checking
|
| 262 |
+
_check_same_shape(preds, target)
|
| 263 |
+
_check_data_shape_to_num_outputs(preds, target, num_outputs)
|
| 264 |
+
|
| 265 |
+
if num_outputs == 1:
|
| 266 |
+
preds = preds.unsqueeze(1)
|
| 267 |
+
target = target.unsqueeze(1)
|
| 268 |
+
|
| 269 |
+
concat_preds.append(preds)
|
| 270 |
+
concat_target.append(target)
|
| 271 |
+
|
| 272 |
+
return concat_preds, concat_target
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _kendall_corrcoef_compute(
|
| 276 |
+
preds: Tensor,
|
| 277 |
+
target: Tensor,
|
| 278 |
+
variant: _MetricVariant,
|
| 279 |
+
alternative: Optional[_TestAlternative] = None,
|
| 280 |
+
) -> tuple[Tensor, Optional[Tensor]]:
|
| 281 |
+
"""Compute Kendall rank correlation coefficient, and optionally p-value of corresponding statistical test.
|
| 282 |
+
|
| 283 |
+
Args:
|
| 284 |
+
Args:
|
| 285 |
+
preds: Sequence of data
|
| 286 |
+
target: Sequence of data
|
| 287 |
+
variant: Indication of which variant of Kendall's tau to be used
|
| 288 |
+
alternative: Alternative hypothesis for for t-test. Possible values:
|
| 289 |
+
- 'two-sided': the rank correlation is nonzero
|
| 290 |
+
- 'less': the rank correlation is negative (less than zero)
|
| 291 |
+
- 'greater': the rank correlation is positive (greater than zero)
|
| 292 |
+
|
| 293 |
+
"""
|
| 294 |
+
(
|
| 295 |
+
concordant_pairs,
|
| 296 |
+
discordant_pairs,
|
| 297 |
+
preds_ties,
|
| 298 |
+
preds_ties_p1,
|
| 299 |
+
preds_ties_p2,
|
| 300 |
+
target_ties,
|
| 301 |
+
target_ties_p1,
|
| 302 |
+
target_ties_p2,
|
| 303 |
+
n_total,
|
| 304 |
+
) = _get_metric_metadata(preds, target, variant)
|
| 305 |
+
con_min_dis_pairs = concordant_pairs - discordant_pairs
|
| 306 |
+
|
| 307 |
+
tau = _calculate_tau(
|
| 308 |
+
preds, target, concordant_pairs, discordant_pairs, con_min_dis_pairs, n_total, preds_ties, target_ties, variant
|
| 309 |
+
)
|
| 310 |
+
p_value = (
|
| 311 |
+
_calculate_p_value(
|
| 312 |
+
con_min_dis_pairs,
|
| 313 |
+
n_total,
|
| 314 |
+
preds_ties,
|
| 315 |
+
preds_ties_p1,
|
| 316 |
+
preds_ties_p2,
|
| 317 |
+
target_ties,
|
| 318 |
+
target_ties_p1,
|
| 319 |
+
target_ties_p2,
|
| 320 |
+
variant,
|
| 321 |
+
alternative,
|
| 322 |
+
)
|
| 323 |
+
if alternative
|
| 324 |
+
else None
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Squeeze tensor if num_outputs=1
|
| 328 |
+
if tau.shape[0] == 1:
|
| 329 |
+
tau = tau.squeeze()
|
| 330 |
+
p_value = p_value.squeeze() if p_value is not None else None
|
| 331 |
+
|
| 332 |
+
return tau.clamp(-1, 1), p_value
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def kendall_rank_corrcoef(
|
| 336 |
+
preds: Tensor,
|
| 337 |
+
target: Tensor,
|
| 338 |
+
variant: Literal["a", "b", "c"] = "b",
|
| 339 |
+
t_test: bool = False,
|
| 340 |
+
alternative: Optional[Literal["two-sided", "less", "greater"]] = "two-sided",
|
| 341 |
+
) -> Union[Tensor, tuple[Tensor, Tensor]]:
|
| 342 |
+
r"""Compute `Kendall Rank Correlation Coefficient`_.
|
| 343 |
+
|
| 344 |
+
.. math::
|
| 345 |
+
tau_a = \frac{C - D}{C + D}
|
| 346 |
+
|
| 347 |
+
where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs.
|
| 348 |
+
|
| 349 |
+
.. math::
|
| 350 |
+
tau_b = \frac{C - D}{\sqrt{(C + D + T_{preds}) * (C + D + T_{target})}}
|
| 351 |
+
|
| 352 |
+
where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs and :math:`T` represents
|
| 353 |
+
a total number of ties.
|
| 354 |
+
|
| 355 |
+
.. math::
|
| 356 |
+
tau_c = 2 * \frac{C - D}{n^2 * \frac{m - 1}{m}}
|
| 357 |
+
|
| 358 |
+
where :math:`C` represents concordant pairs, :math:`D` stands for discordant pairs, :math:`n` is a total number
|
| 359 |
+
of observations and :math:`m` is a ``min`` of unique values in ``preds`` and ``target`` sequence.
|
| 360 |
+
|
| 361 |
+
Definitions according to Definition according to `The Treatment of Ties in Ranking Problems`_.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
preds: Sequence of data of either shape ``(N,)`` or ``(N,d)``
|
| 365 |
+
target: Sequence of data of either shape ``(N,)`` or ``(N,d)``
|
| 366 |
+
variant: Indication of which variant of Kendall's tau to be used
|
| 367 |
+
t_test: Indication whether to run t-test
|
| 368 |
+
alternative: Alternative hypothesis for t-test. Possible values:
|
| 369 |
+
- 'two-sided': the rank correlation is nonzero
|
| 370 |
+
- 'less': the rank correlation is negative (less than zero)
|
| 371 |
+
- 'greater': the rank correlation is positive (greater than zero)
|
| 372 |
+
|
| 373 |
+
Return:
|
| 374 |
+
Correlation tau statistic
|
| 375 |
+
(Optional) p-value of corresponding statistical test (asymptotic)
|
| 376 |
+
|
| 377 |
+
Raises:
|
| 378 |
+
ValueError: If ``t_test`` is not of a type bool
|
| 379 |
+
ValueError: If ``t_test=True`` and ``alternative=None``
|
| 380 |
+
|
| 381 |
+
Example (single output regression):
|
| 382 |
+
>>> from torchmetrics.functional.regression import kendall_rank_corrcoef
|
| 383 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 384 |
+
>>> target = torch.tensor([3, -0.5, 2, 1])
|
| 385 |
+
>>> kendall_rank_corrcoef(preds, target)
|
| 386 |
+
tensor(0.3333)
|
| 387 |
+
|
| 388 |
+
Example (multi output regression):
|
| 389 |
+
>>> from torchmetrics.functional.regression import kendall_rank_corrcoef
|
| 390 |
+
>>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
|
| 391 |
+
>>> target = torch.tensor([[3, -0.5], [2, 1]])
|
| 392 |
+
>>> kendall_rank_corrcoef(preds, target)
|
| 393 |
+
tensor([1., 1.])
|
| 394 |
+
|
| 395 |
+
Example (single output regression with t-test)
|
| 396 |
+
>>> from torchmetrics.functional.regression import kendall_rank_corrcoef
|
| 397 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 398 |
+
>>> target = torch.tensor([3, -0.5, 2, 1])
|
| 399 |
+
>>> kendall_rank_corrcoef(preds, target, t_test=True, alternative='two-sided')
|
| 400 |
+
(tensor(0.3333), tensor(0.4969))
|
| 401 |
+
|
| 402 |
+
Example (multi output regression with t-test):
|
| 403 |
+
>>> from torchmetrics.functional.regression import kendall_rank_corrcoef
|
| 404 |
+
>>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
|
| 405 |
+
>>> target = torch.tensor([[3, -0.5], [2, 1]])
|
| 406 |
+
>>> kendall_rank_corrcoef(preds, target, t_test=True, alternative='two-sided')
|
| 407 |
+
(tensor([1., 1.]), tensor([nan, nan]))
|
| 408 |
+
|
| 409 |
+
"""
|
| 410 |
+
if not isinstance(t_test, bool):
|
| 411 |
+
raise ValueError(f"Argument `t_test` is expected to be of a type `bool`, but got {type(t_test)}.")
|
| 412 |
+
if t_test and alternative is None:
|
| 413 |
+
raise ValueError("Argument `alternative` is required if `t_test=True` but got `None`.")
|
| 414 |
+
|
| 415 |
+
_variant = _MetricVariant.from_str(str(variant))
|
| 416 |
+
_alternative = _TestAlternative.from_str(str(alternative)) if t_test else None
|
| 417 |
+
|
| 418 |
+
_preds, _target = _kendall_corrcoef_update(
|
| 419 |
+
preds, target, [], [], num_outputs=1 if preds.ndim == 1 else preds.shape[-1]
|
| 420 |
+
)
|
| 421 |
+
tau, p_value = _kendall_corrcoef_compute(
|
| 422 |
+
dim_zero_cat(_preds),
|
| 423 |
+
dim_zero_cat(_target),
|
| 424 |
+
_variant, # type: ignore[arg-type] # todo
|
| 425 |
+
_alternative, # type: ignore[arg-type] # todo
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
if p_value is not None:
|
| 429 |
+
return tau, p_value
|
| 430 |
+
return tau
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/kl_divergence.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from typing_extensions import Literal
|
| 20 |
+
|
| 21 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 22 |
+
from torchmetrics.utilities.compute import _safe_xlogy
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _kld_update(p: Tensor, q: Tensor, log_prob: bool) -> tuple[Tensor, int]:
|
| 26 |
+
"""Update and returns KL divergence scores for each observation and the total number of observations.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
p: data distribution with shape ``[N, d]``
|
| 30 |
+
q: prior or approximate distribution with shape ``[N, d]``
|
| 31 |
+
log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
|
| 32 |
+
will normalize to make sure the distributes sum to 1
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
_check_same_shape(p, q)
|
| 36 |
+
if p.ndim != 2 or q.ndim != 2:
|
| 37 |
+
raise ValueError(f"Expected both p and q distribution to be 2D but got {p.ndim} and {q.ndim} respectively")
|
| 38 |
+
|
| 39 |
+
total = p.shape[0]
|
| 40 |
+
if log_prob:
|
| 41 |
+
measures = torch.sum(p.exp() * (p - q), axis=-1) # type: ignore[call-overload]
|
| 42 |
+
else:
|
| 43 |
+
p = p / p.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
|
| 44 |
+
q = q / q.sum(axis=-1, keepdim=True) # type: ignore[call-overload]
|
| 45 |
+
measures = _safe_xlogy(p, p / q).sum(axis=-1) # type: ignore[call-overload]
|
| 46 |
+
|
| 47 |
+
return measures, total
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _kld_compute(
|
| 51 |
+
measures: Tensor, total: Union[int, Tensor], reduction: Literal["mean", "sum", "none", None] = "mean"
|
| 52 |
+
) -> Tensor:
|
| 53 |
+
"""Compute the KL divergenece based on the type of reduction.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
measures: Tensor of KL divergence scores for each observation
|
| 57 |
+
total: Number of observations
|
| 58 |
+
reduction:
|
| 59 |
+
Determines how to reduce over the ``N``/batch dimension:
|
| 60 |
+
|
| 61 |
+
- ``'mean'`` [default]: Averages score across samples
|
| 62 |
+
- ``'sum'``: Sum score across samples
|
| 63 |
+
- ``'none'`` or ``None``: Returns score per sample
|
| 64 |
+
|
| 65 |
+
Example:
|
| 66 |
+
>>> p = torch.tensor([[0.36, 0.48, 0.16]])
|
| 67 |
+
>>> q = torch.tensor([[1/3, 1/3, 1/3]])
|
| 68 |
+
>>> measures, total = _kld_update(p, q, log_prob=False)
|
| 69 |
+
>>> _kld_compute(measures, total)
|
| 70 |
+
tensor(0.0853)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
if reduction == "sum":
|
| 74 |
+
return measures.sum()
|
| 75 |
+
if reduction == "mean":
|
| 76 |
+
return measures.sum() / total
|
| 77 |
+
if reduction is None or reduction == "none":
|
| 78 |
+
return measures
|
| 79 |
+
return measures / total
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def kl_divergence(
|
| 83 |
+
p: Tensor, q: Tensor, log_prob: bool = False, reduction: Literal["mean", "sum", "none", None] = "mean"
|
| 84 |
+
) -> Tensor:
|
| 85 |
+
r"""Compute `KL divergence`_.
|
| 86 |
+
|
| 87 |
+
.. math::
|
| 88 |
+
D_{KL}(P||Q) = \sum_{x\in\mathcal{X}} P(x) \log\frac{P(x)}{Q{x}}
|
| 89 |
+
|
| 90 |
+
Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
|
| 91 |
+
over data and :math:`Q` is often a prior or approximation of :math:`P`. It should be noted that the KL divergence
|
| 92 |
+
is a non-symmetrical metric i.e. :math:`D_{KL}(P||Q) \neq D_{KL}(Q||P)`.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
p: data distribution with shape ``[N, d]``
|
| 96 |
+
q: prior or approximate distribution with shape ``[N, d]``
|
| 97 |
+
log_prob: bool indicating if input is log-probabilities or probabilities. If given as probabilities,
|
| 98 |
+
will normalize to make sure the distributes sum to 1
|
| 99 |
+
reduction:
|
| 100 |
+
Determines how to reduce over the ``N``/batch dimension:
|
| 101 |
+
|
| 102 |
+
- ``'mean'`` [default]: Averages score across samples
|
| 103 |
+
- ``'sum'``: Sum score across samples
|
| 104 |
+
- ``'none'`` or ``None``: Returns score per sample
|
| 105 |
+
|
| 106 |
+
Example:
|
| 107 |
+
>>> from torch import tensor
|
| 108 |
+
>>> p = tensor([[0.36, 0.48, 0.16]])
|
| 109 |
+
>>> q = tensor([[1/3, 1/3, 1/3]])
|
| 110 |
+
>>> kl_divergence(p, q)
|
| 111 |
+
tensor(0.0853)
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
measures, total = _kld_update(p, q, log_prob)
|
| 115 |
+
return _kld_compute(measures, total, reduction)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_cosh.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch import Tensor
|
| 17 |
+
|
| 18 |
+
from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _unsqueeze_tensors(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor]:
|
| 23 |
+
if preds.ndim == 2:
|
| 24 |
+
return preds, target
|
| 25 |
+
return preds.unsqueeze(1), target.unsqueeze(1)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _log_cosh_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, Tensor]:
|
| 29 |
+
"""Update and returns variables required to compute LogCosh error.
|
| 30 |
+
|
| 31 |
+
Check for same shape of input tensors.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
preds: Predicted tensor
|
| 35 |
+
target: Ground truth tensor
|
| 36 |
+
num_outputs: Number of outputs in multioutput setting
|
| 37 |
+
|
| 38 |
+
Return:
|
| 39 |
+
Sum of LogCosh error over examples, and total number of examples
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
_check_same_shape(preds, target)
|
| 43 |
+
_check_data_shape_to_num_outputs(preds, target, num_outputs)
|
| 44 |
+
|
| 45 |
+
preds, target = _unsqueeze_tensors(preds, target)
|
| 46 |
+
diff = preds - target
|
| 47 |
+
sum_log_cosh_error = torch.log((torch.exp(diff) + torch.exp(-diff)) / 2).sum(0).squeeze()
|
| 48 |
+
num_obs = torch.tensor(target.shape[0], device=preds.device)
|
| 49 |
+
return sum_log_cosh_error, num_obs
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _log_cosh_error_compute(sum_log_cosh_error: Tensor, num_obs: Tensor) -> Tensor:
|
| 53 |
+
"""Compute Mean Squared Error.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
sum_log_cosh_error: Sum of LogCosh errors over all observations
|
| 57 |
+
num_obs: Number of predictions or observations
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
return (sum_log_cosh_error / num_obs).squeeze()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def log_cosh_error(preds: Tensor, target: Tensor) -> Tensor:
|
| 64 |
+
r"""Compute the `LogCosh Error`_.
|
| 65 |
+
|
| 66 |
+
.. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right)
|
| 67 |
+
|
| 68 |
+
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
preds: estimated labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)``
|
| 72 |
+
target: ground truth labels with shape ``(batch_size,)`` or `(batch_size, num_outputs)``
|
| 73 |
+
|
| 74 |
+
Return:
|
| 75 |
+
Tensor with LogCosh error
|
| 76 |
+
|
| 77 |
+
Example (single output regression)::
|
| 78 |
+
>>> from torchmetrics.functional.regression import log_cosh_error
|
| 79 |
+
>>> preds = torch.tensor([3.0, 5.0, 2.5, 7.0])
|
| 80 |
+
>>> target = torch.tensor([2.5, 5.0, 4.0, 8.0])
|
| 81 |
+
>>> log_cosh_error(preds, target)
|
| 82 |
+
tensor(0.3523)
|
| 83 |
+
|
| 84 |
+
Example (multi output regression)::
|
| 85 |
+
>>> from torchmetrics.functional.regression import log_cosh_error
|
| 86 |
+
>>> preds = torch.tensor([[3.0, 5.0, 1.2], [-2.1, 2.5, 7.0]])
|
| 87 |
+
>>> target = torch.tensor([[2.5, 5.0, 1.3], [0.3, 4.0, 8.0]])
|
| 88 |
+
>>> log_cosh_error(preds, target)
|
| 89 |
+
tensor([0.9176, 0.4277, 0.2194])
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
sum_log_cosh_error, num_obs = _log_cosh_error_update(
|
| 93 |
+
preds, target, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]
|
| 94 |
+
)
|
| 95 |
+
return _log_cosh_error_compute(sum_log_cosh_error, num_obs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/log_mse.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _mean_squared_log_error_update(preds: Tensor, target: Tensor) -> tuple[Tensor, int]:
|
| 23 |
+
"""Return variables required to compute Mean Squared Log Error. Checks for same shape of tensors.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
preds: Predicted tensor
|
| 27 |
+
target: Ground truth tensor
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
_check_same_shape(preds, target)
|
| 31 |
+
sum_squared_log_error = torch.sum(torch.pow(torch.log1p(preds) - torch.log1p(target), 2))
|
| 32 |
+
return sum_squared_log_error, target.numel()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _mean_squared_log_error_compute(sum_squared_log_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor:
|
| 36 |
+
"""Compute Mean Squared Log Error.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
sum_squared_log_error:
|
| 40 |
+
Sum of square of log errors over all observations ``(log error = log(target) - log(prediction))``
|
| 41 |
+
num_obs: Number of predictions or observations
|
| 42 |
+
|
| 43 |
+
Example:
|
| 44 |
+
>>> preds = torch.tensor([0., 1, 2, 3])
|
| 45 |
+
>>> target = torch.tensor([0., 1, 2, 2])
|
| 46 |
+
>>> sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target)
|
| 47 |
+
>>> _mean_squared_log_error_compute(sum_squared_log_error, num_obs)
|
| 48 |
+
tensor(0.0207)
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
return sum_squared_log_error / num_obs
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def mean_squared_log_error(preds: Tensor, target: Tensor) -> Tensor:
|
| 55 |
+
"""Compute mean squared log error.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
preds: estimated labels
|
| 59 |
+
target: ground truth labels
|
| 60 |
+
|
| 61 |
+
Return:
|
| 62 |
+
Tensor with RMSLE
|
| 63 |
+
|
| 64 |
+
Example:
|
| 65 |
+
>>> from torchmetrics.functional.regression import mean_squared_log_error
|
| 66 |
+
>>> x = torch.tensor([0., 1, 2, 3])
|
| 67 |
+
>>> y = torch.tensor([0., 1, 2, 2])
|
| 68 |
+
>>> mean_squared_log_error(x, y)
|
| 69 |
+
tensor(0.0207)
|
| 70 |
+
|
| 71 |
+
.. attention::
|
| 72 |
+
Half precision is only support on GPU for this metric.
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target)
|
| 76 |
+
return _mean_squared_log_error_compute(sum_squared_log_error, num_obs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mae.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _mean_absolute_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, int]:
|
| 23 |
+
"""Update and returns variables required to compute Mean Absolute Error.
|
| 24 |
+
|
| 25 |
+
Check for same shape of input tensors.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
preds: Predicted tensor
|
| 29 |
+
target: Ground truth tensor
|
| 30 |
+
num_outputs: Number of outputs in multioutput setting
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
_check_same_shape(preds, target)
|
| 34 |
+
if num_outputs == 1:
|
| 35 |
+
preds = preds.view(-1)
|
| 36 |
+
target = target.view(-1)
|
| 37 |
+
preds = preds if preds.is_floating_point else preds.float() # type: ignore[truthy-function] # todo
|
| 38 |
+
target = target if target.is_floating_point else target.float() # type: ignore[truthy-function] # todo
|
| 39 |
+
sum_abs_error = torch.sum(torch.abs(preds - target), dim=0)
|
| 40 |
+
return sum_abs_error, target.shape[0]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _mean_absolute_error_compute(sum_abs_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor:
|
| 44 |
+
"""Compute Mean Absolute Error.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
sum_abs_error: Sum of absolute value of errors over all observations
|
| 48 |
+
num_obs: Number of predictions or observations
|
| 49 |
+
|
| 50 |
+
Example:
|
| 51 |
+
>>> preds = torch.tensor([0., 1, 2, 3])
|
| 52 |
+
>>> target = torch.tensor([0., 1, 2, 2])
|
| 53 |
+
>>> sum_abs_error, num_obs = _mean_absolute_error_update(preds, target, num_outputs=1)
|
| 54 |
+
>>> _mean_absolute_error_compute(sum_abs_error, num_obs)
|
| 55 |
+
tensor(0.2500)
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
return sum_abs_error / num_obs
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def mean_absolute_error(preds: Tensor, target: Tensor, num_outputs: int = 1) -> Tensor:
|
| 62 |
+
"""Compute mean absolute error.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
preds: estimated labels
|
| 66 |
+
target: ground truth labels
|
| 67 |
+
num_outputs: Number of outputs in multioutput setting
|
| 68 |
+
|
| 69 |
+
Return:
|
| 70 |
+
Tensor with MAE
|
| 71 |
+
|
| 72 |
+
Example:
|
| 73 |
+
>>> from torchmetrics.functional.regression import mean_absolute_error
|
| 74 |
+
>>> x = torch.tensor([0., 1, 2, 3])
|
| 75 |
+
>>> y = torch.tensor([0., 1, 2, 2])
|
| 76 |
+
>>> mean_absolute_error(x, y)
|
| 77 |
+
tensor(0.2500)
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
sum_abs_error, num_obs = _mean_absolute_error_update(preds, target, num_outputs=num_outputs)
|
| 81 |
+
return _mean_absolute_error_compute(sum_abs_error, num_obs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mape.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _mean_absolute_percentage_error_update(
|
| 23 |
+
preds: Tensor,
|
| 24 |
+
target: Tensor,
|
| 25 |
+
epsilon: float = 1.17e-06,
|
| 26 |
+
) -> tuple[Tensor, int]:
|
| 27 |
+
"""Update and returns variables required to compute Mean Percentage Error.
|
| 28 |
+
|
| 29 |
+
Check for same shape of input tensors.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
preds: Predicted tensor
|
| 33 |
+
target: Ground truth tensor
|
| 34 |
+
epsilon: Specifies the lower bound for target values. Any target value below epsilon
|
| 35 |
+
is set to epsilon (avoids ``ZeroDivisionError``).
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
_check_same_shape(preds, target)
|
| 39 |
+
|
| 40 |
+
abs_diff = torch.abs(preds - target)
|
| 41 |
+
abs_per_error = abs_diff / torch.clamp(torch.abs(target), min=epsilon)
|
| 42 |
+
|
| 43 |
+
sum_abs_per_error = torch.sum(abs_per_error)
|
| 44 |
+
|
| 45 |
+
num_obs = target.numel()
|
| 46 |
+
|
| 47 |
+
return sum_abs_per_error, num_obs
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _mean_absolute_percentage_error_compute(sum_abs_per_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor:
|
| 51 |
+
"""Compute Mean Absolute Percentage Error.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
sum_abs_per_error: Sum of absolute value of percentage errors over all observations
|
| 55 |
+
``(percentage error = (target - prediction) / target)``
|
| 56 |
+
num_obs: Number of predictions or observations
|
| 57 |
+
|
| 58 |
+
Example:
|
| 59 |
+
>>> target = torch.tensor([1, 10, 1e6])
|
| 60 |
+
>>> preds = torch.tensor([0.9, 15, 1.2e6])
|
| 61 |
+
>>> sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target)
|
| 62 |
+
>>> _mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs)
|
| 63 |
+
tensor(0.2667)
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
return sum_abs_per_error / num_obs
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Tensor:
|
| 70 |
+
"""Compute mean absolute percentage error.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
preds: estimated labels
|
| 74 |
+
target: ground truth labels
|
| 75 |
+
|
| 76 |
+
Return:
|
| 77 |
+
Tensor with MAPE
|
| 78 |
+
|
| 79 |
+
Note:
|
| 80 |
+
The epsilon value is taken from `scikit-learn's implementation of MAPE`_.
|
| 81 |
+
|
| 82 |
+
Example:
|
| 83 |
+
>>> from torchmetrics.functional.regression import mean_absolute_percentage_error
|
| 84 |
+
>>> target = torch.tensor([1, 10, 1e6])
|
| 85 |
+
>>> preds = torch.tensor([0.9, 15, 1.2e6])
|
| 86 |
+
>>> mean_absolute_percentage_error(preds, target)
|
| 87 |
+
tensor(0.2667)
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target)
|
| 91 |
+
return _mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/minkowski.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The PyTorch Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
|
| 17 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 18 |
+
from torchmetrics.utilities.exceptions import TorchMetricsUserError
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _minkowski_distance_update(preds: Tensor, targets: Tensor, p: float) -> Tensor:
|
| 22 |
+
"""Update and return variables required to compute Minkowski distance.
|
| 23 |
+
|
| 24 |
+
Checks for same shape of input tensors.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
preds: Predicted tensor
|
| 28 |
+
targets: Ground truth tensor
|
| 29 |
+
p: Non-negative number acting as the p to the errors
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
_check_same_shape(preds, targets)
|
| 33 |
+
|
| 34 |
+
if not (isinstance(p, (float, int)) and p >= 1):
|
| 35 |
+
raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {p}")
|
| 36 |
+
|
| 37 |
+
difference = torch.abs(preds - targets)
|
| 38 |
+
return torch.sum(torch.pow(difference, p))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _minkowski_distance_compute(distance: Tensor, p: float) -> Tensor:
|
| 42 |
+
"""Compute Minkowski Distance.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
distance: Sum of the p-th powers of errors over all observations
|
| 46 |
+
p: The non-negative numeric power the errors are to be raised to
|
| 47 |
+
|
| 48 |
+
Example:
|
| 49 |
+
>>> preds = torch.tensor([0., 1, 2, 3])
|
| 50 |
+
>>> target = torch.tensor([0., 2, 3, 1])
|
| 51 |
+
>>> distance_p_sum = _minkowski_distance_update(preds, target, 5)
|
| 52 |
+
>>> _minkowski_distance_compute(distance_p_sum, 5)
|
| 53 |
+
tensor(2.0244)
|
| 54 |
+
|
| 55 |
+
"""
|
| 56 |
+
return torch.pow(distance, 1.0 / p)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def minkowski_distance(preds: Tensor, targets: Tensor, p: float) -> Tensor:
|
| 60 |
+
r"""Compute the `Minkowski distance`_.
|
| 61 |
+
|
| 62 |
+
.. math:: d_{\text{Minkowski}} = \\sum_{i}^N (| y_i - \\hat{y_i} |^p)^\frac{1}{p}
|
| 63 |
+
|
| 64 |
+
This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski
|
| 65 |
+
distance with p=2.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
preds: estimated labels of type Tensor
|
| 69 |
+
targets: ground truth labels of type Tensor
|
| 70 |
+
p: int or float larger than 1, exponent to which the difference between preds and target is to be raised
|
| 71 |
+
|
| 72 |
+
Return:
|
| 73 |
+
Tensor with the Minkowski distance
|
| 74 |
+
|
| 75 |
+
Example:
|
| 76 |
+
>>> from torchmetrics.functional.regression import minkowski_distance
|
| 77 |
+
>>> x = torch.tensor([1.0, 2.8, 3.5, 4.5])
|
| 78 |
+
>>> y = torch.tensor([6.1, 2.11, 3.1, 5.6])
|
| 79 |
+
>>> minkowski_distance(x, y, p=3)
|
| 80 |
+
tensor(5.1220)
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
minkowski_dist_sum = _minkowski_distance_update(preds, targets, p)
|
| 84 |
+
return _minkowski_distance_compute(minkowski_dist_sum, p)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/mse.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _mean_squared_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> tuple[Tensor, int]:
|
| 23 |
+
"""Update and returns variables required to compute Mean Squared Error.
|
| 24 |
+
|
| 25 |
+
Check for same shape of input tensors.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
preds: Predicted tensor
|
| 29 |
+
target: Ground truth tensor
|
| 30 |
+
num_outputs: Number of outputs in multioutput setting
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
_check_same_shape(preds, target)
|
| 34 |
+
if num_outputs == 1:
|
| 35 |
+
preds = preds.view(-1)
|
| 36 |
+
target = target.view(-1)
|
| 37 |
+
diff = preds - target
|
| 38 |
+
sum_squared_error = torch.sum(diff * diff, dim=0)
|
| 39 |
+
return sum_squared_error, target.shape[0]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _mean_squared_error_compute(sum_squared_error: Tensor, num_obs: Union[int, Tensor], squared: bool = True) -> Tensor:
|
| 43 |
+
"""Compute Mean Squared Error.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
sum_squared_error: Sum of square of errors over all observations
|
| 47 |
+
num_obs: Number of predictions or observations
|
| 48 |
+
squared: Returns RMSE value if set to False.
|
| 49 |
+
|
| 50 |
+
Example:
|
| 51 |
+
>>> preds = torch.tensor([0., 1, 2, 3])
|
| 52 |
+
>>> target = torch.tensor([0., 1, 2, 2])
|
| 53 |
+
>>> sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=1)
|
| 54 |
+
>>> _mean_squared_error_compute(sum_squared_error, num_obs)
|
| 55 |
+
tensor(0.2500)
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
return sum_squared_error / num_obs if squared else torch.sqrt(sum_squared_error / num_obs)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def mean_squared_error(preds: Tensor, target: Tensor, squared: bool = True, num_outputs: int = 1) -> Tensor:
|
| 62 |
+
"""Compute mean squared error.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
preds: estimated labels
|
| 66 |
+
target: ground truth labels
|
| 67 |
+
squared: returns RMSE value if set to False
|
| 68 |
+
num_outputs: Number of outputs in multioutput setting
|
| 69 |
+
|
| 70 |
+
Return:
|
| 71 |
+
Tensor with MSE
|
| 72 |
+
|
| 73 |
+
Example:
|
| 74 |
+
>>> from torchmetrics.functional.regression import mean_squared_error
|
| 75 |
+
>>> x = torch.tensor([0., 1, 2, 3])
|
| 76 |
+
>>> y = torch.tensor([0., 1, 2, 2])
|
| 77 |
+
>>> mean_squared_error(x, y)
|
| 78 |
+
tensor(0.2500)
|
| 79 |
+
|
| 80 |
+
"""
|
| 81 |
+
sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=num_outputs)
|
| 82 |
+
return _mean_squared_error_compute(sum_squared_error, num_obs, squared=squared)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/nrmse.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
from typing_extensions import Literal
|
| 19 |
+
|
| 20 |
+
from torchmetrics.functional.regression.mse import _mean_squared_error_update
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _normalized_root_mean_squared_error_update(
|
| 24 |
+
preds: Tensor, target: Tensor, num_outputs: int, normalization: Literal["mean", "range", "std", "l2"] = "mean"
|
| 25 |
+
) -> tuple[Tensor, int, Tensor]:
|
| 26 |
+
"""Updates and returns the sum of squared errors and the number of observations for NRMSE computation.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
preds: Predicted tensor
|
| 30 |
+
target: Ground truth tensor
|
| 31 |
+
num_outputs: Number of outputs in multioutput setting
|
| 32 |
+
normalization: type of normalization to be applied. Choose from "mean", "range", "std", "l2"
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs)
|
| 36 |
+
|
| 37 |
+
target = target.view(-1) if num_outputs == 1 else target
|
| 38 |
+
if normalization == "mean":
|
| 39 |
+
denom = torch.mean(target, dim=0)
|
| 40 |
+
elif normalization == "range":
|
| 41 |
+
denom = torch.max(target, dim=0).values - torch.min(target, dim=0).values
|
| 42 |
+
elif normalization == "std":
|
| 43 |
+
denom = torch.std(target, correction=0, dim=0)
|
| 44 |
+
elif normalization == "l2":
|
| 45 |
+
denom = torch.norm(target, p=2, dim=0)
|
| 46 |
+
else:
|
| 47 |
+
raise ValueError(
|
| 48 |
+
f"Argument `normalization` should be either 'mean', 'range', 'std' or 'l2' but got {normalization}"
|
| 49 |
+
)
|
| 50 |
+
return sum_squared_error, num_obs, denom
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _normalized_root_mean_squared_error_compute(
|
| 54 |
+
sum_squared_error: Tensor, num_obs: Union[int, Tensor], denom: Tensor
|
| 55 |
+
) -> Tensor:
|
| 56 |
+
"""Calculates RMSE and normalizes it."""
|
| 57 |
+
rmse = torch.sqrt(sum_squared_error / num_obs)
|
| 58 |
+
return rmse / denom
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def normalized_root_mean_squared_error(
|
| 62 |
+
preds: Tensor,
|
| 63 |
+
target: Tensor,
|
| 64 |
+
normalization: Literal["mean", "range", "std", "l2"] = "mean",
|
| 65 |
+
num_outputs: int = 1,
|
| 66 |
+
) -> Tensor:
|
| 67 |
+
"""Calculates the `Normalized Root Mean Squared Error`_ (NRMSE) also know as scatter index.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
preds: estimated labels
|
| 71 |
+
target: ground truth labels
|
| 72 |
+
normalization: type of normalization to be applied. Choose from "mean", "range", "std", "l2" which corresponds
|
| 73 |
+
to normalizing the RMSE by the mean of the target, the range of the target, the standard deviation of the
|
| 74 |
+
target or the L2 norm of the target.
|
| 75 |
+
num_outputs: Number of outputs in multioutput setting
|
| 76 |
+
|
| 77 |
+
Return:
|
| 78 |
+
Tensor with the NRMSE score
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
>>> import torch
|
| 82 |
+
>>> from torchmetrics.functional.regression import normalized_root_mean_squared_error
|
| 83 |
+
>>> preds = torch.tensor([0., 1, 2, 3])
|
| 84 |
+
>>> target = torch.tensor([0., 1, 2, 2])
|
| 85 |
+
>>> normalized_root_mean_squared_error(preds, target, normalization="mean")
|
| 86 |
+
tensor(0.4000)
|
| 87 |
+
>>> normalized_root_mean_squared_error(preds, target, normalization="range")
|
| 88 |
+
tensor(0.2500)
|
| 89 |
+
>>> normalized_root_mean_squared_error(preds, target, normalization="std")
|
| 90 |
+
tensor(0.6030)
|
| 91 |
+
>>> normalized_root_mean_squared_error(preds, target, normalization="l2")
|
| 92 |
+
tensor(0.1667)
|
| 93 |
+
|
| 94 |
+
Example (multioutput):
|
| 95 |
+
>>> import torch
|
| 96 |
+
>>> from torchmetrics.functional.regression import normalized_root_mean_squared_error
|
| 97 |
+
>>> preds = torch.tensor([[0., 1], [2, 3], [4, 5], [6, 7]])
|
| 98 |
+
>>> target = torch.tensor([[0., 1], [3, 3], [4, 5], [8, 9]])
|
| 99 |
+
>>> normalized_root_mean_squared_error(preds, target, normalization="mean", num_outputs=2)
|
| 100 |
+
tensor([0.2981, 0.2222])
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
sum_squared_error, num_obs, denom = _normalized_root_mean_squared_error_update(
|
| 104 |
+
preds, target, num_outputs=num_outputs, normalization=normalization
|
| 105 |
+
)
|
| 106 |
+
return _normalized_root_mean_squared_error_compute(sum_squared_error, num_obs, denom)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/pearson.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs
|
| 20 |
+
from torchmetrics.utilities import rank_zero_warn
|
| 21 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _pearson_corrcoef_update(
|
| 25 |
+
preds: Tensor,
|
| 26 |
+
target: Tensor,
|
| 27 |
+
mean_x: Tensor,
|
| 28 |
+
mean_y: Tensor,
|
| 29 |
+
max_abs_dev_x: Tensor,
|
| 30 |
+
max_abs_dev_y: Tensor,
|
| 31 |
+
var_x: Tensor,
|
| 32 |
+
var_y: Tensor,
|
| 33 |
+
corr_xy: Tensor,
|
| 34 |
+
num_prior: Tensor,
|
| 35 |
+
num_outputs: int,
|
| 36 |
+
) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
|
| 37 |
+
"""Update and returns variables required to compute Pearson Correlation Coefficient.
|
| 38 |
+
|
| 39 |
+
Check for same shape of input tensors.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
preds: estimated scores
|
| 43 |
+
target: ground truth scores
|
| 44 |
+
mean_x: current mean estimate of x tensor
|
| 45 |
+
mean_y: current mean estimate of y tensor
|
| 46 |
+
max_abs_dev_x: current maximum absolute value of x tensor
|
| 47 |
+
max_abs_dev_y: current maximum absolute value of y tensor
|
| 48 |
+
var_x: current variance estimate of x tensor
|
| 49 |
+
var_y: current variance estimate of y tensor
|
| 50 |
+
corr_xy: current covariance estimate between x and y tensor
|
| 51 |
+
num_prior: current number of observed observations
|
| 52 |
+
num_outputs: Number of outputs in multioutput setting
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
# Data checking
|
| 56 |
+
_check_same_shape(preds, target)
|
| 57 |
+
_check_data_shape_to_num_outputs(preds, target, num_outputs)
|
| 58 |
+
num_obs = preds.shape[0]
|
| 59 |
+
|
| 60 |
+
batch_mean_x = preds.mean(0)
|
| 61 |
+
batch_mean_y = target.mean(0)
|
| 62 |
+
delta_x = batch_mean_x - mean_x
|
| 63 |
+
delta_y = batch_mean_y - mean_y
|
| 64 |
+
n_total = num_prior + num_obs
|
| 65 |
+
mx_new = mean_x + delta_x * num_obs / n_total
|
| 66 |
+
my_new = mean_y + delta_y * num_obs / n_total
|
| 67 |
+
if num_obs == 1:
|
| 68 |
+
delta2_x = batch_mean_x - mx_new
|
| 69 |
+
delta2_y = batch_mean_y - my_new
|
| 70 |
+
var_x = var_x + delta2_x * delta_x
|
| 71 |
+
var_y = var_y + delta2_y * delta_y
|
| 72 |
+
corr_xy = corr_xy + delta_x * delta2_y
|
| 73 |
+
else:
|
| 74 |
+
preds_centered = preds - batch_mean_x
|
| 75 |
+
target_centered = target - batch_mean_y
|
| 76 |
+
|
| 77 |
+
batch_var_x = (preds_centered**2).sum(0)
|
| 78 |
+
batch_var_y = (target_centered**2).sum(0)
|
| 79 |
+
batch_cov_xy = (preds_centered * target_centered).sum(0)
|
| 80 |
+
|
| 81 |
+
correction = num_prior * num_obs / n_total
|
| 82 |
+
var_x = var_x + batch_var_x + delta_x**2 * correction
|
| 83 |
+
var_y = var_y + batch_var_y + delta_y**2 * correction
|
| 84 |
+
|
| 85 |
+
corr_xy = corr_xy + batch_cov_xy + delta_x * delta_y * correction
|
| 86 |
+
max_abs_dev_x = torch.maximum(max_abs_dev_x, torch.max((preds - mx_new).abs(), dim=0)[0])
|
| 87 |
+
max_abs_dev_y = torch.maximum(max_abs_dev_y, torch.max((target - my_new).abs(), dim=0)[0])
|
| 88 |
+
return mx_new, my_new, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, n_total
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _pearson_corrcoef_compute(
|
| 92 |
+
max_abs_dev_x: Tensor,
|
| 93 |
+
max_abs_dev_y: Tensor,
|
| 94 |
+
var_x: Tensor,
|
| 95 |
+
var_y: Tensor,
|
| 96 |
+
corr_xy: Tensor,
|
| 97 |
+
nb: Tensor,
|
| 98 |
+
) -> Tensor:
|
| 99 |
+
"""Compute the final pearson correlation based on accumulated statistics.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
max_abs_dev_x: maximum absolute value of x tensor
|
| 103 |
+
max_abs_dev_y: maximum absolute value of y tensor
|
| 104 |
+
var_x: variance estimate of x tensor
|
| 105 |
+
var_y: variance estimate of y tensor
|
| 106 |
+
corr_xy: covariance estimate between x and y tensor
|
| 107 |
+
nb: number of observations
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
# prevent overwrite the inputs
|
| 111 |
+
var_x = var_x / (nb - 1)
|
| 112 |
+
var_y = var_y / (nb - 1)
|
| 113 |
+
corr_xy = corr_xy / (nb - 1)
|
| 114 |
+
# if var_x, var_y is float16 and on cpu, make it bfloat16 as sqrt is not supported for float16
|
| 115 |
+
# on cpu, remove this after https://github.com/pytorch/pytorch/issues/54774 is fixed
|
| 116 |
+
if var_x.dtype == torch.float16 and var_x.device == torch.device("cpu"):
|
| 117 |
+
var_x = var_x.bfloat16()
|
| 118 |
+
var_y = var_y.bfloat16()
|
| 119 |
+
var_x = var_x * torch.pow(max_abs_dev_x, -2)
|
| 120 |
+
var_y = var_y * torch.pow(max_abs_dev_y, -2)
|
| 121 |
+
corr_xy = corr_xy / (max_abs_dev_x * max_abs_dev_y)
|
| 122 |
+
bound = math.sqrt(torch.finfo(var_x.dtype).eps)
|
| 123 |
+
if (
|
| 124 |
+
(var_x < bound).any()
|
| 125 |
+
or (var_y < bound).any()
|
| 126 |
+
or ~torch.isfinite(var_x).any()
|
| 127 |
+
or ~torch.isfinite(var_y).any()
|
| 128 |
+
or ~torch.isfinite(corr_xy).any()
|
| 129 |
+
):
|
| 130 |
+
rank_zero_warn(
|
| 131 |
+
"The variance of predictions or target is close to zero. This can cause instability in Pearson correlation"
|
| 132 |
+
"coefficient, leading to wrong results. Consider re-scaling the input if possible or computing using a"
|
| 133 |
+
f"larger dtype (currently using {var_x.dtype}). Setting the correlation coefficient to nan.",
|
| 134 |
+
UserWarning,
|
| 135 |
+
)
|
| 136 |
+
zero_var_mask = (
|
| 137 |
+
(var_x < bound) | (var_y < bound) | ~torch.isfinite(var_x) | ~torch.isfinite(var_y) | ~torch.isfinite(corr_xy)
|
| 138 |
+
)
|
| 139 |
+
corrcoef = torch.full_like(corr_xy, float("nan"), device=corr_xy.device, dtype=corr_xy.dtype)
|
| 140 |
+
valid_mask = ~zero_var_mask
|
| 141 |
+
if valid_mask.any():
|
| 142 |
+
corrcoef[valid_mask] = (
|
| 143 |
+
(corr_xy[valid_mask] / (var_x[valid_mask] * var_y[valid_mask]).sqrt()).squeeze().to(corrcoef.dtype)
|
| 144 |
+
)
|
| 145 |
+
corrcoef = torch.clamp(corrcoef, -1.0, 1.0)
|
| 146 |
+
return corrcoef.squeeze()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor:
|
| 150 |
+
"""Compute pearson correlation coefficient.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
preds: estimated scores
|
| 154 |
+
target: ground truth scores
|
| 155 |
+
|
| 156 |
+
Example (single output regression):
|
| 157 |
+
>>> from torchmetrics.functional.regression import pearson_corrcoef
|
| 158 |
+
>>> target = torch.tensor([3, -0.5, 2, 7])
|
| 159 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 160 |
+
>>> pearson_corrcoef(preds, target)
|
| 161 |
+
tensor(0.9849)
|
| 162 |
+
|
| 163 |
+
Example (multi output regression):
|
| 164 |
+
>>> from torchmetrics.functional.regression import pearson_corrcoef
|
| 165 |
+
>>> target = torch.tensor([[3, -0.5], [2, 7]])
|
| 166 |
+
>>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
|
| 167 |
+
>>> pearson_corrcoef(preds, target)
|
| 168 |
+
tensor([1., 1.])
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
d = preds.shape[1] if preds.ndim == 2 else 1
|
| 172 |
+
_temp = torch.zeros(d, dtype=preds.dtype, device=preds.device)
|
| 173 |
+
mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone()
|
| 174 |
+
var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone()
|
| 175 |
+
max_abs_dev_x, max_abs_dev_y = _temp.clone(), _temp.clone()
|
| 176 |
+
_, _, max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update(
|
| 177 |
+
preds=preds,
|
| 178 |
+
target=target,
|
| 179 |
+
mean_x=mean_x,
|
| 180 |
+
mean_y=mean_y,
|
| 181 |
+
max_abs_dev_x=max_abs_dev_x,
|
| 182 |
+
max_abs_dev_y=max_abs_dev_y,
|
| 183 |
+
var_x=var_x,
|
| 184 |
+
var_y=var_y,
|
| 185 |
+
corr_xy=corr_xy,
|
| 186 |
+
num_prior=nb,
|
| 187 |
+
num_outputs=1 if preds.ndim == 1 else preds.shape[-1],
|
| 188 |
+
)
|
| 189 |
+
return _pearson_corrcoef_compute(max_abs_dev_x, max_abs_dev_y, var_x, var_y, corr_xy, nb)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/r2.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.utilities import rank_zero_warn
|
| 20 |
+
from torchmetrics.utilities.checks import _check_same_shape
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _r2_score_update(preds: Tensor, target: Tensor) -> tuple[Tensor, Tensor, Tensor, int]:
|
| 24 |
+
"""Update and returns variables required to compute R2 score.
|
| 25 |
+
|
| 26 |
+
Check for same shape and 1D/2D input tensors.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
preds: Predicted tensor
|
| 30 |
+
target: Ground truth tensor
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
_check_same_shape(preds, target)
|
| 34 |
+
if preds.ndim > 2:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
"Expected both prediction and target to be 1D or 2D tensors,"
|
| 37 |
+
f" but received tensors with dimension {preds.shape}"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
sum_obs = torch.sum(target, dim=0)
|
| 41 |
+
sum_squared_obs = torch.sum(target * target, dim=0)
|
| 42 |
+
residual = target - preds
|
| 43 |
+
rss = torch.sum(residual * residual, dim=0)
|
| 44 |
+
return sum_squared_obs, sum_obs, rss, target.size(0)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _r2_score_compute(
|
| 48 |
+
sum_squared_obs: Tensor,
|
| 49 |
+
sum_obs: Tensor,
|
| 50 |
+
rss: Tensor,
|
| 51 |
+
num_obs: Union[int, Tensor],
|
| 52 |
+
adjusted: int = 0,
|
| 53 |
+
multioutput: str = "uniform_average",
|
| 54 |
+
) -> Tensor:
|
| 55 |
+
"""Compute R2 score.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
sum_squared_obs: Sum of square of all observations
|
| 59 |
+
sum_obs: Sum of all observations
|
| 60 |
+
rss: Residual sum of squares
|
| 61 |
+
num_obs: Number of predictions or observations
|
| 62 |
+
adjusted: number of independent regressors for calculating adjusted r2 score.
|
| 63 |
+
multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings:
|
| 64 |
+
|
| 65 |
+
* `'raw_values'` returns full set of scores
|
| 66 |
+
* `'uniform_average'` scores are uniformly averaged
|
| 67 |
+
* `'variance_weighted'` scores are weighted by their individual variances
|
| 68 |
+
|
| 69 |
+
Example:
|
| 70 |
+
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
|
| 71 |
+
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
|
| 72 |
+
>>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
|
| 73 |
+
>>> _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, multioutput="raw_values")
|
| 74 |
+
tensor([0.9654, 0.9082])
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
if num_obs < 2:
|
| 78 |
+
raise ValueError("Needs at least two samples to calculate r2 score.")
|
| 79 |
+
|
| 80 |
+
mean_obs = sum_obs / num_obs
|
| 81 |
+
tss = sum_squared_obs - sum_obs * mean_obs
|
| 82 |
+
|
| 83 |
+
# Account for near constant targets
|
| 84 |
+
cond_rss = ~torch.isclose(rss, torch.zeros_like(rss), atol=1e-4)
|
| 85 |
+
cond_tss = ~torch.isclose(tss, torch.zeros_like(tss), atol=1e-4)
|
| 86 |
+
cond = cond_rss & cond_tss
|
| 87 |
+
|
| 88 |
+
raw_scores = torch.ones_like(rss)
|
| 89 |
+
raw_scores[cond] = 1 - (rss[cond] / tss[cond])
|
| 90 |
+
raw_scores[cond_rss & ~cond_tss] = 0.0
|
| 91 |
+
|
| 92 |
+
if multioutput == "raw_values":
|
| 93 |
+
r2 = raw_scores
|
| 94 |
+
elif multioutput == "uniform_average":
|
| 95 |
+
r2 = torch.mean(raw_scores)
|
| 96 |
+
elif multioutput == "variance_weighted":
|
| 97 |
+
tss_sum = torch.sum(tss)
|
| 98 |
+
r2 = torch.sum(tss / tss_sum * raw_scores)
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"Argument `multioutput` must be either `raw_values`,"
|
| 102 |
+
f" `uniform_average` or `variance_weighted`. Received {multioutput}."
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if adjusted < 0 or not isinstance(adjusted, int):
|
| 106 |
+
raise ValueError("`adjusted` parameter should be an integer larger or equal to 0.")
|
| 107 |
+
|
| 108 |
+
if adjusted != 0:
|
| 109 |
+
if adjusted > num_obs - 1:
|
| 110 |
+
rank_zero_warn(
|
| 111 |
+
"More independent regressions than data points in adjusted r2 score. Falls back to standard r2 score.",
|
| 112 |
+
UserWarning,
|
| 113 |
+
)
|
| 114 |
+
elif adjusted == num_obs - 1:
|
| 115 |
+
rank_zero_warn("Division by zero in adjusted r2 score. Falls back to standard r2 score.", UserWarning)
|
| 116 |
+
else:
|
| 117 |
+
return 1 - (1 - r2) * (num_obs - 1) / (num_obs - adjusted - 1)
|
| 118 |
+
return r2
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def r2_score(
|
| 122 |
+
preds: Tensor,
|
| 123 |
+
target: Tensor,
|
| 124 |
+
adjusted: int = 0,
|
| 125 |
+
multioutput: str = "uniform_average",
|
| 126 |
+
) -> Tensor:
|
| 127 |
+
r"""Compute r2 score also known as `R2 Score_Coefficient Determination`_.
|
| 128 |
+
|
| 129 |
+
.. math:: R^2 = 1 - \frac{SS_{res}}{SS_{tot}}
|
| 130 |
+
|
| 131 |
+
where :math:`SS_{res}=\sum_i (y_i - f(x_i))^2` is the sum of residual squares, and
|
| 132 |
+
:math:`SS_{tot}=\sum_i (y_i - \bar{y})^2` is total sum of squares. Can also calculate
|
| 133 |
+
adjusted r2 score given by
|
| 134 |
+
|
| 135 |
+
.. math:: R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1}
|
| 136 |
+
|
| 137 |
+
where the parameter :math:`k` (the number of independent regressors) should
|
| 138 |
+
be provided as the ``adjusted`` argument.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
preds: estimated labels
|
| 142 |
+
target: ground truth labels
|
| 143 |
+
adjusted: number of independent regressors for calculating adjusted r2 score.
|
| 144 |
+
multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings:
|
| 145 |
+
|
| 146 |
+
* ``'raw_values'`` returns full set of scores
|
| 147 |
+
* ``'uniform_average'`` scores are uniformly averaged
|
| 148 |
+
* ``'variance_weighted'`` scores are weighted by their individual variances
|
| 149 |
+
|
| 150 |
+
Raises:
|
| 151 |
+
ValueError:
|
| 152 |
+
If both ``preds`` and ``targets`` are not ``1D`` or ``2D`` tensors.
|
| 153 |
+
ValueError:
|
| 154 |
+
If ``len(preds)`` is less than ``2`` since at least ``2`` samples are needed to calculate r2 score.
|
| 155 |
+
ValueError:
|
| 156 |
+
If ``multioutput`` is not one of ``raw_values``, ``uniform_average`` or ``variance_weighted``.
|
| 157 |
+
ValueError:
|
| 158 |
+
If ``adjusted`` is not an ``integer`` greater than ``0``.
|
| 159 |
+
|
| 160 |
+
Example:
|
| 161 |
+
>>> from torchmetrics.functional.regression import r2_score
|
| 162 |
+
>>> target = torch.tensor([3, -0.5, 2, 7])
|
| 163 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 164 |
+
>>> r2_score(preds, target)
|
| 165 |
+
tensor(0.9486)
|
| 166 |
+
|
| 167 |
+
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
|
| 168 |
+
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
|
| 169 |
+
>>> r2_score(preds, target, multioutput='raw_values')
|
| 170 |
+
tensor([0.9654, 0.9082])
|
| 171 |
+
|
| 172 |
+
"""
|
| 173 |
+
sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
|
| 174 |
+
return _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, adjusted, multioutput)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torchmetrics/functional/regression/rse.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright The Lightning team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
from torchmetrics.functional.regression.r2 import _r2_score_update
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _relative_squared_error_compute(
|
| 23 |
+
sum_squared_obs: Tensor,
|
| 24 |
+
sum_obs: Tensor,
|
| 25 |
+
sum_squared_error: Tensor,
|
| 26 |
+
num_obs: Union[int, Tensor],
|
| 27 |
+
squared: bool = True,
|
| 28 |
+
) -> Tensor:
|
| 29 |
+
"""Computes Relative Squared Error.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
sum_squared_obs: Sum of square of all observations
|
| 33 |
+
sum_obs: Sum of all observations
|
| 34 |
+
sum_squared_error: Residual sum of squares
|
| 35 |
+
num_obs: Number of predictions or observations
|
| 36 |
+
squared: Returns RRSE value if set to False.
|
| 37 |
+
|
| 38 |
+
Example:
|
| 39 |
+
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
|
| 40 |
+
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
|
| 41 |
+
>>> # RSE uses the same update function as R2 score.
|
| 42 |
+
>>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
|
| 43 |
+
>>> _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=True)
|
| 44 |
+
tensor(0.0632)
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
epsilon = torch.finfo(sum_squared_error.dtype).eps
|
| 48 |
+
rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / num_obs, min=epsilon)
|
| 49 |
+
if not squared:
|
| 50 |
+
rse = torch.sqrt(rse)
|
| 51 |
+
return torch.mean(rse)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def relative_squared_error(preds: Tensor, target: Tensor, squared: bool = True) -> Tensor:
|
| 55 |
+
r"""Computes the relative squared error (RSE).
|
| 56 |
+
|
| 57 |
+
.. math:: \text{RSE} = \frac{\sum_i^N(y_i - \hat{y_i})^2}{\sum_i^N(y_i - \overline{y})^2}
|
| 58 |
+
|
| 59 |
+
Where :math:`y` is a tensor of target values with mean :math:`\overline{y}`, and
|
| 60 |
+
:math:`\hat{y}` is a tensor of predictions.
|
| 61 |
+
|
| 62 |
+
If `preds` and `targets` are 2D tensors, the RSE is averaged over the second dim.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
preds: estimated labels
|
| 66 |
+
target: ground truth labels
|
| 67 |
+
squared: returns RRSE value if set to False
|
| 68 |
+
Return:
|
| 69 |
+
Tensor with RSE
|
| 70 |
+
|
| 71 |
+
Example:
|
| 72 |
+
>>> from torchmetrics.functional.regression import relative_squared_error
|
| 73 |
+
>>> target = torch.tensor([3, -0.5, 2, 7])
|
| 74 |
+
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
|
| 75 |
+
>>> relative_squared_error(preds, target)
|
| 76 |
+
tensor(0.0514)
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target)
|
| 80 |
+
return _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=squared)
|