File size: 28,384 Bytes
9c6594c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections.abc import Sequence
from typing import Any, Callable, Optional, Union
import torch
from torch import Tensor
from typing_extensions import Literal
from torchmetrics.metric import Metric
from torchmetrics.utilities import rank_zero_warn
from torchmetrics.utilities.data import dim_zero_cat
from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
from torchmetrics.wrappers.running import Running
if not _MATPLOTLIB_AVAILABLE:
__doctest_skip__ = ["SumMetric.plot", "MeanMetric.plot", "MaxMetric.plot", "MinMetric.plot"]
class BaseAggregator(Metric):
"""Base class for aggregation metrics.
Args:
fn: string specifying the reduction function
default_value: default tensor value to use for the metric state
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
state_name: name of the metric state
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
"""
is_differentiable = None
higher_is_better = None
full_state_update: bool = False
def __init__(
self,
fn: Union[Callable, str],
default_value: Union[Tensor, list],
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "error",
state_name: str = "value",
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
allowed_nan_strategy = ("error", "warn", "ignore", "disable")
if nan_strategy not in allowed_nan_strategy and not isinstance(nan_strategy, float):
raise ValueError(
f"Arg `nan_strategy` should either be a float or one of {allowed_nan_strategy} but got {nan_strategy}."
)
self.nan_strategy = nan_strategy
self.add_state(state_name, default=default_value, dist_reduce_fx=fn)
self.state_name = state_name
def _cast_and_nan_check_input(
self, x: Union[float, Tensor], weight: Optional[Union[float, Tensor]] = None
) -> tuple[Tensor, Tensor]:
"""Convert input ``x`` to a tensor and check for Nans."""
if not isinstance(x, Tensor):
x = torch.as_tensor(x, dtype=self.dtype, device=self.device)
if weight is not None and not isinstance(weight, Tensor):
weight = torch.as_tensor(weight, dtype=self.dtype, device=self.device)
if self.nan_strategy != "disable":
nans = torch.isnan(x)
if weight is not None:
nans_weight = torch.isnan(weight)
else:
nans_weight = torch.zeros_like(nans).bool()
weight = torch.ones_like(x)
if nans.any() or nans_weight.any():
if self.nan_strategy == "error":
raise RuntimeError("Encountered `nan` values in tensor")
if self.nan_strategy in ("ignore", "warn"):
if self.nan_strategy == "warn":
rank_zero_warn("Encountered `nan` values in tensor. Will be removed.", UserWarning)
x = x[~(nans | nans_weight)]
weight = weight[~(nans | nans_weight)]
else:
if not isinstance(self.nan_strategy, float):
raise ValueError(f"`nan_strategy` shall be float but you pass {self.nan_strategy}")
x[nans | nans_weight] = self.nan_strategy
weight[nans | nans_weight] = 1
else:
weight = torch.ones_like(x)
return x.to(self.dtype), weight.to(self.dtype)
def update(self, value: Union[float, Tensor]) -> None:
"""Overwrite in child class."""
def compute(self) -> Tensor:
"""Compute the aggregated value."""
return getattr(self, self.state_name)
class MaxMetric(BaseAggregator):
"""Aggregate a stream of value into their maximum value.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated maximum value over all inputs received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import MaxMetric
>>> metric = MaxMetric()
>>> metric.update(1)
>>> metric.update(tensor([2, 3]))
>>> metric.compute()
tensor(3.)
"""
full_state_update: bool = True
max_value: Tensor
def __init__(
self,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(
"max",
-torch.tensor(float("inf"), dtype=torch.get_default_dtype()),
nan_strategy,
state_name="max_value",
**kwargs,
)
def update(self, value: Union[float, Tensor]) -> None:
"""Update state with data.
Args:
value: Either a float or tensor containing data. Additional tensor
dimensions will be flattened
"""
value, _ = self._cast_and_nan_check_input(value)
if value.numel(): # make sure tensor not empty
self.max_value = torch.max(self.max_value, torch.max(value))
def plot(
self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
) -> _PLOT_OUT_TYPE:
"""Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An matplotlib axis object. If provided will add plot to that axis
Returns:
Figure and Axes object
Raises:
ModuleNotFoundError:
If `matplotlib` is not installed
.. plot::
:scale: 75
>>> # Example plotting a single value
>>> from torchmetrics.aggregation import MaxMetric
>>> metric = MaxMetric()
>>> metric.update([1, 2, 3])
>>> fig_, ax_ = metric.plot()
.. plot::
:scale: 75
>>> # Example plotting multiple values
>>> from torchmetrics.aggregation import MaxMetric
>>> metric = MaxMetric()
>>> values = [ ]
>>> for i in range(10):
... values.append(metric(i))
>>> fig_, ax_ = metric.plot(values)
"""
return self._plot(val, ax)
class MinMetric(BaseAggregator):
"""Aggregate a stream of value into their minimum value.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated minimum value over all inputs received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import MinMetric
>>> metric = MinMetric()
>>> metric.update(1)
>>> metric.update(tensor([2, 3]))
>>> metric.compute()
tensor(1.)
"""
full_state_update: bool = True
min_value: Tensor
def __init__(
self,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(
"min",
torch.tensor(float("inf"), dtype=torch.get_default_dtype()),
nan_strategy,
state_name="min_value",
**kwargs,
)
def update(self, value: Union[float, Tensor]) -> None:
"""Update state with data.
Args:
value: Either a float or tensor containing data. Additional tensor
dimensions will be flattened
"""
value, _ = self._cast_and_nan_check_input(value)
if value.numel(): # make sure tensor not empty
self.min_value = torch.min(self.min_value, torch.min(value))
def plot(
self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
) -> _PLOT_OUT_TYPE:
"""Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An matplotlib axis object. If provided will add plot to that axis
Returns:
Figure and Axes object
Raises:
ModuleNotFoundError:
If `matplotlib` is not installed
.. plot::
:scale: 75
>>> # Example plotting a single value
>>> from torchmetrics.aggregation import MinMetric
>>> metric = MinMetric()
>>> metric.update([1, 2, 3])
>>> fig_, ax_ = metric.plot()
.. plot::
:scale: 75
>>> # Example plotting multiple values
>>> from torchmetrics.aggregation import MinMetric
>>> metric = MinMetric()
>>> values = [ ]
>>> for i in range(10):
... values.append(metric(i))
>>> fig_, ax_ = metric.plot(values)
"""
return self._plot(val, ax)
class SumMetric(BaseAggregator):
"""Aggregate a stream of value into their sum.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated sum over all inputs received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import SumMetric
>>> metric = SumMetric()
>>> metric.update(1)
>>> metric.update(tensor([2, 3]))
>>> metric.compute()
tensor(6.)
"""
sum_value: Tensor
def __init__(
self,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(
"sum",
torch.tensor(0.0, dtype=torch.get_default_dtype()),
nan_strategy,
state_name="sum_value",
**kwargs,
)
def update(self, value: Union[float, Tensor]) -> None:
"""Update state with data.
Args:
value: Either a float or tensor containing data. Additional tensor
dimensions will be flattened
"""
value, _ = self._cast_and_nan_check_input(value)
if value.numel():
self.sum_value += value.sum()
def plot(
self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
) -> _PLOT_OUT_TYPE:
"""Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An matplotlib axis object. If provided will add plot to that axis
Returns:
Figure and Axes object
Raises:
ModuleNotFoundError:
If `matplotlib` is not installed
.. plot::
:scale: 75
>>> # Example plotting a single value
>>> from torchmetrics.aggregation import SumMetric
>>> metric = SumMetric()
>>> metric.update([1, 2, 3])
>>> fig_, ax_ = metric.plot()
.. plot::
:scale: 75
>>> # Example plotting multiple values
>>> from torch import rand, randint
>>> from torchmetrics.aggregation import SumMetric
>>> metric = SumMetric()
>>> values = [ ]
>>> for i in range(10):
... values.append(metric([i, i+1]))
>>> fig_, ax_ = metric.plot(values)
"""
return self._plot(val, ax)
class CatMetric(BaseAggregator):
"""Concatenate a stream of values.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with concatenated values over all input received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import CatMetric
>>> metric = CatMetric()
>>> metric.update(1)
>>> metric.update(tensor([2, 3]))
>>> metric.compute()
tensor([1., 2., 3.])
"""
value: Tensor
def __init__(
self,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__("cat", [], nan_strategy, **kwargs)
def update(self, value: Union[float, Tensor]) -> None:
"""Update state with data.
Args:
value: Either a float or tensor containing data. Additional tensor
dimensions will be flattened
"""
value, _ = self._cast_and_nan_check_input(value)
if value.numel():
self.value.append(value)
def compute(self) -> Tensor:
"""Compute the aggregated value."""
if isinstance(self.value, list) and self.value:
return dim_zero_cat(self.value)
return self.value
class MeanMetric(BaseAggregator):
"""Aggregate a stream of value into their mean value.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
- ``weight`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float value with
arbitrary shape ``(...,)``. Needs to be broadcastable with the shape of ``value`` tensor.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated (weighted) mean over all inputs received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torchmetrics.aggregation import MeanMetric
>>> metric = MeanMetric()
>>> metric.update(1)
>>> metric.update(torch.tensor([2, 3]))
>>> metric.compute()
tensor(2.)
"""
mean_value: Tensor
weight: Tensor
def __init__(
self,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(
"sum",
torch.tensor(0.0, dtype=torch.get_default_dtype()),
nan_strategy,
state_name="mean_value",
**kwargs,
)
self.add_state("weight", default=torch.tensor(0.0, dtype=torch.get_default_dtype()), dist_reduce_fx="sum")
def update(self, value: Union[float, Tensor], weight: Union[float, Tensor, None] = None) -> None:
"""Update state with data.
Args:
value: Either a float or tensor containing data. Additional tensor
dimensions will be flattened
weight: Either a float or tensor containing weights for calculating
the average. Shape of weight should be able to broadcast with
the shape of `value`. Default to None corresponding to simple
harmonic average.
"""
# broadcast weight to value shape
if not isinstance(value, Tensor):
value = torch.as_tensor(value, dtype=self.dtype, device=self.device)
if weight is None:
weight = torch.ones_like(value)
elif not isinstance(weight, Tensor):
weight = torch.as_tensor(weight, dtype=self.dtype, device=self.device)
weight = torch.broadcast_to(weight, value.shape)
value, weight = self._cast_and_nan_check_input(value, weight)
if value.numel() == 0:
return
self.mean_value += (value * weight).sum()
self.weight += weight.sum()
def compute(self) -> Tensor:
"""Compute the aggregated value."""
return self.mean_value / self.weight
def plot(
self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
) -> _PLOT_OUT_TYPE:
"""Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An matplotlib axis object. If provided will add plot to that axis
Returns:
Figure and Axes object
Raises:
ModuleNotFoundError:
If `matplotlib` is not installed
.. plot::
:scale: 75
>>> # Example plotting a single value
>>> from torchmetrics.aggregation import MeanMetric
>>> metric = MeanMetric()
>>> metric.update([1, 2, 3])
>>> fig_, ax_ = metric.plot()
.. plot::
:scale: 75
>>> # Example plotting multiple values
>>> from torchmetrics.aggregation import MeanMetric
>>> metric = MeanMetric()
>>> values = [ ]
>>> for i in range(10):
... values.append(metric([i, i+1]))
>>> fig_, ax_ = metric.plot(values)
"""
return self._plot(val, ax)
class RunningMean(Running):
"""Aggregate a stream of value into their mean over a running window.
Using this metric compared to `MeanMetric` allows for calculating metrics over a running window of values, instead
of the whole history of values. This is beneficial when you want to get a better estimate of the metric during
training and don't want to wait for the whole training to finish to get epoch level estimates.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated sum over all inputs received
Args:
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import RunningMean
>>> metric = RunningMean(window=3)
>>> for i in range(6):
... current_val = metric(tensor([i]))
... running_val = metric.compute()
... total_val = tensor(sum(list(range(i+1)))) / (i+1) # total mean over all samples
... print(f"{current_val=}, {running_val=}, {total_val=}")
current_val=tensor(0.), running_val=tensor(0.), total_val=tensor(0.)
current_val=tensor(1.), running_val=tensor(0.5000), total_val=tensor(0.5000)
current_val=tensor(2.), running_val=tensor(1.), total_val=tensor(1.)
current_val=tensor(3.), running_val=tensor(2.), total_val=tensor(1.5000)
current_val=tensor(4.), running_val=tensor(3.), total_val=tensor(2.)
current_val=tensor(5.), running_val=tensor(4.), total_val=tensor(2.5000)
"""
def __init__(
self,
window: int = 5,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(base_metric=MeanMetric(nan_strategy=nan_strategy, **kwargs), window=window)
class RunningSum(Running):
"""Aggregate a stream of value into their sum over a running window.
Using this metric compared to `SumMetric` allows for calculating metrics over a running window of values, instead
of the whole history of values. This is beneficial when you want to get a better estimate of the metric during
training and don't want to wait for the whole training to finish to get epoch level estimates.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``value`` (:class:`~float` or :class:`~torch.Tensor`): a single float or an tensor of float values with
arbitrary shape ``(...,)``.
As output of `forward` and `compute` the metric returns the following output
- ``agg`` (:class:`~torch.Tensor`): scalar float tensor with aggregated sum over all inputs received
Args:
window: The size of the running window.
nan_strategy: options:
- ``'error'``: if any `nan` values are encountered will give a RuntimeError
- ``'warn'``: if any `nan` values are encountered will give a warning and continue
- ``'ignore'``: all `nan` values are silently removed
- ``'disable'``: disable all `nan` checks
- a float: if a float is provided will impute any `nan` values with this value
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
ValueError:
If ``nan_strategy`` is not one of ``error``, ``warn``, ``ignore``, ``disable`` or a float
Example:
>>> from torch import tensor
>>> from torchmetrics.aggregation import RunningSum
>>> metric = RunningSum(window=3)
>>> for i in range(6):
... current_val = metric(tensor([i]))
... running_val = metric.compute()
... total_val = tensor(sum(list(range(i+1)))) # total sum over all samples
... print(f"{current_val=}, {running_val=}, {total_val=}")
current_val=tensor(0.), running_val=tensor(0.), total_val=tensor(0)
current_val=tensor(1.), running_val=tensor(1.), total_val=tensor(1)
current_val=tensor(2.), running_val=tensor(3.), total_val=tensor(3)
current_val=tensor(3.), running_val=tensor(6.), total_val=tensor(6)
current_val=tensor(4.), running_val=tensor(9.), total_val=tensor(10)
current_val=tensor(5.), running_val=tensor(12.), total_val=tensor(15)
"""
def __init__(
self,
window: int = 5,
nan_strategy: Union[Literal["error", "warn", "ignore", "disable"], float] = "warn",
**kwargs: Any,
) -> None:
super().__init__(base_metric=SumMetric(nan_strategy=nan_strategy, **kwargs), window=window)
|