diff --git a/ignite/engine/engine.py b/ignite/engine/engine.py index 2171618463f9..fcbb55ad423e 100644 --- a/ignite/engine/engine.py +++ b/ignite/engine/engine.py @@ -55,7 +55,7 @@ def log_training(engine): e = engine.state.epoch n = engine.state.max_epochs i = engine.state.iteration - print("Epoch {}/{} : {} - batch loss: {}, lr: {}".format(e, n, i, batch_loss, lr)) + print(f"Epoch {e}/{n} : {i} - batch loss: {batch_loss}, lr: {lr}") trainer.run(data_loader, max_epochs=5) @@ -218,13 +218,11 @@ class TBPTT_Events(EventEnum): # engine.state contains an attribute time_iteration, which can be accessed using engine.state.time_iteration """ if not (event_to_attr is None or isinstance(event_to_attr, dict)): - raise ValueError("Expected event_to_attr to be dictionary. Got {}.".format(type(event_to_attr))) + raise ValueError(f"Expected event_to_attr to be dictionary. Got {type(event_to_attr)}.") for index, e in enumerate(event_names): if not isinstance(e, (str, EventEnum)): - raise TypeError( - "Value at {} of event_names should be a str or EventEnum, but given {}".format(index, e) - ) + raise TypeError(f"Value at {index} of event_names should be a str or EventEnum, but given {e}") self._allowed_events.append(e) if event_to_attr and e in event_to_attr: State.event_to_attr[e] = event_to_attr[e] @@ -271,7 +269,7 @@ def add_event_handler(self, event_name: Any, handler: Callable, *args: Any, **kw engine = Engine(process_function) def print_epoch(engine): - print("Epoch: {}".format(engine.state.epoch)) + print(f"Epoch: {engine.state.epoch}") engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch) @@ -301,7 +299,7 @@ def execute_something(): if event_name not in self._allowed_events: self.logger.error("attempt to add event handler to an invalid event %s.", event_name) - raise ValueError("Event {} is not a valid event for this Engine.".format(event_name)) + raise ValueError(f"Event {event_name} is not a valid event for this Engine.") event_args = (Exception(),) if event_name == Events.EXCEPTION_RAISED else () try: @@ -359,7 +357,7 @@ def remove_event_handler(self, handler: Callable, event_name: Any) -> None: """ if event_name not in self._event_handlers: - raise ValueError("Input event name '{}' does not exist".format(event_name)) + raise ValueError(f"Input event name '{event_name}' does not exist") new_event_handlers = [ (h, args, kwargs) @@ -367,7 +365,7 @@ def remove_event_handler(self, handler: Callable, event_name: Any) -> None: if not self._compare_handlers(handler, h) ] if len(new_event_handlers) == len(self._event_handlers[event_name]): - raise ValueError("Input handler '{}' is not found among registered event handlers".format(handler)) + raise ValueError(f"Input handler '{handler}' is not found among registered event handlers") self._event_handlers[event_name] = new_event_handlers def on(self, event_name: Any, *args: Any, **kwargs: Any) -> Callable: @@ -387,7 +385,7 @@ def on(self, event_name: Any, *args: Any, **kwargs: Any) -> Callable: @engine.on(Events.EPOCH_COMPLETED) def print_epoch(): - print("Epoch: {}".format(engine.state.epoch)) + print(f"Epoch: {engine.state.epoch}") @engine.on(Events.EPOCH_COMPLETED | Events.COMPLETED) def execute_something(): @@ -533,9 +531,7 @@ def load_state_dict(self, state_dict: Mapping) -> None: for k in self._state_dict_user_keys: if k not in state_dict: raise ValueError( - "Required user state attribute '{}' is absent in provided state_dict '{}'".format( - k, state_dict.keys() - ) + f"Required user state attribute '{k}' is absent in provided state_dict '{state_dict.keys()}'" ) self.state.max_epochs = state_dict["max_epochs"] self.state.epoch_length = state_dict["epoch_length"] @@ -552,7 +548,7 @@ def load_state_dict(self, state_dict: Mapping) -> None: if self.state.epoch_length is None: raise ValueError( "If epoch is provided in the state dict, epoch_length should not be None. " - "Input state_dict: {}".format(state_dict) + f"Input state_dict: {state_dict}" ) self.state.iteration = self.state.epoch_length * self.state.epoch @@ -670,18 +666,14 @@ def switch_batch(engine): if max_epochs < self.state.epoch: raise ValueError( "Argument max_epochs should be larger than the start epoch " - "defined in the state: {} vs {}. Please, set engine.state.max_epochs = None " - "before calling engine.run() in order to restart the training from the beginning.".format( - max_epochs, self.state.epoch - ) + f"defined in the state: {max_epochs} vs {self.state.epoch}. Please, set engine.state.max_epochs = None " + "before calling engine.run() in order to restart the training from the beginning." ) self.state.max_epochs = max_epochs if epoch_length is not None: if epoch_length != self.state.epoch_length: raise ValueError( - "Argument epoch_length should be same as in the state, given {} vs {}".format( - epoch_length, self.state.epoch_length - ) + f"Argument epoch_length should be same as in the state, given {epoch_length} vs {self.state.epoch_length}" ) if self.state.max_epochs is None or self._is_done(self.state): @@ -708,12 +700,10 @@ def switch_batch(engine): self.state.max_epochs = max_epochs self.state.max_iters = max_iters self.state.epoch_length = epoch_length - self.logger.info("Engine run starting with max_epochs={}.".format(max_epochs)) + self.logger.info(f"Engine run starting with max_epochs={max_epochs}.") else: self.logger.info( - "Engine run resuming from iteration {}, epoch {} until {} epochs".format( - self.state.iteration, self.state.epoch, self.state.max_epochs - ) + f"Engine run resuming from iteration {self.state.iteration}, epoch {self.state.epoch} until {self.state.max_epochs} epochs" ) self.state.dataloader = data @@ -843,9 +833,7 @@ def _run_once_on_dataset(self) -> float: warnings.warn( "Data iterator can not provide data anymore but required total number of " "iterations to run is not reached. " - "Current iteration: {} vs Total iterations to run : {}".format( - self.state.iteration, total_iters, - ) + f"Current iteration: {self.state.iteration} vs Total iterations to run : {total_iters}" ) break diff --git a/ignite/engine/events.py b/ignite/engine/events.py index e05f477b2a82..4f07f5765082 100644 --- a/ignite/engine/events.py +++ b/ignite/engine/events.py @@ -315,7 +315,7 @@ def __init__(self) -> None: def _append(self, event: Union[Events, CallableEventWithFilter]) -> None: if not isinstance(event, (Events, CallableEventWithFilter)): - raise TypeError("Argument event should be Events or CallableEventWithFilter, got: {}".format(type(event))) + raise TypeError(f"Argument event should be Events or CallableEventWithFilter, got: {type(event)}") self._events.append(event) def __getitem__(self, item: int) -> Union[Events, CallableEventWithFilter]: @@ -392,7 +392,7 @@ def _update_attrs(self) -> None: def get_event_attrib_value(self, event_name: Union[str, Events, CallableEventWithFilter]) -> int: if event_name not in State.event_to_attr: - raise RuntimeError("Unknown event name '{}'".format(event_name)) + raise RuntimeError(f"Unknown event name '{event_name}'") return getattr(self, State.event_to_attr[event_name]) def __repr__(self) -> str: @@ -400,7 +400,7 @@ def __repr__(self) -> str: for attr, value in self.__dict__.items(): if not isinstance(value, (numbers.Number, str)): value = type(value) - s += "\t{}: {}\n".format(attr, value) + s += f"\t{attr}: {value}\n" return s @@ -424,7 +424,7 @@ class RemovableEventHandle: engine = Engine() def print_epoch(engine): - print("Epoch: {}".format(engine.state.epoch)) + print(f"Epoch: {engine.state.epoch}") with engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch): # print_epoch handler registered for a single run diff --git a/ignite/engine/utils.py b/ignite/engine/utils.py index 9c4c5b8d9846..d2c2d10d1ea5 100644 --- a/ignite/engine/utils.py +++ b/ignite/engine/utils.py @@ -15,7 +15,7 @@ def _check_signature(fn: Callable, fn_description: str, *args: Any, **kwargs: An exception_msg = str(exc) passed_params = list(args) + list(kwargs) raise ValueError( - "Error adding {} '{}': " - "takes parameters {} but will be called with {}" - "({}).".format(fn, fn_description, fn_params, passed_params, exception_msg) + f"Error adding {fn} '{fn_description}': " + f"takes parameters {fn_params} but will be called with {passed_params}" + f"({exception_msg})." ) diff --git a/ignite/handlers/checkpoint.py b/ignite/handlers/checkpoint.py index f3c419ee9dfb..994f89b0033c 100644 --- a/ignite/handlers/checkpoint.py +++ b/ignite/handlers/checkpoint.py @@ -251,7 +251,7 @@ def __init__( if to_save is not None: # for compatibility with ModelCheckpoint if not isinstance(to_save, collections.Mapping): - raise TypeError("Argument `to_save` should be a dictionary, but given {}".format(type(to_save))) + raise TypeError(f"Argument `to_save` should be a dictionary, but given {type(to_save)}") if len(to_save) < 1: raise ValueError("No objects to checkpoint.") @@ -261,11 +261,11 @@ def __init__( if include_self: if not isinstance(to_save, collections.MutableMapping): raise TypeError( - "If `include_self` is True, then `to_save` must be mutable, but given {}.".format(type(to_save)) + f"If `include_self` is True, then `to_save` must be mutable, but given {type(to_save)}." ) if "checkpointer" in to_save: - raise ValueError("Cannot have key 'checkpointer' if `include_self` is True: {}".format(to_save)) + raise ValueError(f"Cannot have key 'checkpointer' if `include_self` is True: {to_save}") if not (callable(save_handler) or isinstance(save_handler, BaseSaveHandler)): raise TypeError("Argument `save_handler` should be callable or inherit from BaseSaveHandler") @@ -274,9 +274,7 @@ def __init__( raise ValueError("If `score_name` is provided, then `score_function` " "should be also provided.") if global_step_transform is not None and not callable(global_step_transform): - raise TypeError( - "global_step_transform should be a function, got {} instead.".format(type(global_step_transform)) - ) + raise TypeError(f"global_step_transform should be a function, got {type(global_step_transform)} instead.") self.to_save = to_save self.filename_prefix = filename_prefix @@ -318,9 +316,7 @@ def __call__(self, engine: Engine) -> None: if self._check_lt_n_saved() or self._saved[0].priority < priority: - priority_str = ( - "{}".format(priority) if isinstance(priority, numbers.Integral) else "{:.4f}".format(priority) - ) + priority_str = f"{priority}" if isinstance(priority, numbers.Integral) else f"{priority:.4f}" checkpoint = self._setup_checkpoint() @@ -351,7 +347,7 @@ def __call__(self, engine: Engine) -> None: filename = filename_pattern.format(**filename_dict) metadata = { - "basename": "{}{}{}".format(self.filename_prefix, "_" * int(len(self.filename_prefix) > 0), name), + "basename": f"{self.filename_prefix}{'_' * int(len(self.filename_prefix) > 0)}{name}", "score_name": self.score_name, "priority": priority, } @@ -443,7 +439,7 @@ def setup_filename_pattern( def _check_objects(objs: Mapping, attr: str) -> None: for k, obj in objs.items(): if not hasattr(obj, attr): - raise TypeError("Object {} should have `{}` method".format(type(obj), attr)) + raise TypeError(f"Object {type(obj)} should have `{attr}` method") @staticmethod def load_objects(to_load: Mapping, checkpoint: Mapping, **kwargs: Any) -> None: @@ -488,7 +484,7 @@ def load_objects(to_load: Mapping, checkpoint: Mapping, **kwargs: Any) -> None: """ Checkpoint._check_objects(to_load, "load_state_dict") if not isinstance(checkpoint, collections.Mapping): - raise TypeError("Argument checkpoint should be a dictionary, but given {}".format(type(checkpoint))) + raise TypeError(f"Argument checkpoint should be a dictionary, but given {type(checkpoint)}") if len(kwargs) > 1 or any(k for k in kwargs.keys() if k not in ["strict"]): warnings.warn("kwargs contains keys other than strict and these will be ignored") @@ -506,7 +502,7 @@ def load_objects(to_load: Mapping, checkpoint: Mapping, **kwargs: Any) -> None: # multiple objects to load for k, obj in to_load.items(): if k not in checkpoint: - raise ValueError("Object labeled by '{}' from `to_load` is not found in the checkpoint".format(k)) + raise ValueError(f"Object labeled by '{k}' from `to_load` is not found in the checkpoint") if isinstance(obj, (nn.DataParallel, nn.parallel.DistributedDataParallel)): obj = obj.module if isinstance(obj, torch.nn.Module): @@ -552,16 +548,16 @@ def _check_and_setup(dirname: str, create_dir: bool, require_empty: bool) -> Non os.makedirs(dirname) # Ensure that dirname exists if not os.path.exists(dirname): - raise ValueError("Directory path '{}' is not found".format(dirname)) + raise ValueError(f"Directory path '{dirname}' is not found") if require_empty: matched = [fname for fname in os.listdir(dirname) if fname.endswith(".pt")] if len(matched) > 0: raise ValueError( - "Files {} with extension '.pt' are already present " - "in the directory {}. If you want to use this " + f"Files {matched} with extension '.pt' are already present " + f"in the directory {dirname}. If you want to use this " "directory anyway, pass `require_empty=False`." - "".format(matched, dirname) + "" ) def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None: @@ -709,7 +705,7 @@ def last_checkpoint(self) -> Union[str, None]: if not isinstance(self.save_handler, DiskSaver): raise RuntimeError( - "Unable to save checkpoint, save_handler should be DiskSaver, got {}.".format(type(self.save_handler)) + f"Unable to save checkpoint, save_handler should be DiskSaver, got {type(self.save_handler)}." ) return os.path.join(self.save_handler.dirname, self._saved[-1].filename) diff --git a/ignite/handlers/terminate_on_nan.py b/ignite/handlers/terminate_on_nan.py index d016d62657b9..9b54fbee2a2d 100644 --- a/ignite/handlers/terminate_on_nan.py +++ b/ignite/handlers/terminate_on_nan.py @@ -51,7 +51,5 @@ def raise_error(x: Union[float, torch.Tensor]) -> None: try: apply_to_type(output, (numbers.Number, torch.Tensor), raise_error) except RuntimeError: - self.logger.warning( - "{}: Output '{}' contains NaN or Inf. Stop training".format(self.__class__.__name__, output) - ) + self.logger.warning(f"{self.__class__.__name__}: Output '{output}' contains NaN or Inf. Stop training") engine.terminate() diff --git a/ignite/metrics/accumulation.py b/ignite/metrics/accumulation.py index b6c780ea272d..c26d1758d79f 100644 --- a/ignite/metrics/accumulation.py +++ b/ignite/metrics/accumulation.py @@ -46,7 +46,7 @@ def __init__( device: Union[str, torch.device] = torch.device("cpu"), ): if not callable(op): - raise TypeError("Argument op should be a callable, but given {}".format(type(op))) + raise TypeError(f"Argument op should be a callable, but given {type(op)}") self._op = op @@ -59,7 +59,7 @@ def reset(self) -> None: def _check_output_type(self, output: Union[float, torch.Tensor]) -> None: if not (isinstance(output, numbers.Number) or isinstance(output, torch.Tensor)): - raise TypeError("Output should be a number or torch.Tensor, but given {}".format(type(output))) + raise TypeError(f"Output should be a number or torch.Tensor, but given {type(output)}") @reinit__is_reduced def update(self, output: Union[float, torch.Tensor]) -> None: @@ -135,7 +135,7 @@ def _mean_op(a: Union[float, torch.Tensor], x: Union[float, torch.Tensor]) -> Un def compute(self) -> Union[float, torch.Tensor]: if self.num_examples < 1: raise NotComputableError( - "{} must have at least one example before it can be computed.".format(self.__class__.__name__) + f"{self.__class__.__name__} must have at least one example before it can be computed." ) return self.accumulator / self.num_examples @@ -186,7 +186,7 @@ def _geom_op(a: torch.Tensor, x: Union[float, torch.Tensor]) -> torch.Tensor: def compute(self) -> Union[float, torch.Tensor]: if self.num_examples < 1: raise NotComputableError( - "{} must have at least one example before it can be computed.".format(self.__class__.__name__) + f"{self.__class__.__name__} must have at least one example before it can be computed." ) tensor = torch.exp(self.accumulator / self.num_examples) diff --git a/ignite/metrics/accuracy.py b/ignite/metrics/accuracy.py index 47e357e62eda..25f8ad4a6f1b 100644 --- a/ignite/metrics/accuracy.py +++ b/ignite/metrics/accuracy.py @@ -31,7 +31,7 @@ def _check_shape(self, output: Sequence[torch.Tensor]) -> None: raise ValueError( "y must have shape of (batch_size, ...) and y_pred must have " "shape of (batch_size, num_categories, ...) or (batch_size, ...), " - "but given {} vs {}.".format(y.shape, y_pred.shape) + f"but given {y.shape} vs {y_pred.shape}." ) y_shape = y.shape @@ -78,19 +78,17 @@ def _check_type(self, output: Sequence[torch.Tensor]) -> None: num_classes = 1 else: raise RuntimeError( - "Invalid shapes of y (shape={}) and y_pred (shape={}), check documentation." - " for expected shapes of y and y_pred.".format(y.shape, y_pred.shape) + f"Invalid shapes of y (shape={y.shape}) and y_pred (shape={y_pred.shape}), check documentation." + " for expected shapes of y and y_pred." ) if self._type is None: self._type = update_type self._num_classes = num_classes else: if self._type != update_type: - raise RuntimeError("Input data type has changed from {} to {}.".format(self._type, update_type)) + raise RuntimeError(f"Input data type has changed from {self._type} to {update_type}.") if self._num_classes != num_classes: - raise ValueError( - "Input data number of classes has changed from {} to {}".format(self._num_classes, num_classes) - ) + raise ValueError(f"Input data number of classes has changed from {self._num_classes} to {num_classes}") class Accuracy(_BaseClassification): diff --git a/ignite/metrics/confusion_matrix.py b/ignite/metrics/confusion_matrix.py index c45fc6445681..8591b77a6b89 100644 --- a/ignite/metrics/confusion_matrix.py +++ b/ignite/metrics/confusion_matrix.py @@ -65,20 +65,18 @@ def _check_shape(self, output: Sequence[torch.Tensor]) -> None: y_pred, y = output[0].detach(), output[1].detach() if y_pred.ndimension() < 2: - raise ValueError( - "y_pred must have shape (batch_size, num_categories, ...), but given {}".format(y_pred.shape) - ) + raise ValueError(f"y_pred must have shape (batch_size, num_categories, ...), but given {y_pred.shape}") if y_pred.shape[1] != self.num_classes: raise ValueError( - "y_pred does not have correct number of categories: {} vs {}".format(y_pred.shape[1], self.num_classes) + f"y_pred does not have correct number of categories: {y_pred.shape[1]} vs {self.num_classes}" ) if not (y.ndimension() + 1 == y_pred.ndimension()): raise ValueError( "y_pred must have shape (batch_size, num_categories, ...) and y must have " "shape of (batch_size, ...), " - "but given {} vs {}.".format(y.shape, y_pred.shape) + f"but given {y.shape} vs {y_pred.shape}." ) y_shape = y.shape @@ -155,14 +153,14 @@ def IoU(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> MetricsLambd """ if not isinstance(cm, ConfusionMatrix): - raise TypeError("Argument cm should be instance of ConfusionMatrix, but given {}".format(type(cm))) + raise TypeError(f"Argument cm should be instance of ConfusionMatrix, but given {type(cm)}") if not (cm.average in (None, "samples")): raise ValueError("ConfusionMatrix should have average attribute either None or 'samples'") if ignore_index is not None: if not (isinstance(ignore_index, numbers.Integral) and 0 <= ignore_index < cm.num_classes): - raise ValueError("ignore_index should be non-negative integer, but given {}".format(ignore_index)) + raise ValueError(f"ignore_index should be non-negative integer, but given {ignore_index}") # Increase floating point precision and pass to CPU cm = cm.type(torch.DoubleTensor) @@ -172,9 +170,7 @@ def IoU(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> MetricsLambd def ignore_index_fn(iou_vector: torch.Tensor) -> torch.Tensor: if ignore_idx >= len(iou_vector): - raise ValueError( - "ignore_index {} is larger than the length of IoU vector {}".format(ignore_idx, len(iou_vector)) - ) + raise ValueError(f"ignore_index {ignore_idx} is larger than the length of IoU vector {len(iou_vector)}") indices = list(range(len(iou_vector))) indices.remove(ignore_idx) return iou_vector[indices] @@ -274,11 +270,11 @@ def DiceCoefficient(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> """ if not isinstance(cm, ConfusionMatrix): - raise TypeError("Argument cm should be instance of ConfusionMatrix, but given {}".format(type(cm))) + raise TypeError(f"Argument cm should be instance of ConfusionMatrix, but given {type(cm)}") if ignore_index is not None: if not (isinstance(ignore_index, numbers.Integral) and 0 <= ignore_index < cm.num_classes): - raise ValueError("ignore_index should be non-negative integer, but given {}".format(ignore_index)) + raise ValueError(f"ignore_index should be non-negative integer, but given {ignore_index}") # Increase floating point precision and pass to CPU cm = cm.type(torch.DoubleTensor) @@ -290,7 +286,7 @@ def DiceCoefficient(cm: ConfusionMatrix, ignore_index: Optional[int] = None) -> def ignore_index_fn(dice_vector: torch.Tensor) -> torch.Tensor: if ignore_idx >= len(dice_vector): raise ValueError( - "ignore_index {} is larger than the length of Dice vector {}".format(ignore_idx, len(dice_vector)) + f"ignore_index {ignore_idx} is larger than the length of Dice vector {len(dice_vector)}" ) indices = list(range(len(dice_vector))) indices.remove(ignore_idx) diff --git a/ignite/metrics/epoch_metric.py b/ignite/metrics/epoch_metric.py index f4f05d88e393..cc8f3ec4a7c0 100644 --- a/ignite/metrics/epoch_metric.py +++ b/ignite/metrics/epoch_metric.py @@ -88,15 +88,12 @@ def _check_type(self, output: Tuple[torch.Tensor, torch.Tensor]) -> None: dtype_preds = self._predictions[-1].dtype if dtype_preds != y_pred.dtype: raise ValueError( - "Incoherent types between input y_pred and stored predictions: " - "{} vs {}".format(dtype_preds, y_pred.dtype) + f"Incoherent types between input y_pred and stored predictions: {dtype_preds} vs {y_pred.dtype}" ) dtype_targets = self._targets[-1].dtype if dtype_targets != y.dtype: - raise ValueError( - "Incoherent types between input y and stored targets: {} vs {}".format(dtype_targets, y.dtype) - ) + raise ValueError(f"Incoherent types between input y and stored targets: {dtype_targets} vs {y.dtype}") @reinit__is_reduced def update(self, output: Tuple[torch.Tensor, torch.Tensor]) -> None: @@ -121,7 +118,7 @@ def update(self, output: Tuple[torch.Tensor, torch.Tensor]) -> None: try: self.compute_fn(self._predictions[0], self._targets[0]) except Exception as e: - warnings.warn("Probably, there can be a problem with `compute_fn`:\n {}.".format(e), EpochMetricWarning) + warnings.warn(f"Probably, there can be a problem with `compute_fn`:\n {e}.", EpochMetricWarning) def compute(self) -> float: if len(self._predictions) < 1 or len(self._targets) < 1: diff --git a/ignite/metrics/fbeta.py b/ignite/metrics/fbeta.py index 769c0febfc10..7083808eeb69 100644 --- a/ignite/metrics/fbeta.py +++ b/ignite/metrics/fbeta.py @@ -36,7 +36,7 @@ def Fbeta( MetricsLambda, F-beta metric """ if not (beta > 0): - raise ValueError("Beta should be a positive integer, but given {}".format(beta)) + raise ValueError(f"Beta should be a positive integer, but given {beta}") if precision is not None and output_transform is not None: raise ValueError("If precision argument is provided, output_transform should be None") diff --git a/ignite/metrics/metric.py b/ignite/metrics/metric.py index 000769f2779b..59dad2a7b39e 100644 --- a/ignite/metrics/metric.py +++ b/ignite/metrics/metric.py @@ -209,8 +209,8 @@ def __init__( # check if reset and update methods are decorated. Compute may not be decorated if not (hasattr(self.reset, "_decorated") and hasattr(self.update, "_decorated")): warnings.warn( - "{} class does not support distributed setting. Computed result is not collected " - "across all computing devices".format(self.__class__.__name__), + f"{self.__class__.__name__} class does not support distributed setting. Computed result is not collected " + "across all computing devices", RuntimeWarning, ) @@ -282,14 +282,12 @@ def iteration_completed(self, engine: Engine) -> None: if isinstance(output, Mapping): if self.required_output_keys is None: raise TypeError( - "Transformed engine output for {} metric should be a tuple/list, but given {}".format( - self.__class__.__name__, type(output) - ) + f"Transformed engine output for {self.__class__.__name__} metric should be a tuple/list, but given {type(output)}" ) if not all([k in output for k in self.required_output_keys]): raise ValueError( "When transformed engine's output is a mapping, " - "it should contain {} keys, but given {}".format(self.required_output_keys, list(output.keys())) + f"it should contain {self.required_output_keys} keys, but given {list(output.keys())}" ) output = tuple(output[k] for k in self.required_output_keys) self.update(output) @@ -305,9 +303,7 @@ def completed(self, engine: Engine, name: str) -> None: result = self.compute() if isinstance(result, Mapping): if name in result.keys(): - raise ValueError( - "Argument name '{}' is conflicting with mapping keys: {}".format(name, list(result.keys())) - ) + raise ValueError(f"Argument name '{name}' is conflicting with mapping keys: {list(result.keys())}") for key, value in result.items(): engine.state.metrics[key] = value @@ -325,11 +321,9 @@ def _check_usage(self, usage: Union[str, MetricUsage]) -> MetricUsage: elif usage == BatchWise.usage_name: usage = BatchWise() else: - raise ValueError( - "usage should be 'EpochWise.usage_name' or 'BatchWise.usage_name', get {}".format(usage) - ) + raise ValueError(f"usage should be 'EpochWise.usage_name' or 'BatchWise.usage_name', get {usage}") if not isinstance(usage, MetricUsage): - raise TypeError("Unhandled usage type {}".format(type(usage))) + raise TypeError(f"Unhandled usage type {type(usage)}") return usage def attach(self, engine: Engine, name: str, usage: Union[str, MetricUsage] = EpochWise()) -> None: diff --git a/ignite/metrics/precision.py b/ignite/metrics/precision.py index 1f390d5c4bfe..2955dfd73b11 100644 --- a/ignite/metrics/precision.py +++ b/ignite/metrics/precision.py @@ -51,7 +51,7 @@ def compute(self) -> Union[torch.Tensor, float]: is_scalar = not isinstance(self._positives, torch.Tensor) or self._positives.ndim == 0 if is_scalar and self._positives == 0: raise NotComputableError( - "{} must have at least one example before it can be computed.".format(self.__class__.__name__) + f"{self.__class__.__name__} must have at least one example before it can be computed." ) if not (self._type == "multilabel" and not self._average): @@ -149,8 +149,8 @@ def update(self, output: Sequence[torch.Tensor]) -> None: num_classes = y_pred.size(1) if y.max() + 1 > num_classes: raise ValueError( - "y_pred contains less classes than y. Number of predicted classes is {}" - " and element in y has invalid class = {}.".format(num_classes, y.max().item() + 1) + f"y_pred contains less classes than y. Number of predicted classes is {num_classes}" + f" and element in y has invalid class = {y.max().item() + 1}." ) y = to_onehot(y.view(-1), num_classes=num_classes) indices = torch.argmax(y_pred, dim=1).view(-1) diff --git a/ignite/metrics/recall.py b/ignite/metrics/recall.py index 19a087febb64..7d7dc29e477b 100644 --- a/ignite/metrics/recall.py +++ b/ignite/metrics/recall.py @@ -90,8 +90,8 @@ def update(self, output: Sequence[torch.Tensor]) -> None: num_classes = y_pred.size(1) if y.max() + 1 > num_classes: raise ValueError( - "y_pred contains less classes than y. Number of predicted classes is {}" - " and element in y has invalid class = {}.".format(num_classes, y.max().item() + 1) + f"y_pred contains less classes than y. Number of predicted classes is {num_classes}" + f" and element in y has invalid class = {y.max().item() + 1}." ) y = to_onehot(y.view(-1), num_classes=num_classes) indices = torch.argmax(y_pred, dim=1).view(-1) diff --git a/ignite/metrics/ssim.py b/ignite/metrics/ssim.py index 69a9e861f394..ed00c2cafe13 100644 --- a/ignite/metrics/ssim.py +++ b/ignite/metrics/ssim.py @@ -70,10 +70,10 @@ def __init__( raise ValueError("Argument sigma should be either float or a sequence of float.") if any(x % 2 == 0 or x <= 0 for x in self.kernel_size): - raise ValueError("Expected kernel_size to have odd positive number. Got {}.".format(kernel_size)) + raise ValueError(f"Expected kernel_size to have odd positive number. Got {kernel_size}.") if any(y <= 0 for y in self.sigma): - raise ValueError("Expected sigma to have positive number. Got {}.".format(sigma)) + raise ValueError(f"Expected sigma to have positive number. Got {sigma}.") super(SSIM, self).__init__(output_transform=output_transform, device=device) self.gaussian = gaussian @@ -124,19 +124,17 @@ def update(self, output: Sequence[torch.Tensor]) -> None: if y_pred.dtype != y.dtype: raise TypeError( - "Expected y_pred and y to have the same data type. Got y_pred: {} and y: {}.".format( - y_pred.dtype, y.dtype - ) + f"Expected y_pred and y to have the same data type. Got y_pred: {y_pred.dtype} and y: {y.dtype}." ) if y_pred.shape != y.shape: raise ValueError( - "Expected y_pred and y to have the same shape. Got y_pred: {} and y: {}.".format(y_pred.shape, y.shape) + f"Expected y_pred and y to have the same shape. Got y_pred: {y_pred.shape} and y: {y.shape}." ) if len(y_pred.shape) != 4 or len(y.shape) != 4: raise ValueError( - "Expected y_pred and y to have BxCxHxW shape. Got y_pred: {} and y: {}.".format(y_pred.shape, y.shape) + f"Expected y_pred and y to have BxCxHxW shape. Got y_pred: {y_pred.shape} and y: {y.shape}." ) channel = y_pred.size(1)