code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def set_bypass_mode(cls, bypass: bool) -> None: """ Set ``clearml.Task`` to offline mode. Will bypass all outside communication, and will save all data and logs to a local session folder. Should only be used in "standalone mode", when there is no access to the *clearml-server*. ...
Set ``clearml.Task`` to offline mode. Will bypass all outside communication, and will save all data and logs to a local session folder. Should only be used in "standalone mode", when there is no access to the *clearml-server*. Args: bypass: If ``True``, all outside communic...
set_bypass_mode
python
pytorch/ignite
ignite/handlers/clearml_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/clearml_logger.py
BSD-3-Clause
def get_local_copy(self, filename: str) -> Optional[str]: """Get artifact local copy. .. warning:: In distributed configuration this method should be called on rank 0 process. Args: filename: artifact name. Returns: a local path to a downloaded co...
Get artifact local copy. .. warning:: In distributed configuration this method should be called on rank 0 process. Args: filename: artifact name. Returns: a local path to a downloaded copy of the artifact
get_local_copy
python
pytorch/ignite
ignite/handlers/clearml_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/clearml_logger.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Method replace internal state of the class with provided state dict data. Args: state_dict: a dict with "counter" and "best_score" keys/values. """ super().load_state_dict(state_dict) self.counter = state_dic...
Method replace internal state of the class with provided state dict data. Args: state_dict: a dict with "counter" and "best_score" keys/values.
load_state_dict
python
pytorch/ignite
ignite/handlers/early_stopping.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/early_stopping.py
BSD-3-Clause
def attach( self, engine: Engine, name: str = "ema_momentum", warn_if_exists: bool = True, event: Union[str, Events, CallableEventWithFilter, EventsList] = Events.ITERATION_COMPLETED, ) -> None: """Attach the handler to engine. After the handler is attached, the ``Eng...
Attach the handler to engine. After the handler is attached, the ``Engine.state`` will add an new attribute with name ``name`` if the attribute does not exist. Then, the current momentum can be retrieved from ``Engine.state`` when the engine runs. Note: There are two cases where a ...
attach
python
pytorch/ignite
ignite/handlers/ema_handler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/ema_handler.py
BSD-3-Clause
def attach( self, engine: Engine, name: str, every: int = 1, output_transform: Optional[Callable] = None, state_attributes: Optional[List[str]] = None, optimizer: Optional[torch.optim.Optimizer] = None, ) -> None: """Attaches all the logging handlers t...
Attaches all the logging handlers to the given engine. Args: engine: The engine to attach the logging handlers to. name: The name of the engine (e.g., "Train", "Validate") to include in log messages. every: Frequency of iterations to log information. Logs are generated every...
attach
python
pytorch/ignite
ignite/handlers/fbresearch_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/fbresearch_logger.py
BSD-3-Clause
def log_every(self, engine: Engine, optimizer: Optional[torch.optim.Optimizer] = None) -> None: """ Logs the training progress at regular intervals. Args: engine: The training engine. optimizer: The optimizer used for training. Defaults to None. """ asser...
Logs the training progress at regular intervals. Args: engine: The training engine. optimizer: The optimizer used for training. Defaults to None.
log_every
python
pytorch/ignite
ignite/handlers/fbresearch_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/fbresearch_logger.py
BSD-3-Clause
def log_epoch_completed(self, engine: Engine, name: str) -> None: """ Logs the completion of an epoch. Args: engine: The engine object that triggered the event. name: The name of the event. Returns: None """ epoch_time = engine.state....
Logs the completion of an epoch. Args: engine: The engine object that triggered the event. name: The name of the event. Returns: None
log_epoch_completed
python
pytorch/ignite
ignite/handlers/fbresearch_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/fbresearch_logger.py
BSD-3-Clause
def log_completed(self, engine: Engine, name: str) -> None: """ Logs the completion of a run. Args: engine: The engine object representing the training/validation loop. name: The name of the run. """ if engine.state.max_epochs and engine.state.max_epochs...
Logs the completion of a run. Args: engine: The engine object representing the training/validation loop. name: The name of the run.
log_completed
python
pytorch/ignite
ignite/handlers/fbresearch_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/fbresearch_logger.py
BSD-3-Clause
def _detach(self, trainer: Engine) -> None: """ Detaches lr_finder from trainer. Args: trainer: the trainer to detach form. """ if trainer.has_event_handler(self._run, Events.STARTED): trainer.remove_event_handler(self._run, Events.STARTED) if tr...
Detaches lr_finder from trainer. Args: trainer: the trainer to detach form.
_detach
python
pytorch/ignite
ignite/handlers/lr_finder.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/lr_finder.py
BSD-3-Clause
def plot( self, skip_start: int = 10, skip_end: int = 5, log_lr: bool = True, display_suggestion: bool = True, ax: Optional[Any] = None, **kwargs: Any, ) -> None: """Plots the learning rate range test. This method requires ``matplotlib`` packa...
Plots the learning rate range test. This method requires ``matplotlib`` package to be installed: .. code-block:: bash pip install matplotlib Args: skip_start: number of batches to trim from the start. Default: 10. skip_end: number of batche...
plot
python
pytorch/ignite
ignite/handlers/lr_finder.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/lr_finder.py
BSD-3-Clause
def lr_suggestion(self) -> Any: """ Returns: Learning rate at the minimum numerical gradient (ignoring the increasing part of the curve) """ if not self._history: raise RuntimeError("learning rate finder didn't run yet so lr_suggestion can't be returne...
Returns: Learning rate at the minimum numerical gradient (ignoring the increasing part of the curve)
lr_suggestion
python
pytorch/ignite
ignite/handlers/lr_finder.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/lr_finder.py
BSD-3-Clause
def apply_suggested_lr(self, optimizer: Optimizer) -> None: """ Applying the suggested learning rate(s) on the given optimizer. Args: optimizer: the optimizer to apply the suggested learning rate(s) on. Note: The given optimizer must be the same as the one we be...
Applying the suggested learning rate(s) on the given optimizer. Args: optimizer: the optimizer to apply the suggested learning rate(s) on. Note: The given optimizer must be the same as the one we before found the suggested learning rate for.
apply_suggested_lr
python
pytorch/ignite
ignite/handlers/lr_finder.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/lr_finder.py
BSD-3-Clause
def attach( self, trainer: Engine, to_save: Mapping, output_transform: Callable = lambda output: output, num_iter: Optional[int] = None, start_lr: Optional[Union[float, List[float]]] = None, end_lr: Optional[Union[float, List[float]]] = 10.0, step_mode: st...
Attaches lr_finder to a given trainer. It also resets model and optimizer at the end of the run. Args: trainer: lr_finder is attached to this trainer. Please, keep in mind that all attached handlers will be executed. to_save: dictionary with optimizer and other objects t...
attach
python
pytorch/ignite
ignite/handlers/lr_finder.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/lr_finder.py
BSD-3-Clause
def state_dict(self) -> Dict[str, Any]: """Returns a dictionary containing a whole state of BaseParamScheduler. Returns: dict: a dictionary containing a whole state of BaseParamScheduler """ destination = OrderedDict() for name in self._state_attrs: ...
Returns a dictionary containing a whole state of BaseParamScheduler. Returns: dict: a dictionary containing a whole state of BaseParamScheduler
state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Copies parameters from :attr:`state_dict` into this BaseParamScheduler. Args: state_dict: a dict containing parameters. """ if not isinstance(state_dict, Mapping): raise TypeError(f"Argument state_dict sh...
Copies parameters from :attr:`state_dict` into this BaseParamScheduler. Args: state_dict: a dict containing parameters.
load_state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def plot_values(cls, num_events: int, **scheduler_kwargs: Mapping) -> Any: """Method to plot simulated scheduled values during `num_events` events. This class requires `matplotlib package <https://matplotlib.org/>`_ to be installed: .. code-block:: bash pip install matplotlib ...
Method to plot simulated scheduled values during `num_events` events. This class requires `matplotlib package <https://matplotlib.org/>`_ to be installed: .. code-block:: bash pip install matplotlib Args: num_events: number of events during the simulation. ...
plot_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def simulate_values(cls, num_events: int, **scheduler_kwargs: Any) -> List[List[int]]: """Method to simulate scheduled values during `num_events` events. Args: num_events: number of events during the simulation. scheduler_kwargs: parameter scheduler configuration kwargs. ...
Method to simulate scheduled values during `num_events` events. Args: num_events: number of events during the simulation. scheduler_kwargs: parameter scheduler configuration kwargs. Returns: event_index, value Examples: .. code-block:: python ...
simulate_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def _get_param(self) -> Union[List[float], float]: """Applies warm-up if the scheduler is in the warm-up phase, otherwise returns what is returned by `self.get_param()` """ if self.event_index > self.cycle_size: warmup_progress = (self.event_index - self.cycle_size) / self.wa...
Applies warm-up if the scheduler is in the warm-up phase, otherwise returns what is returned by `self.get_param()`
_get_param
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def get_param(self) -> float: """Method to get current optimizer's parameter value""" cycle_progress = self.event_index / self.cycle_size if self.monotonic: return self.start_value + (self.end_value - self.start_value) * cycle_progress else: return self.end_value...
Method to get current optimizer's parameter value
get_param
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def state_dict(self) -> Dict[str, Any]: """Returns a dictionary containing a whole state of ConcatScheduler. Returns: dict: a dictionary containing a whole state of ConcatScheduler """ state_dict = super(ConcatScheduler, self).state_dict() state_dict...
Returns a dictionary containing a whole state of ConcatScheduler. Returns: dict: a dictionary containing a whole state of ConcatScheduler
state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Copies parameters from :attr:`state_dict` into this ConcatScheduler. Args: state_dict: a dict containing parameters. """ if not isinstance(state_dict, Mapping): raise TypeError(f"Argument state_dict shoul...
Copies parameters from :attr:`state_dict` into this ConcatScheduler. Args: state_dict: a dict containing parameters.
load_state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def simulate_values( # type: ignore[override] cls, num_events: int, schedulers: List[ParamScheduler], durations: List[int], param_names: Optional[Union[List[str], Tuple[str]]] = None, ) -> List[List[int]]: """Method to simulate scheduled values during num_events even...
Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. schedulers: list of parameter schedulers. durations: list of number of events that lasts a parameter scheduler from schedulers. param_names: pa...
simulate_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def simulate_values( # type: ignore[override] cls, num_events: int, lr_scheduler: PyTorchLRScheduler, **kwargs: Any ) -> List[List[int]]: """Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. lr_sc...
Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. lr_scheduler: lr_scheduler object to wrap. Returns: event_index, value
simulate_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def create_lr_scheduler_with_warmup( lr_scheduler: Union[ParamScheduler, PyTorchLRScheduler], warmup_start_value: float, warmup_duration: int, warmup_end_value: Optional[float] = None, save_history: bool = False, output_simulated_values: Optional[List] = None, ) -> "ConcatScheduler": """ ...
Helper method to create a learning rate scheduler with a linear warm-up. Args: lr_scheduler: learning rate scheduler after the warm-up. warmup_start_value: learning rate start value of the warm-up phase. warmup_duration: warm-up phase duration, number of events. warmup_end_valu...
create_lr_scheduler_with_warmup
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def state_dict(self) -> Dict[str, List[Any]]: """Returns a dictionary containing a whole state of ParamGroupScheduler. Returns: dict: a dictionary containing a whole state of ParamGroupScheduler """ state_dict: Dict[str, List[Any]] = OrderedDict() sta...
Returns a dictionary containing a whole state of ParamGroupScheduler. Returns: dict: a dictionary containing a whole state of ParamGroupScheduler
state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Copies parameters from :attr:`state_dict` into this ParamScheduler. Args: state_dict: a dict containing parameters. """ if not isinstance(state_dict, Mapping): raise TypeError(f"Argument state_dict should...
Copies parameters from :attr:`state_dict` into this ParamScheduler. Args: state_dict: a dict containing parameters.
load_state_dict
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def simulate_values( cls, num_events: int, schedulers: List[ParamScheduler], **kwargs: Any ) -> List[List[Union[List[float], float, int]]]: """Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. sche...
Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. schedulers: lr_scheduler object to wrap. kwargs: kwargs passed to construct an instance of :class:`ignite.handlers.param_scheduler.ParamGro...
simulate_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def simulate_values( # type: ignore[override] cls, num_events: int, metric_values: List[float], init_lr: float, **scheduler_kwargs: Any ) -> List[List[int]]: """Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulatio...
Method to simulate scheduled values during num_events events. Args: num_events: number of events during the simulation. metric_values: values to change LR based on. init_lr: initial LR to start with. scheduler_kwargs: kwargs passed to construct an instance of ...
simulate_values
python
pytorch/ignite
ignite/handlers/param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/param_scheduler.py
BSD-3-Clause
def attach( self, engine: Engine, event: Union[str, Events, CallableEventWithFilter, EventsList] = Events.ITERATION_COMPLETED, ) -> None: """Attach the handler to the engine. Once the handler is attached, the ``Engine.state`` will have a new attribute with the name ``param_na...
Attach the handler to the engine. Once the handler is attached, the ``Engine.state`` will have a new attribute with the name ``param_name``. Then the current value of the parameter can be retrieved from ``Engine.state`` when the engine is running. Args: engine: trainer to which the ...
attach
python
pytorch/ignite
ignite/handlers/state_param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/state_param_scheduler.py
BSD-3-Clause
def simulate_values(cls, num_events: int, **scheduler_kwargs: Any) -> List[List[int]]: """Method to simulate scheduled engine state parameter values during `num_events` events. Args: num_events: number of events during the simulation. scheduler_kwargs: parameter scheduler config...
Method to simulate scheduled engine state parameter values during `num_events` events. Args: num_events: number of events during the simulation. scheduler_kwargs: parameter scheduler configuration kwargs. Returns: event_index, value Examples: .. co...
simulate_values
python
pytorch/ignite
ignite/handlers/state_param_scheduler.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/state_param_scheduler.py
BSD-3-Clause
def attach(self, engine: Engine, name: Optional[str] = None) -> None: """Attaching `reset` method at EPOCH_STARTED and `update` method at ITERATION_COMPLETED. If `name` is passed, will store `self.data` on `engine.state` under `name`. """ engine.add_event_handler(Events....
Attaching `reset` method at EPOCH_STARTED and `update` method at ITERATION_COMPLETED. If `name` is passed, will store `self.data` on `engine.state` under `name`.
attach
python
pytorch/ignite
ignite/handlers/stores.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/stores.py
BSD-3-Clause
def attach(self, engine: Engine) -> None: """Attach BasicTimeProfiler to the given engine. Args: engine: the instance of Engine to attach """ if not isinstance(engine, Engine): raise TypeError(f"Argument engine should be ignite.engine.Engine, but given {type(engi...
Attach BasicTimeProfiler to the given engine. Args: engine: the instance of Engine to attach
attach
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def get_results(self) -> Dict[str, Dict[str, Any]]: """ Method to fetch the aggregated profiler results after the engine is run .. code-block:: python results = profiler.get_results() """ total_eh_time: Union[int, torch.Tensor] = sum( [(self.event_handl...
Method to fetch the aggregated profiler results after the engine is run .. code-block:: python results = profiler.get_results()
get_results
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def write_results(self, output_path: str) -> None: """ Method to store the unaggregated profiling results to a csv file Args: output_path: file output path containing a filename .. code-block:: python profiler.write_results('path_to_dir/awesome_filename.csv') ...
Method to store the unaggregated profiling results to a csv file Args: output_path: file output path containing a filename .. code-block:: python profiler.write_results('path_to_dir/awesome_filename.csv') Examples: .. code-block:: text ...
write_results
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def print_results(results: Dict) -> str: """ Method to print the aggregated results from the profiler Args: results: the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Examples: .. code-block:: t...
Method to print the aggregated results from the profiler Args: results: the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Examples: .. code-block:: text ------------------------------...
print_results
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def attach(self, engine: Engine) -> None: """Attach HandlersTimeProfiler to the given engine. Args: engine: the instance of Engine to attach """ if not isinstance(engine, Engine): raise TypeError(f"Argument engine should be ignite.engine.Engine, but given {type(e...
Attach HandlersTimeProfiler to the given engine. Args: engine: the instance of Engine to attach
attach
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def write_results(self, output_path: str) -> None: """ Method to store the unaggregated profiling results to a csv file Args: output_path: file output path containing a filename .. code-block:: python profiler.write_results('path_to_dir/awesome_filename.csv') ...
Method to store the unaggregated profiling results to a csv file Args: output_path: file output path containing a filename .. code-block:: python profiler.write_results('path_to_dir/awesome_filename.csv') Examples: .. code-block:: text ...
write_results
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def print_results(results: List[List[Union[str, float]]]) -> None: """ Method to print the aggregated results from the profiler Args: results: the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Examples: ...
Method to print the aggregated results from the profiler Args: results: the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Examples: .. code-block:: text -------------------------------...
print_results
python
pytorch/ignite
ignite/handlers/time_profilers.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/time_profilers.py
BSD-3-Clause
def attach( self, engine: Engine, start: Events = Events.STARTED, pause: Events = Events.COMPLETED, resume: Optional[Events] = None, step: Optional[Events] = None, ) -> "Timer": """Register callbacks to control the timer. Args: engine: Eng...
Register callbacks to control the timer. Args: engine: Engine that this timer will be attached to. start: Event which should start (reset) the timer. pause: Event which should pause the timer. resume: Event which should resume the timer. step: Event w...
attach
python
pytorch/ignite
ignite/handlers/timing.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/timing.py
BSD-3-Clause
def log_message(self, message: str) -> None: """ Logs a message, preserving the progress bar correct output format. Args: message: string you wish to log. """ from tqdm import tqdm tqdm.write(message, file=self.tqdm_kwargs.get("file", None))
Logs a message, preserving the progress bar correct output format. Args: message: string you wish to log.
log_message
python
pytorch/ignite
ignite/handlers/tqdm_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/tqdm_logger.py
BSD-3-Clause
def attach( # type: ignore[override] self, engine: Engine, metric_names: Optional[Union[str, List[str]]] = None, output_transform: Optional[Callable] = None, event_name: Union[Events, CallableEventWithFilter] = Events.ITERATION_COMPLETED, closing_event_name: Union[Events...
Attaches the progress bar to an engine object. Args: engine: engine object. metric_names: list of metric names to plot or a string "all" to plot all available metrics. output_transform: a function to select what you want to print from the engine's ...
attach
python
pytorch/ignite
ignite/handlers/tqdm_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/tqdm_logger.py
BSD-3-Clause
def global_step_from_engine(engine: Engine, custom_event_name: Optional[Events] = None) -> Callable: """Helper method to setup `global_step_transform` function using another engine. This can be helpful for logging trainer epoch/iteration while output handler is attached to an evaluator. Args: engin...
Helper method to setup `global_step_transform` function using another engine. This can be helpful for logging trainer epoch/iteration while output handler is attached to an evaluator. Args: engine: engine which state is used to provide the global step custom_event_name: registered event name. O...
global_step_from_engine
python
pytorch/ignite
ignite/handlers/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/utils.py
BSD-3-Clause
def add_scalar( self, logger: VisdomLogger, k: str, v: Union[str, float, torch.Tensor], event_name: Any, global_step: int ) -> None: """ Helper method to log a scalar with VisdomLogger. Args: logger: visdom logger k: scalar name which is used to set window ti...
Helper method to log a scalar with VisdomLogger. Args: logger: visdom logger k: scalar name which is used to set window title and y-axis label v: scalar value, y-axis value event_name: Event name which is used to setup x-axis label. Valid events are from...
add_scalar
python
pytorch/ignite
ignite/handlers/visdom_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/visdom_logger.py
BSD-3-Clause
def ClassificationReport( beta: int = 1, output_dict: bool = False, output_transform: Callable = lambda x: x, device: Union[str, torch.device] = torch.device("cpu"), is_multilabel: bool = False, labels: Optional[List[str]] = None, ) -> MetricsLambda: r"""Build a text report showing the main ...
Build a text report showing the main classification metrics. The report resembles in functionality to `scikit-learn classification_report <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html#sklearn.metrics.classification_report>`_ The underlying implementation doesn...
ClassificationReport
python
pytorch/ignite
ignite/metrics/classification_report.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/classification_report.py
BSD-3-Clause
def normalize(matrix: torch.Tensor, average: str) -> torch.Tensor: """Normalize given `matrix` with given `average`.""" if average == "recall": return matrix / (matrix.sum(dim=1).unsqueeze(1) + 1e-15) elif average == "precision": return matrix / (matrix.sum(dim=0) + 1e-15...
Normalize given `matrix` with given `average`.
normalize
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def IoU(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> MetricsLambda: r"""Calculates Intersection over Union using :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. .. math:: \text{J}(A, B) = \frac{ \lvert A \cap B \rvert }{ \lvert A \cup B \rvert } Args: cm: instance ...
Calculates Intersection over Union using :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. .. math:: \text{J}(A, B) = \frac{ \lvert A \cap B \rvert }{ \lvert A \cup B \rvert } Args: cm: instance of confusion matrix metric ignore_index: index to ignore, e.g. background index ...
IoU
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def cmAccuracy(cm: ConfusionMatrix) -> MetricsLambda: """Calculates accuracy using :class:`~ignite.metrics.metric.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric Returns: MetricsLambda """ # Increase floating point precision and pass to CPU cm = cm.to(tor...
Calculates accuracy using :class:`~ignite.metrics.metric.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric Returns: MetricsLambda
cmAccuracy
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def cmPrecision(cm: ConfusionMatrix, average: bool = True) -> MetricsLambda: """Calculates precision using :class:`~ignite.metrics.metric.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric average: if True metric value is averaged over all classes Returns: Metric...
Calculates precision using :class:`~ignite.metrics.metric.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric average: if True metric value is averaged over all classes Returns: MetricsLambda
cmPrecision
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def cmRecall(cm: ConfusionMatrix, average: bool = True) -> MetricsLambda: """ Calculates recall using :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric average: if True metric value is averaged over all classes Returns: ...
Calculates recall using :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric average: if True metric value is averaged over all classes Returns: MetricsLambda
cmRecall
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def DiceCoefficient(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> MetricsLambda: """Calculates Dice Coefficient for a given :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric ignore_index: index to ignore, e.g. backgroun...
Calculates Dice Coefficient for a given :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric. Args: cm: instance of confusion matrix metric ignore_index: index to ignore, e.g. background index Examples: For more information on how metric works with :class:`~ignite.engine.e...
DiceCoefficient
python
pytorch/ignite
ignite/metrics/confusion_matrix.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/confusion_matrix.py
BSD-3-Clause
def Fbeta( beta: float, average: bool = True, precision: Optional[Precision] = None, recall: Optional[Recall] = None, output_transform: Optional[Callable] = None, device: Optional[Union[str, torch.device]] = None, ) -> MetricsLambda: r"""Calculates F-beta score. .. math:: F_\bet...
Calculates F-beta score. .. math:: F_\beta = \left( 1 + \beta^2 \right) * \frac{ \text{precision} * \text{recall} } { \left( \beta^2 * \text{precision} \right) + \text{recall} } where :math:`\beta` is a positive real factor. - ``update`` must receive output of the form ``(y_pred, y)``. ...
Fbeta
python
pytorch/ignite
ignite/metrics/fbeta.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/fbeta.py
BSD-3-Clause
def __init__( self, rec_thresholds: Optional[Union[Sequence[float], torch.Tensor]] = None, class_mean: Optional[Literal["micro", "macro", "weighted"]] = "macro", ) -> None: r"""Base class for Average Precision metric. This class contains the methods for setting up the thresh...
Base class for Average Precision metric. This class contains the methods for setting up the thresholds and computing AP & AR. Args: rec_thresholds: recall thresholds (sensivity levels) to be considered for computing Mean Average Precision. It could be a 1-dim tensor or a se...
__init__
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def _compute_average_precision(self, recall: torch.Tensor, precision: torch.Tensor) -> torch.Tensor: """Measuring average precision. Args: recall: n-dimensional tensor whose last dimension represents confidence thresholds as much as #samples. Should be ordered in ascending order...
Measuring average precision. Args: recall: n-dimensional tensor whose last dimension represents confidence thresholds as much as #samples. Should be ordered in ascending order in its last dimension. precision: like ``recall`` in the shape. Returns: avera...
_compute_average_precision
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def _cat_and_agg_tensors( tensors: List[torch.Tensor], tensor_shape_except_last_dim: Tuple[int], dtype: torch.dtype, device: Union[str, torch.device], ) -> torch.Tensor: """ Concatenate tensors in ``tensors`` at their last dimension and gather all tensors from across all processes. All tenso...
Concatenate tensors in ``tensors`` at their last dimension and gather all tensors from across all processes. All tensors should have the same shape (denoted by ``tensor_shape_except_last_dim``) except at their last dimension.
_cat_and_agg_tensors
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def __init__( self, rec_thresholds: Optional[Union[Sequence[float], torch.Tensor]] = None, class_mean: Optional["Literal['micro', 'macro', 'weighted']"] = "macro", is_multilabel: bool = False, output_transform: Callable = lambda x: x, device: Union[str, torch.device] = to...
Calculate the mean average precision metric i.e. mean of the averaged-over-recall precision for classification task: .. math:: \text{Average Precision} = \sum_{k=1}^{\#rec\_thresholds} (r_k - r_{k-1}) P_k Mean average precision attempts to give a measure of detector or classifier p...
__init__
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def _prepare_output(self, output: Sequence[torch.Tensor]) -> Sequence[torch.Tensor]: """Prepares and returns ``y_pred`` and ``y`` tensors. Input and output shapes of the method is as follows. ``C`` and ``L`` denote the number of classes and labels in multiclass and multilabel inputs respectively. ...
Prepares and returns ``y_pred`` and ``y`` tensors. Input and output shapes of the method is as follows. ``C`` and ``L`` denote the number of classes and labels in multiclass and multilabel inputs respectively. ========== =========== ============ ``y_pred`` ------------------------------...
_prepare_output
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def update(self, output: Tuple[torch.Tensor, torch.Tensor]) -> None: """Metric update function using prediction and target. Args: output: a binary tuple consisting of prediction and target tensors This metric follows the same rules on ``output`` members shape as the ...
Metric update function using prediction and target. Args: output: a binary tuple consisting of prediction and target tensors This metric follows the same rules on ``output`` members shape as the :meth:`Precision.update <.metrics.precision.Precision.update>` except f...
update
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def _compute_recall_and_precision( self, y_true: torch.Tensor, y_pred: torch.Tensor, y_true_positive_count: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: r"""Measuring recall & precision. Shape of function inputs and return values follow the table below. N is the number of sa...
Measuring recall & precision. Shape of function inputs and return values follow the table below. N is the number of samples. \#unique scores represents number of unique scores in ``scores`` which is actually the number of thresholds. ===================== ==============================...
_compute_recall_and_precision
python
pytorch/ignite
ignite/metrics/mean_average_precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/mean_average_precision.py
BSD-3-Clause
def iteration_completed(self, engine: Engine) -> None: """Helper method to update metric's computation. It is automatically attached to the `engine` with :meth:`~ignite.metrics.metric.Metric.attach`. Args: engine: the engine to which the metric must be attached Note: ...
Helper method to update metric's computation. It is automatically attached to the `engine` with :meth:`~ignite.metrics.metric.Metric.attach`. Args: engine: the engine to which the metric must be attached Note: ``engine.state.output`` is used to compute metric values. ...
iteration_completed
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def completed(self, engine: Engine, name: str) -> None: """Helper method to compute metric's value and put into the engine. It is automatically attached to the `engine` with :meth:`~ignite.metrics.metric.Metric.attach`. If metrics' value is torch tensor, it is explicitly sent to CPU device. ...
Helper method to compute metric's value and put into the engine. It is automatically attached to the `engine` with :meth:`~ignite.metrics.metric.Metric.attach`. If metrics' value is torch tensor, it is explicitly sent to CPU device. Args: engine: the engine to which the metric must ...
completed
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def attach(self, engine: Engine, name: str, usage: Union[str, MetricUsage] = EpochWise()) -> None: """ Attaches current metric to provided engine. On the end of engine's run, `engine.state.metrics` dictionary will contain computed metric's value under provided name. Args: en...
Attaches current metric to provided engine. On the end of engine's run, `engine.state.metrics` dictionary will contain computed metric's value under provided name. Args: engine: the engine to which the metric must be attached name: the name of the metric to attach ...
attach
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def detach(self, engine: Engine, usage: Union[str, MetricUsage] = EpochWise()) -> None: """ Detaches current metric from the engine and no metric's computation is done during the run. This method in conjunction with :meth:`~ignite.metrics.metric.Metric.attach` can be useful if several me...
Detaches current metric from the engine and no metric's computation is done during the run. This method in conjunction with :meth:`~ignite.metrics.metric.Metric.attach` can be useful if several metrics need to be computed with different periods. For example, one metric is computed every trainin...
detach
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def is_attached(self, engine: Engine, usage: Union[str, MetricUsage] = EpochWise()) -> bool: """ Checks if current metric is attached to provided engine. If attached, metric's computed value is written to `engine.state.metrics` dictionary. Args: engine: the engine checked fr...
Checks if current metric is attached to provided engine. If attached, metric's computed value is written to `engine.state.metrics` dictionary. Args: engine: the engine checked from which the metric should be attached usage: the usage of the metric. Valid string values s...
is_attached
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def state_dict(self) -> OrderedDict: """Method returns state dict with attributes of the metric specified in its `_state_dict_all_req_keys` attribute. Can be used to save internal state of the class. """ state = self._state_dict_per_rank() if idist.get_world_size() > 1: ...
Method returns state dict with attributes of the metric specified in its `_state_dict_all_req_keys` attribute. Can be used to save internal state of the class.
state_dict
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Method replaces internal state of the class with provided state dict data. If there's an active distributed configuration, the process uses its rank to pick the proper value from the list of values saved under each attribute's name in t...
Method replaces internal state of the class with provided state dict data. If there's an active distributed configuration, the process uses its rank to pick the proper value from the list of values saved under each attribute's name in the dict. Args: state_dict: a dict containing a...
load_state_dict
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def sync_all_reduce(*attrs: Any) -> Callable: """Helper decorator for distributed configuration to collect instance attribute value across all participating processes and apply the specified reduction operation. See :doc:`metrics` on how to use it. Args: attrs: attribute names of decorated cla...
Helper decorator for distributed configuration to collect instance attribute value across all participating processes and apply the specified reduction operation. See :doc:`metrics` on how to use it. Args: attrs: attribute names of decorated class .. versionchanged:: 0.4.5 - Ability t...
sync_all_reduce
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def reinit__is_reduced(func: Callable) -> Callable: """Helper decorator for distributed configuration. See :doc:`metrics` on how to use it. Args: func: A callable to reinit. """ @wraps(func) def wrapper(self: Metric, *args: Any, **kwargs: Any) -> None: func(self, *args, **kwar...
Helper decorator for distributed configuration. See :doc:`metrics` on how to use it. Args: func: A callable to reinit.
reinit__is_reduced
python
pytorch/ignite
ignite/metrics/metric.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/metric.py
BSD-3-Clause
def reset(self) -> None: """ `numerator`, `denominator` and `weight` are three variables chosen to be abstract representatives of the ones that are measured for cases with different `average` parameters. `weight` is only used when `average='weighted'`. Actual value of these three variabl...
`numerator`, `denominator` and `weight` are three variables chosen to be abstract representatives of the ones that are measured for cases with different `average` parameters. `weight` is only used when `average='weighted'`. Actual value of these three variables is as follows. a...
reset
python
pytorch/ignite
ignite/metrics/precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/precision.py
BSD-3-Clause
def compute(self) -> Union[torch.Tensor, float]: r""" Return value of the metric for `average` options `'weighted'` and `'macro'` is computed as follows. .. math:: \text{Precision/Recall} = \frac{ numerator }{ denominator } \cdot weight wherein `weight` is the internal vari...
Return value of the metric for `average` options `'weighted'` and `'macro'` is computed as follows. .. math:: \text{Precision/Recall} = \frac{ numerator }{ denominator } \cdot weight wherein `weight` is the internal variable `_weight` for `'weighted'` option and :math:`1/C` ...
compute
python
pytorch/ignite
ignite/metrics/precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/precision.py
BSD-3-Clause
def update(self, output: Sequence[torch.Tensor]) -> None: r""" Update the metric state using prediction and target. Args: output: a binary tuple of tensors (y_pred, y) whose shapes follow the table below. N stands for the batch dimension, `...` for possible additiona...
Update the metric state using prediction and target. Args: output: a binary tuple of tensors (y_pred, y) whose shapes follow the table below. N stands for the batch dimension, `...` for possible additional dimensions and C for class dimension. .. list-table...
update
python
pytorch/ignite
ignite/metrics/precision.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/precision.py
BSD-3-Clause
def attach(self, engine: Engine, name: str, usage: Union[str, MetricUsage] = RunningBatchWise()) -> None: r""" Attach the metric to the ``engine`` using the events determined by the ``usage``. Args: engine: the engine to get attached to. name: by which, the metric is ins...
Attach the metric to the ``engine`` using the events determined by the ``usage``. Args: engine: the engine to get attached to. name: by which, the metric is inserted into ``engine.state.metrics`` dictionary. usage: the usage determining on which events the metric is...
attach
python
pytorch/ignite
ignite/metrics/running_average.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/running_average.py
BSD-3-Clause
def _get_covariance(self, sigma: torch.Tensor, total: torch.Tensor) -> torch.Tensor: r""" Calculates covariance from mean and sum of products of variables """ sub_matrix = torch_outer(total, total) sub_matrix = sub_matrix / self._num_examples return (sigma - sub_matrix)...
Calculates covariance from mean and sum of products of variables
_get_covariance
python
pytorch/ignite
ignite/metrics/gan/fid.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/gan/fid.py
BSD-3-Clause
def compute_ngram_scores(candidate: Sequence[Any], reference: Sequence[Any], n: int = 4) -> Score: """ Compute the score based on ngram co-occurence of sequences of items Args: candidate: candidate sequence of items reference: reference sequence of items n: ngram order Returns:...
Compute the score based on ngram co-occurence of sequences of items Args: candidate: candidate sequence of items reference: reference sequence of items n: ngram order Returns: The score containing the number of ngram co-occurences .. versionadded:: 0.4.5
compute_ngram_scores
python
pytorch/ignite
ignite/metrics/nlp/rouge.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/nlp/rouge.py
BSD-3-Clause
def compute_lcs_scores(candidate: Sequence[Any], reference: Sequence[Any]) -> Score: """ Compute the score based on longest common subsequence of sequences of items Args: candidate: candidate sequence of items reference: reference sequence of items Returns: The score containing...
Compute the score based on longest common subsequence of sequences of items Args: candidate: candidate sequence of items reference: reference sequence of items Returns: The score containing the length of longest common subsequence .. versionadded:: 0.4.5
compute_lcs_scores
python
pytorch/ignite
ignite/metrics/nlp/rouge.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/nlp/rouge.py
BSD-3-Clause
def lcs(seq_a: Sequence[Any], seq_b: Sequence[Any]) -> int: """ Compute the length of the longest common subsequence in two sequence of items https://en.wikipedia.org/wiki/Longest_common_subsequence_problem Args: seq_a: first sequence of items seq_b: second sequence of items Return...
Compute the length of the longest common subsequence in two sequence of items https://en.wikipedia.org/wiki/Longest_common_subsequence_problem Args: seq_a: first sequence of items seq_b: second sequence of items Returns: The length of the longest common subsequence .. ver...
lcs
python
pytorch/ignite
ignite/metrics/nlp/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/nlp/utils.py
BSD-3-Clause
def modified_precision(references: Sequence[Sequence[Any]], candidate: Any, n: int) -> Tuple[int, int]: """ Compute the modified precision .. math:: p_{n} = \frac{m_{n}}{l_{n}} where m_{n} is the number of matched n-grams between translation T and its reference R, and l_{n} is the total num...
Compute the modified precision .. math:: p_{n} = rac{m_{n}}{l_{n}} where m_{n} is the number of matched n-grams between translation T and its reference R, and l_{n} is the total number of n-grams in the translation T. More details can be found in `Papineni et al. 2002`__. __ https:/...
modified_precision
python
pytorch/ignite
ignite/metrics/nlp/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/nlp/utils.py
BSD-3-Clause
def coco_tensor_list_to_dict_list( output: Tuple[ Union[List[torch.Tensor], List[Dict[str, torch.Tensor]]], Union[List[torch.Tensor], List[Dict[str, torch.Tensor]]], ] ) -> Tuple[List[Dict[str, torch.Tensor]], List[Dict[str, torch.Tensor]]]: """Convert either of output's `y_pred` or `y` from...
Convert either of output's `y_pred` or `y` from list of `(N, 6)` tensors to list of str-to-tensor dictionaries, or keep them unchanged if they're already in the deisred format. Input format is a `(N, 6)` or (`N, 5)` tensor which `N` is the number of predicted/target bounding boxes for the image and the sec...
coco_tensor_list_to_dict_list
python
pytorch/ignite
ignite/metrics/vision/object_detection_average_precision_recall.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/vision/object_detection_average_precision_recall.py
BSD-3-Clause
def __init__( self, iou_thresholds: Optional[Union[Sequence[float], torch.Tensor]] = None, rec_thresholds: Optional[Union[Sequence[float], torch.Tensor]] = None, num_classes: int = 80, max_detections_per_image_per_class: int = 100, area_range: Literal["small", "medium", "...
Calculate mean average precision & recall for evaluating an object detector in the COCO way. Average precision is computed by averaging precision over increasing levels of recall thresholds. In COCO, the maximum precision across thresholds greater or equal a recall threshold is considered as t...
__init__
python
pytorch/ignite
ignite/metrics/vision/object_detection_average_precision_recall.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/vision/object_detection_average_precision_recall.py
BSD-3-Clause
def _compute_recall_and_precision( self, TP: torch.Tensor, FP: torch.Tensor, scores: torch.Tensor, y_true_count: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: r"""Measuring recall & precision This method is different from that of MeanAveragePrecision since in the pycocotools referenc...
Measuring recall & precision This method is different from that of MeanAveragePrecision since in the pycocotools reference implementation, when there are predictions with the same scores, they're considered associated with different thresholds in the course of measuring recall values, although ...
_compute_recall_and_precision
python
pytorch/ignite
ignite/metrics/vision/object_detection_average_precision_recall.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/vision/object_detection_average_precision_recall.py
BSD-3-Clause
def _compute_average_precision(self, recall: torch.Tensor, precision: torch.Tensor) -> torch.Tensor: """Measuring average precision. This method is overriden since :math:`1/#recall_thresholds` is used instead of :math:`r_k - r_{k-1}` as the recall differential in COCO's reference implementation ...
Measuring average precision. This method is overriden since :math:`1/#recall_thresholds` is used instead of :math:`r_k - r_{k-1}` as the recall differential in COCO's reference implementation i.e., pycocotools. Args: recall: n-dimensional tensor whose last dimension is the dimension...
_compute_average_precision
python
pytorch/ignite
ignite/metrics/vision/object_detection_average_precision_recall.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/vision/object_detection_average_precision_recall.py
BSD-3-Clause
def update(self, output: Tuple[List[Dict[str, torch.Tensor]], List[Dict[str, torch.Tensor]]]) -> None: r"""Metric update method using prediction and target. Args: output: a tuple, (y_pred, y), of two same-length lists, each one containing str-to-tensor dictionaries whose ite...
Metric update method using prediction and target. Args: output: a tuple, (y_pred, y), of two same-length lists, each one containing str-to-tensor dictionaries whose items is as follows. N\ :sub:`det` and N\ :sub:`gt` are number of detections and ground truths for a s...
update
python
pytorch/ignite
ignite/metrics/vision/object_detection_average_precision_recall.py
https://github.com/pytorch/ignite/blob/master/ignite/metrics/vision/object_detection_average_precision_recall.py
BSD-3-Clause
def pytest_addoption(parser): """ Add custom command line options for the ignite test suite here. See: This function is a pytest hook (due to its name) and is *"automatically" executed at the start of a test run https://docs.pytest.org/en/latest/reference/reference.html#initialization-hooks ...
Add custom command line options for the ignite test suite here. See: This function is a pytest hook (due to its name) and is *"automatically" executed at the start of a test run https://docs.pytest.org/en/latest/reference/reference.html#initialization-hooks * "automatically" is true provided t...
pytest_addoption
python
pytorch/ignite
tests/ignite/conftest.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/conftest.py
BSD-3-Clause
def pytest_configure(config): """ This function is a pytest hook (due to its name) and is run after command line parsing is complete in order to configure the test session. """ config.addinivalue_line("markers", "distributed: run distributed") config.addinivalue_line("markers", "multinode_distri...
This function is a pytest hook (due to its name) and is run after command line parsing is complete in order to configure the test session.
pytest_configure
python
pytorch/ignite
tests/ignite/conftest.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/conftest.py
BSD-3-Clause
def term_handler(): """ This allows the pytest session to be terminated upon retries on CI. It may be worth using this fixture solely in that context. For a discussion on whether sigterm should be ignored and why pytest usually ignores it see: https://github.com/pytest-dev/pytest/issues/5243 """...
This allows the pytest session to be terminated upon retries on CI. It may be worth using this fixture solely in that context. For a discussion on whether sigterm should be ignored and why pytest usually ignores it see: https://github.com/pytest-dev/pytest/issues/5243
term_handler
python
pytorch/ignite
tests/ignite/conftest.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/conftest.py
BSD-3-Clause
def local_rank(worker_id): """use a different account in each xdist worker""" if "gw" in worker_id: lrank = int(worker_id.replace("gw", "")) elif "master" == worker_id: lrank = 0 else: raise RuntimeError(f"Can not get rank from worker_id={worker_id}") os.environ["LOCAL_RANK...
use a different account in each xdist worker
local_rank
python
pytorch/ignite
tests/ignite/conftest.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/conftest.py
BSD-3-Clause
def pytest_sessionfinish(session, exitstatus): """ Any functionality that should be run at the end of the session should be added here. This is a pytest hook (due to its name) and is called after the whole test run finished, right before returning the exit status to the system. """ # If requ...
Any functionality that should be run at the end of the session should be added here. This is a pytest hook (due to its name) and is called after the whole test run finished, right before returning the exit status to the system.
pytest_sessionfinish
python
pytorch/ignite
tests/ignite/conftest.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/conftest.py
BSD-3-Clause
def _get_dummy_step_fn(model: Union[nn.Module, DataParallel, DistributedDataParallel]) -> Callable: """Get a dummy step function, given model is a (wrapper of) dummy model returned from _get_dummy_model""" def step_fn(engine, batch): """Increment the weight by 1 at each iteration""" _unwrap_mod...
Get a dummy step function, given model is a (wrapper of) dummy model returned from _get_dummy_model
_get_dummy_step_fn
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_has_momentum_scheduler(get_dummy_model): """Test the handler has attribute `momentum_scheduler` and `_momentum_lambda_obj`""" momentum_warmup = 0.0 warmup_iters = 10 ema_handler = EMAHandler(get_dummy_model(), momentum_warmup=momentum_warmup, warmup_iters=warmup_iters) assert hasattr(ema_ha...
Test the handler has attribute `momentum_scheduler` and `_momentum_lambda_obj`
test_has_momentum_scheduler
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_ema_warmup_func(get_dummy_model): """Test the built-in linear warmup function for the EMA momentum""" momentum = 0.5 momentum_warmup_1 = 0.0 momentum_warmup_2 = 1.0 warmup_iters = 5 def check_ema_momentum(engine: Engine, momentum_warmup, final_momentum, warmup_iters): if engine...
Test the built-in linear warmup function for the EMA momentum
test_ema_warmup_func
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_ema_ema_model_on_cuda(get_dummy_model): """Test if ema_handler.ema_model is nn.Module or nn.DataParallel and under eval mode""" model = get_dummy_model().to(idist.device()) model = idist.auto_model(model) ema_handler = EMAHandler(model) ema_model = ema_handler.ema_model assert not ema_m...
Test if ema_handler.ema_model is nn.Module or nn.DataParallel and under eval mode
test_ema_ema_model_on_cuda
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_ema_get_const_momentum(get_dummy_model): """Test if momentum retrieved from the engine is constant and equal to the handler's momentum""" model = get_dummy_model() step_fn = _get_dummy_step_fn(model) engine = Engine(step_fn) def assert_const_momentum(engine: Engine, const_momentum): ...
Test if momentum retrieved from the engine is constant and equal to the handler's momentum
test_ema_get_const_momentum
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_ema_buffer(handle_buffers): """Test if the tensors in buffer are also correctly updated""" model = nn.BatchNorm2d(2) model.running_mean.data.fill_(1.5) model.running_var.data.fill_(1.5) # manually register a buffer to test if it will be correctly updated model.register_buffer("dummy_bu...
Test if the tensors in buffer are also correctly updated
test_ema_buffer
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_ema_two_handlers(get_dummy_model): """Test when two EMA handlers are attached to a trainer""" model_1 = get_dummy_model() ema_handler_1 = EMAHandler(model_1, momentum=0.5) model_2 = get_dummy_model() ema_handler_2 = EMAHandler(model_2, momentum=0.5) def _step_fn(engine: Engine, batch:...
Test when two EMA handlers are attached to a trainer
test_ema_two_handlers
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def _test_ema_final_weight(model, device=None, ddp=False, interval=1): """Test if final smoothed weights are correct""" if device is None: # let horovod decide the device device = idist.device() if isinstance(device, str): device = torch.device(device) model = model.to(device) ...
Test if final smoothed weights are correct
_test_ema_final_weight
python
pytorch/ignite
tests/ignite/handlers/test_ema_handler.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/handlers/test_ema_handler.py
BSD-3-Clause
def test_metrics_lambda_update(): """ Test if the underlying metrics are updated """ y_pred = torch.randint(0, 2, size=(15, 10, 4)).float() y = torch.randint(0, 2, size=(15, 10, 4)).long() precision = Precision(average=False) recall = Recall(average=False) def Fbeta(r, p, beta): ...
Test if the underlying metrics are updated
test_metrics_lambda_update
python
pytorch/ignite
tests/ignite/metrics/test_metrics_lambda.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/test_metrics_lambda.py
BSD-3-Clause
def coco_val2017_sample() -> Tuple[List[Dict[str, torch.Tensor]], List[Dict[str, torch.Tensor]]]: """ Predictions are done using torchvision's `fasterrcnn_resnet50_fpn_v2` with the following snippet. Note that beforehand, COCO images and annotations were downloaded and unzipped into "val2017" and "annot...
Predictions are done using torchvision's `fasterrcnn_resnet50_fpn_v2` with the following snippet. Note that beforehand, COCO images and annotations were downloaded and unzipped into "val2017" and "annotations" folders respectively. .. code-block:: python import torch from torchvision....
coco_val2017_sample
python
pytorch/ignite
tests/ignite/metrics/vision/test_object_detection_map.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/vision/test_object_detection_map.py
BSD-3-Clause
def create_coco_api( predictions: List[Dict[str, torch.Tensor]], targets: List[Dict[str, torch.Tensor]] ) -> Tuple[COCO, COCO]: """Create COCO objects from predictions and targets Args: predictions: list of predictions. Each one is a dict containing "bbox", "scores" and "labels" as its keys. The ...
Create COCO objects from predictions and targets Args: predictions: list of predictions. Each one is a dict containing "bbox", "scores" and "labels" as its keys. The associated value to "bbox" is a tensor of shape (n, 4) where n stands for the number of detections. 4 represents top ...
create_coco_api
python
pytorch/ignite
tests/ignite/metrics/vision/test_object_detection_map.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/vision/test_object_detection_map.py
BSD-3-Clause
def pycoco_mAP(predictions: List[Dict[str, torch.Tensor]], targets: List[Dict[str, torch.Tensor]]) -> np.array: """ Returned values are AP@.5...95, AP@.5, AP@.75, AP-S, AP-M, AP-L, AR-1, AR-10, AR-100, AR-S, AR-M, AR-L """ coco_dt, coco_gt = create_coco_api(predictions, targets) eval = COCOeval(coco...
Returned values are AP@.5...95, AP@.5, AP@.75, AP-S, AP-M, AP-L, AR-1, AR-10, AR-100, AR-S, AR-M, AR-L
pycoco_mAP
python
pytorch/ignite
tests/ignite/metrics/vision/test_object_detection_map.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/vision/test_object_detection_map.py
BSD-3-Clause
def test_empty_data(available_device): """ Note that PyCOCO returns -1 when threre's no ground truth data. """ metric = ObjectDetectionAvgPrecisionRecall(device=available_device) assert metric._device == torch.device(available_device) metric.update( ( [{"bbox": torch.zeros((...
Note that PyCOCO returns -1 when threre's no ground truth data.
test_empty_data
python
pytorch/ignite
tests/ignite/metrics/vision/test_object_detection_map.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/vision/test_object_detection_map.py
BSD-3-Clause
def test_matching(available_device): """ PyCOCO matching rules: 1. The higher confidence in a prediction, the sooner decision is made for it. If there's equal confidence in two predictions, the dicision is first made for the one who comes earlier. 2. Each ground truth box...
PyCOCO matching rules: 1. The higher confidence in a prediction, the sooner decision is made for it. If there's equal confidence in two predictions, the dicision is first made for the one who comes earlier. 2. Each ground truth box is matched with at most one prediction. Cro...
test_matching
python
pytorch/ignite
tests/ignite/metrics/vision/test_object_detection_map.py
https://github.com/pytorch/ignite/blob/master/tests/ignite/metrics/vision/test_object_detection_map.py
BSD-3-Clause