Skip to content

Commit b8fc451

Browse files
authored
Move contrib metrics files (#3220)
* move contrib * make changes to ignite/metrics * add tests and import fixes * move docs for deprecated contrib.metrics * move tests for deprecated contrib.metrics * adjust references * rename test modules * fix version of deprecation * fix doctest * add deprecation warnings * adjust precision of comparison in test this test fails intermittently. the main difference between this branch and master is the a chance difference in the order the tests are run which reliably triggers the failure.
1 parent 8cf740d commit b8fc451

File tree

82 files changed

+2504
-1894
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+2504
-1894
lines changed

README.md

+11-8
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def function_before_backprop(engine):
241241
## Out-of-the-box metrics
242242

243243
- [Metrics](https://pytorch.org/ignite/metrics.html#complete-list-of-metrics) for various tasks:
244-
Precision, Recall, Accuracy, Confusion Matrix, IoU etc, ~20 [regression metrics](https://pytorch.org/ignite/contrib/metrics.html#regression-metrics).
244+
Precision, Recall, Accuracy, Confusion Matrix, IoU etc, ~20 [regression metrics](https://pytorch.org/ignite/metrics.html#complete-list-of-metrics).
245245

246246
- Users can also [compose their metrics](https://pytorch.org/ignite/metrics.html#metric-arithmetics) with ease from
247247
existing ones using arithmetic operations or torch methods.
@@ -315,24 +315,27 @@ List of available pre-built images
315315
</summary>
316316

317317
Base
318-
- `pytorchignite/base:latest`
318+
319+
- `pytorchignite/base:latest`
319320
- `pytorchignite/apex:latest`
320321
- `pytorchignite/hvd-base:latest`
321-
- `pytorchignite/hvd-apex:latest`
322+
- `pytorchignite/hvd-apex:latest`
322323
- `pytorchignite/msdp-apex:latest`
323324

324325
Vision:
326+
325327
- `pytorchignite/vision:latest`
326328
- `pytorchignite/hvd-vision:latest`
327329
- `pytorchignite/apex-vision:latest`
328330
- `pytorchignite/hvd-apex-vision:latest`
329331
- `pytorchignite/msdp-apex-vision:latest`
330332

331333
NLP:
334+
332335
- `pytorchignite/nlp:latest`
333336
- `pytorchignite/hvd-nlp:latest`
334-
- `pytorchignite/apex-nlp:latest`
335-
- `pytorchignite/hvd-apex-nlp:latest`
337+
- `pytorchignite/apex-nlp:latest`
338+
- `pytorchignite/hvd-apex-nlp:latest`
336339
- `pytorchignite/msdp-apex-nlp:latest`
337340

338341
</details>
@@ -416,8 +419,8 @@ Features:
416419
## Code-Generator application
417420

418421
The easiest way to create your training scripts with PyTorch-Ignite:
419-
- https://code-generator.pytorch-ignite.ai/
420422

423+
- https://code-generator.pytorch-ignite.ai/
421424

422425
<!-- ############################################################################################################### -->
423426

@@ -502,7 +505,7 @@ Blog articles, tutorials, books
502505
- [The Hero Rises: Build Your Own SSD](https://allegro.ai/blog/the-hero-rises-build-your-own-ssd/)
503506
- [Using Optuna to Optimize PyTorch Ignite Hyperparameters](https://medium.com/pytorch/using-optuna-to-optimize-pytorch-ignite-hyperparameters-626ffe6d4783)
504507
- [PyTorch Ignite - Classifying Tiny ImageNet with EfficientNet](https://towardsdatascience.com/pytorch-ignite-classifying-tiny-imagenet-with-efficientnet-e5b1768e5e8f)
505-
508+
506509
</details>
507510

508511
<details>
@@ -516,7 +519,7 @@ Toolkits
516519
- [Nussl - a flexible, object-oriented Python audio source separation library](https://github.com/nussl/nussl)
517520
- [PyTorch Adapt - A fully featured and modular domain adaptation library](https://github.com/KevinMusgrave/pytorch-adapt)
518521
- [gnina-torch: PyTorch implementation of GNINA scoring function](https://github.com/RMeli/gnina-torch)
519-
522+
520523
</details>
521524

522525
<details>

docs/source/contrib/handlers.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,5 @@ Time profilers [deprecated]
2828
Loggers [deprecated]
2929
--------------------
3030

31-
.. deprecated:: 0.4.14
31+
.. deprecated:: 0.5.1
3232
Loggers moved to :ref:`Loggers`.

docs/source/contrib/metrics.rst

+9-50
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,15 @@
11
ignite.contrib.metrics
2-
======================
2+
=======================
33

4-
Contrib module metrics
5-
----------------------
4+
Contrib module metrics [deprecated]
5+
-----------------------------------
66

7-
.. currentmodule:: ignite.contrib.metrics
7+
.. deprecated:: 0.5.1
8+
All metrics moved to :ref:`Complete list of metrics`.
89

9-
.. autosummary::
10-
:nosignatures:
11-
:toctree: ../generated
1210

13-
AveragePrecision
14-
CohenKappa
15-
GpuInfo
16-
PrecisionRecallCurve
17-
ROC_AUC
18-
RocCurve
11+
Regression metrics [deprecated]
12+
--------------------------------
1913

20-
Regression metrics
21-
------------------
22-
23-
.. currentmodule:: ignite.contrib.metrics.regression
24-
25-
.. automodule:: ignite.contrib.metrics.regression
26-
27-
28-
Module :mod:`ignite.contrib.metrics.regression` provides implementations of
29-
metrics useful for regression tasks. Definitions of metrics are based on `Botchkarev 2018`_, page 30 "Appendix 2. Metrics mathematical definitions".
30-
31-
.. _`Botchkarev 2018`:
32-
https://arxiv.org/abs/1809.03006
33-
34-
Complete list of metrics:
35-
36-
.. currentmodule:: ignite.contrib.metrics.regression
37-
38-
.. autosummary::
39-
:nosignatures:
40-
:toctree: ../generated
41-
42-
CanberraMetric
43-
FractionalAbsoluteError
44-
FractionalBias
45-
GeometricMeanAbsoluteError
46-
GeometricMeanRelativeAbsoluteError
47-
ManhattanDistance
48-
MaximumAbsoluteError
49-
MeanAbsoluteRelativeError
50-
MeanError
51-
MeanNormalizedBias
52-
MedianAbsoluteError
53-
MedianAbsolutePercentageError
54-
MedianRelativeAbsoluteError
55-
R2Score
56-
WaveHedgesDistance
14+
.. deprecated:: 0.5.1
15+
All metrics moved to :ref:`Complete list of metrics`.

docs/source/defaults.rst

+2-3
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,8 @@
1212
from ignite.engine import *
1313
from ignite.handlers import *
1414
from ignite.metrics import *
15+
from ignite.metrics.regression import *
1516
from ignite.utils import *
16-
from ignite.contrib.metrics.regression import *
17-
from ignite.contrib.metrics import *
1817

1918
# create default evaluator for doctests
2019

@@ -46,4 +45,4 @@
4645
('fc', nn.Linear(2, 1))
4746
]))
4847

49-
manual_seed(666)
48+
manual_seed(666)

docs/source/metrics.rst

+32
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,35 @@ Complete list of metrics
352352
FID
353353
CosineSimilarity
354354
Entropy
355+
AveragePrecision
356+
CohenKappa
357+
GpuInfo
358+
PrecisionRecallCurve
359+
RocCurve
360+
ROC_AUC
361+
regression.CanberraMetric
362+
regression.FractionalAbsoluteError
363+
regression.FractionalBias
364+
regression.GeometricMeanAbsoluteError
365+
regression.GeometricMeanRelativeAbsoluteError
366+
regression.ManhattanDistance
367+
regression.MaximumAbsoluteError
368+
regression.MeanAbsoluteRelativeError
369+
regression.MeanError
370+
regression.MeanNormalizedBias
371+
regression.MedianAbsoluteError
372+
regression.MedianAbsolutePercentageError
373+
regression.MedianRelativeAbsoluteError
374+
regression.R2Score
375+
regression.WaveHedgesDistance
376+
377+
378+
.. note::
379+
380+
Module ignite.metrics.regression provides implementations of metrics useful
381+
for regression tasks. Definitions of metrics are based on
382+
`Botchkarev 2018`_, page 30 "Appendix 2. Metrics mathematical definitions".
383+
355384

356385
Helpers for customizing metrics
357386
-------------------------------
@@ -393,3 +422,6 @@ reinit__is_reduced
393422
sync_all_reduce
394423
~~~~~~~~~~~~~~~
395424
.. autofunction:: sync_all_reduce
425+
426+
.. _`Botchkarev 2018`:
427+
https://arxiv.org/abs/1809.03006

examples/mnist/mnist_with_tensorboard_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def run(train_batch_size, val_batch_size, epochs, lr, momentum, log_dir):
9191
trainer.logger = setup_logger("Trainer")
9292

9393
if sys.version_info > (3,):
94-
from ignite.contrib.metrics.gpu_info import GpuInfo
94+
from ignite.metrics.gpu_info import GpuInfo
9595

9696
try:
9797
GpuInfo().attach(trainer)

examples/mnist/mnist_with_tqdm_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def run(train_batch_size, val_batch_size, epochs, lr, momentum, display_gpu_info
6464
RunningAverage(output_transform=lambda x: x).attach(trainer, "loss")
6565

6666
if display_gpu_info:
67-
from ignite.contrib.metrics import GpuInfo
67+
from ignite.metrics import GpuInfo
6868

6969
GpuInfo().attach(trainer, name="gpu")
7070

ignite/contrib/engines/common.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from torch.optim.lr_scheduler import _LRScheduler as PyTorchLRScheduler
1616

1717
import ignite.distributed as idist
18-
from ignite.contrib.metrics import GpuInfo
1918
from ignite.engine import Engine, Events
2019
from ignite.handlers import (
2120
Checkpoint,
@@ -35,7 +34,7 @@
3534
from ignite.handlers.base_logger import BaseLogger
3635
from ignite.handlers.checkpoint import BaseSaveHandler
3736
from ignite.handlers.param_scheduler import ParamScheduler
38-
from ignite.metrics import RunningAverage
37+
from ignite.metrics import GpuInfo, RunningAverage
3938
from ignite.metrics.metric import RunningBatchWise
4039
from ignite.utils import deprecated
4140

@@ -78,14 +77,14 @@ def setup_common_training_handlers(
7877
exclusive with ``save_handler``.
7978
lr_scheduler: learning rate scheduler
8079
as native torch LRScheduler or ignite's parameter scheduler.
81-
with_gpu_stats: if True, :class:`~ignite.contrib.metrics.GpuInfo` is attached to the
80+
with_gpu_stats: if True, :class:`~ignite.metrics.GpuInfo` is attached to the
8281
trainer. This requires `pynvml` package to be installed.
8382
output_names: list of names associated with `update_function` output dictionary.
8483
with_pbars: if True, two progress bars on epochs and optionally on iterations are attached.
8584
Default, True.
8685
with_pbar_on_iters: if True, a progress bar on iterations is attached to the trainer.
8786
Default, True.
88-
log_every_iters: logging interval for :class:`~ignite.contrib.metrics.GpuInfo` and for
87+
log_every_iters: logging interval for :class:`~ignite.metrics.GpuInfo` and for
8988
epoch-wise progress bar. Default, 100.
9089
stop_on_nan: if True, :class:`~ignite.handlers.terminate_on_nan.TerminateOnNan` handler is added to the trainer.
9190
Default, True.

ignite/contrib/metrics/__init__.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import ignite.contrib.metrics.regression
2-
from ignite.contrib.metrics.average_precision import AveragePrecision
3-
from ignite.contrib.metrics.cohen_kappa import CohenKappa
4-
from ignite.contrib.metrics.gpu_info import GpuInfo
5-
from ignite.contrib.metrics.precision_recall_curve import PrecisionRecallCurve
6-
from ignite.contrib.metrics.roc_auc import ROC_AUC, RocCurve
1+
import ignite.metrics.regression
2+
from ignite.metrics import average_precision, cohen_kappa, gpu_info, precision_recall_curve, roc_auc
3+
from ignite.metrics.average_precision import AveragePrecision
4+
from ignite.metrics.cohen_kappa import CohenKappa
5+
from ignite.metrics.gpu_info import GpuInfo
6+
from ignite.metrics.precision_recall_curve import PrecisionRecallCurve
7+
from ignite.metrics.roc_auc import ROC_AUC, RocCurve
+22-81
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,22 @@
1-
from typing import Callable, Union
2-
3-
import torch
4-
5-
from ignite.metrics import EpochMetric
6-
7-
8-
def average_precision_compute_fn(y_preds: torch.Tensor, y_targets: torch.Tensor) -> float:
9-
from sklearn.metrics import average_precision_score
10-
11-
y_true = y_targets.cpu().numpy()
12-
y_pred = y_preds.cpu().numpy()
13-
return average_precision_score(y_true, y_pred)
14-
15-
16-
class AveragePrecision(EpochMetric):
17-
"""Computes Average Precision accumulating predictions and the ground-truth during an epoch
18-
and applying `sklearn.metrics.average_precision_score <https://scikit-learn.org/stable/modules/generated/
19-
sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ .
20-
21-
Args:
22-
output_transform: a callable that is used to transform the
23-
:class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the
24-
form expected by the metric. This can be useful if, for example, you have a multi-output model and
25-
you want to compute the metric with respect to one of the outputs.
26-
check_compute_fn: Default False. If True, `average_precision_score
27-
<https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html
28-
#sklearn.metrics.average_precision_score>`_ is run on the first batch of data to ensure there are
29-
no issues. User will be warned in case there are any issues computing the function.
30-
device: optional device specification for internal storage.
31-
32-
Note:
33-
AveragePrecision expects y to be comprised of 0's and 1's. y_pred must either be probability estimates or
34-
confidence values. To apply an activation to y_pred, use output_transform as shown below:
35-
36-
.. code-block:: python
37-
38-
def activated_output_transform(output):
39-
y_pred, y = output
40-
y_pred = torch.softmax(y_pred, dim=1)
41-
return y_pred, y
42-
avg_precision = AveragePrecision(activated_output_transform)
43-
44-
Examples:
45-
46-
.. include:: defaults.rst
47-
:start-after: :orphan:
48-
49-
.. testcode::
50-
51-
y_pred = torch.tensor([[0.79, 0.21], [0.30, 0.70], [0.46, 0.54], [0.16, 0.84]])
52-
y_true = torch.tensor([[1, 1], [1, 1], [0, 1], [0, 1]])
53-
54-
avg_precision = AveragePrecision()
55-
avg_precision.attach(default_evaluator, 'average_precision')
56-
state = default_evaluator.run([[y_pred, y_true]])
57-
print(state.metrics['average_precision'])
58-
59-
.. testoutput::
60-
61-
0.9166...
62-
63-
"""
64-
65-
def __init__(
66-
self,
67-
output_transform: Callable = lambda x: x,
68-
check_compute_fn: bool = False,
69-
device: Union[str, torch.device] = torch.device("cpu"),
70-
):
71-
try:
72-
from sklearn.metrics import average_precision_score # noqa: F401
73-
except ImportError:
74-
raise ModuleNotFoundError("This contrib module requires scikit-learn to be installed.")
75-
76-
super(AveragePrecision, self).__init__(
77-
average_precision_compute_fn,
78-
output_transform=output_transform,
79-
check_compute_fn=check_compute_fn,
80-
device=device,
81-
)
1+
""" ``ignite.contrib.metrics.average_precision`` was moved to ``ignite.metrics.average_precision``.
2+
Note:
3+
``ignite.contrib.metrics.average_precision`` was moved to ``ignite.metrics.average_precision``.
4+
Please refer to :mod:`~ignite.metrics.average_precision`.
5+
"""
6+
7+
import warnings
8+
9+
removed_in = "0.6.0"
10+
deprecation_warning = (
11+
f"{__file__} has been moved to /ignite/metrics/average_precision.py"
12+
+ (f" and will be removed in version {removed_in}" if removed_in else "")
13+
+ ".\n Please refer to the documentation for more details."
14+
)
15+
warnings.warn(deprecation_warning, DeprecationWarning, stacklevel=2)
16+
from ignite.metrics.average_precision import AveragePrecision
17+
18+
__all__ = [
19+
"AveragePrecision",
20+
]
21+
22+
AveragePrecision = AveragePrecision

0 commit comments

Comments
 (0)