diff --git a/src/torchmetrics/audio/pesq.py b/src/torchmetrics/audio/pesq.py index 39af9f5e604..534a30f203b 100644 --- a/src/torchmetrics/audio/pesq.py +++ b/src/torchmetrics/audio/pesq.py @@ -72,8 +72,8 @@ class PerceptualEvaluationSpeechQuality(Metric): >>> g = torch.manual_seed(1) >>> preds = torch.randn(8000) >>> target = torch.randn(8000) - >>> nb_pesq = PerceptualEvaluationSpeechQuality(8000, 'nb') - >>> nb_pesq(preds, target) + >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb') + >>> pesq(preds, target) tensor(2.2076) >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb') >>> wb_pesq(preds, target) diff --git a/src/torchmetrics/classification/ranking.py b/src/torchmetrics/classification/ranking.py index c667b526fde..2a104641636 100644 --- a/src/torchmetrics/classification/ranking.py +++ b/src/torchmetrics/classification/ranking.py @@ -106,9 +106,9 @@ def update(self, preds: Tensor, target: Tensor) -> None: preds, target = _multilabel_confusion_matrix_format( preds, target, self.num_labels, threshold=0.0, ignore_index=self.ignore_index, should_threshold=False ) - measure, n_elements = _multilabel_coverage_error_update(preds, target) + measure, num_elements = _multilabel_coverage_error_update(preds, target) self.measure += measure - self.total += n_elements + self.total += num_elements def compute(self) -> Tensor: """Compute metric.""" @@ -226,9 +226,9 @@ def update(self, preds: Tensor, target: Tensor) -> None: preds, target = _multilabel_confusion_matrix_format( preds, target, self.num_labels, threshold=0.0, ignore_index=self.ignore_index, should_threshold=False ) - measure, n_elements = _multilabel_ranking_average_precision_update(preds, target) + measure, num_elements = _multilabel_ranking_average_precision_update(preds, target) self.measure += measure - self.total += n_elements + self.total += num_elements def compute(self) -> Tensor: """Compute metric.""" @@ -348,9 +348,9 @@ def update(self, preds: Tensor, target: Tensor) -> None: preds, target = _multilabel_confusion_matrix_format( preds, target, self.num_labels, threshold=0.0, ignore_index=self.ignore_index, should_threshold=False ) - measure, n_elements = _multilabel_ranking_loss_update(preds, target) + measure, num_elements = _multilabel_ranking_loss_update(preds, target) self.measure += measure - self.total += n_elements + self.total += num_elements def compute(self) -> Tensor: """Compute metric.""" diff --git a/src/torchmetrics/collections.py b/src/torchmetrics/collections.py index c1bbce0adb7..bb4eaae4f4a 100644 --- a/src/torchmetrics/collections.py +++ b/src/torchmetrics/collections.py @@ -232,7 +232,7 @@ def _merge_compute_groups(self) -> None: ``O(number_of_metrics_in_collection ** 2)``, as all metrics need to be compared to all other metrics. """ - n_groups = len(self._groups) + num_groups = len(self._groups) while True: for cg_idx1, cg_members1 in deepcopy(self._groups).items(): for cg_idx2, cg_members2 in deepcopy(self._groups).items(): @@ -247,13 +247,13 @@ def _merge_compute_groups(self) -> None: break # Start over if we merged groups - if len(self._groups) != n_groups: + if len(self._groups) != num_groups: break # Stop when we iterate over everything and do not merge any groups - if len(self._groups) == n_groups: + if len(self._groups) == num_groups: break - n_groups = len(self._groups) + num_groups = len(self._groups) # Re-index groups temp = deepcopy(self._groups) diff --git a/src/torchmetrics/detection/_mean_ap.py b/src/torchmetrics/detection/_mean_ap.py index b465697b287..bd9717ff73a 100644 --- a/src/torchmetrics/detection/_mean_ap.py +++ b/src/torchmetrics/detection/_mean_ap.py @@ -452,37 +452,43 @@ def _compute_iou(self, idx: int, class_id: int, max_det: int) -> Tensor: return compute_iou(det, gt, self.iou_type).to(self.device) def __evaluate_image_gt_no_preds( - self, gt: Tensor, gt_label_mask: Tensor, area_range: Tuple[int, int], nb_iou_thrs: int + self, gt: Tensor, gt_label_mask: Tensor, area_range: Tuple[int, int], num_iou_thrs: int ) -> Dict[str, Any]: """Evaluate images with a ground truth but no predictions.""" # GTs gt = [gt[i] for i in gt_label_mask] - nb_gt = len(gt) + num_gt = len(gt) areas = compute_area(gt, iou_type=self.iou_type).to(self.device) ignore_area = (areas < area_range[0]) | (areas > area_range[1]) gt_ignore, _ = torch.sort(ignore_area.to(torch.uint8)) gt_ignore = gt_ignore.to(torch.bool) # Detections - nb_det = 0 - det_ignore = torch.zeros((nb_iou_thrs, nb_det), dtype=torch.bool, device=self.device) + num_det = 0 + det_ignore = torch.zeros((num_iou_thrs, num_det), dtype=torch.bool, device=self.device) return { - "dtMatches": torch.zeros((nb_iou_thrs, nb_det), dtype=torch.bool, device=self.device), - "gtMatches": torch.zeros((nb_iou_thrs, nb_gt), dtype=torch.bool, device=self.device), - "dtScores": torch.zeros(nb_det, dtype=torch.float32, device=self.device), + "dtMatches": torch.zeros((num_iou_thrs, num_det), dtype=torch.bool, device=self.device), + "gtMatches": torch.zeros((num_iou_thrs, num_gt), dtype=torch.bool, device=self.device), + "dtScores": torch.zeros(num_det, dtype=torch.float32, device=self.device), "gtIgnore": gt_ignore, "dtIgnore": det_ignore, } def __evaluate_image_preds_no_gt( - self, det: Tensor, idx: int, det_label_mask: Tensor, max_det: int, area_range: Tuple[int, int], nb_iou_thrs: int + self, + det: Tensor, + idx: int, + det_label_mask: Tensor, + max_det: int, + area_range: Tuple[int, int], + num_iou_thrs: int, ) -> Dict[str, Any]: """Evaluate images with a prediction but no ground truth.""" # GTs - nb_gt = 0 + num_gt = 0 - gt_ignore = torch.zeros(nb_gt, dtype=torch.bool, device=self.device) + gt_ignore = torch.zeros(num_gt, dtype=torch.bool, device=self.device) # Detections @@ -494,15 +500,15 @@ def __evaluate_image_preds_no_gt( det = [det[i] for i in dtind] if len(det) > max_det: det = det[:max_det] - nb_det = len(det) + num_det = len(det) det_areas = compute_area(det, iou_type=self.iou_type).to(self.device) det_ignore_area = (det_areas < area_range[0]) | (det_areas > area_range[1]) - ar = det_ignore_area.reshape((1, nb_det)) - det_ignore = torch.repeat_interleave(ar, nb_iou_thrs, 0) + ar = det_ignore_area.reshape((1, num_det)) + det_ignore = torch.repeat_interleave(ar, num_iou_thrs, 0) return { - "dtMatches": torch.zeros((nb_iou_thrs, nb_det), dtype=torch.bool, device=self.device), - "gtMatches": torch.zeros((nb_iou_thrs, nb_gt), dtype=torch.bool, device=self.device), + "dtMatches": torch.zeros((num_iou_thrs, num_det), dtype=torch.bool, device=self.device), + "gtMatches": torch.zeros((num_iou_thrs, num_gt), dtype=torch.bool, device=self.device), "dtScores": scores_sorted.to(self.device), "gtIgnore": gt_ignore.to(self.device), "dtIgnore": det_ignore.to(self.device), @@ -535,15 +541,15 @@ def _evaluate_image( if len(gt_label_mask) == 0 and len(det_label_mask) == 0: return None - nb_iou_thrs = len(self.iou_thresholds) + num_iou_thrs = len(self.iou_thresholds) # Some GT but no predictions if len(gt_label_mask) > 0 and len(det_label_mask) == 0: - return self.__evaluate_image_gt_no_preds(gt, gt_label_mask, area_range, nb_iou_thrs) + return self.__evaluate_image_gt_no_preds(gt, gt_label_mask, area_range, num_iou_thrs) # Some predictions but no GT if len(gt_label_mask) == 0 and len(det_label_mask) > 0: - return self.__evaluate_image_preds_no_gt(det, idx, det_label_mask, max_det, area_range, nb_iou_thrs) + return self.__evaluate_image_preds_no_gt(det, idx, det_label_mask, max_det, area_range, num_iou_thrs) gt = [gt[i] for i in gt_label_mask] det = [det[i] for i in det_label_mask] @@ -574,13 +580,13 @@ def _evaluate_image( # load computed ious ious = ious[idx, class_id][:, gtind] if len(ious[idx, class_id]) > 0 else ious[idx, class_id] - nb_iou_thrs = len(self.iou_thresholds) - nb_gt = len(gt) - nb_det = len(det) - gt_matches = torch.zeros((nb_iou_thrs, nb_gt), dtype=torch.bool, device=self.device) - det_matches = torch.zeros((nb_iou_thrs, nb_det), dtype=torch.bool, device=self.device) + num_iou_thrs = len(self.iou_thresholds) + num_gt = len(gt) + num_det = len(det) + gt_matches = torch.zeros((num_iou_thrs, num_gt), dtype=torch.bool, device=self.device) + det_matches = torch.zeros((num_iou_thrs, num_det), dtype=torch.bool, device=self.device) gt_ignore = ignore_area_sorted - det_ignore = torch.zeros((nb_iou_thrs, nb_det), dtype=torch.bool, device=self.device) + det_ignore = torch.zeros((num_iou_thrs, num_det), dtype=torch.bool, device=self.device) if torch.numel(ious) > 0: for idx_iou, t in enumerate(self.iou_thresholds): @@ -595,9 +601,9 @@ def _evaluate_image( # set unmatched detections outside of area range to ignore det_areas = compute_area(det, iou_type=self.iou_type).to(self.device) det_ignore_area = (det_areas < area_range[0]) | (det_areas > area_range[1]) - ar = det_ignore_area.reshape((1, nb_det)) + ar = det_ignore_area.reshape((1, num_det)) det_ignore = torch.logical_or( - det_ignore, torch.logical_and(det_matches == 0, torch.repeat_interleave(ar, nb_iou_thrs, 0)) + det_ignore, torch.logical_and(det_matches == 0, torch.repeat_interleave(ar, num_iou_thrs, 0)) ) return { @@ -708,15 +714,15 @@ def _calculate(self, class_ids: List) -> Tuple[MAPMetricResults, MARMetricResult for img_id in img_ids ] - nb_iou_thrs = len(self.iou_thresholds) - nb_rec_thrs = len(self.rec_thresholds) - nb_classes = len(class_ids) - nb_bbox_areas = len(self.bbox_area_ranges) - nb_max_det_thrs = len(self.max_detection_thresholds) - nb_imgs = len(img_ids) - precision = -torch.ones((nb_iou_thrs, nb_rec_thrs, nb_classes, nb_bbox_areas, nb_max_det_thrs)) - recall = -torch.ones((nb_iou_thrs, nb_classes, nb_bbox_areas, nb_max_det_thrs)) - scores = -torch.ones((nb_iou_thrs, nb_rec_thrs, nb_classes, nb_bbox_areas, nb_max_det_thrs)) + num_iou_thrs = len(self.iou_thresholds) + num_rec_thrs = len(self.rec_thresholds) + num_classes = len(class_ids) + num_bbox_areas = len(self.bbox_area_ranges) + num_max_det_thrs = len(self.max_detection_thresholds) + num_imgs = len(img_ids) + precision = -torch.ones((num_iou_thrs, num_rec_thrs, num_classes, num_bbox_areas, num_max_det_thrs)) + recall = -torch.ones((num_iou_thrs, num_classes, num_bbox_areas, num_max_det_thrs)) + scores = -torch.ones((num_iou_thrs, num_rec_thrs, num_classes, num_bbox_areas, num_max_det_thrs)) # move tensors if necessary rec_thresholds_tensor = torch.tensor(self.rec_thresholds) @@ -735,8 +741,8 @@ def _calculate(self, class_ids: List) -> Tuple[MAPMetricResults, MARMetricResult eval_imgs=eval_imgs, rec_thresholds=rec_thresholds_tensor, max_det=max_det, - nb_imgs=nb_imgs, - nb_bbox_areas=nb_bbox_areas, + num_imgs=num_imgs, + num_bbox_areas=num_bbox_areas, ) return precision, recall @@ -787,14 +793,14 @@ def __calculate_recall_precision_scores( eval_imgs: list, rec_thresholds: Tensor, max_det: int, - nb_imgs: int, - nb_bbox_areas: int, + num_imgs: int, + num_bbox_areas: int, ) -> Tuple[Tensor, Tensor, Tensor]: - nb_rec_thrs = len(rec_thresholds) - idx_cls_pointer = idx_cls * nb_bbox_areas * nb_imgs - idx_bbox_area_pointer = idx_bbox_area * nb_imgs + num_rec_thrs = len(rec_thresholds) + idx_cls_pointer = idx_cls * num_bbox_areas * num_imgs + idx_bbox_area_pointer = idx_bbox_area * num_imgs # Load all image evals for current class_id and area_range - img_eval_cls_bbox = [eval_imgs[idx_cls_pointer + idx_bbox_area_pointer + i] for i in range(nb_imgs)] + img_eval_cls_bbox = [eval_imgs[idx_cls_pointer + idx_bbox_area_pointer + i] for i in range(num_imgs)] img_eval_cls_bbox = [e for e in img_eval_cls_bbox if e is not None] if not img_eval_cls_bbox: return recall, precision, scores @@ -824,8 +830,8 @@ def __calculate_recall_precision_scores( nd = len(tp) rc = tp / npig pr = tp / (fp + tp + torch.finfo(torch.float64).eps) - prec = torch.zeros((nb_rec_thrs,)) - score = torch.zeros((nb_rec_thrs,)) + prec = torch.zeros((num_rec_thrs,)) + score = torch.zeros((num_rec_thrs,)) recall[idx, idx_cls, idx_bbox_area, idx_max_det_thrs] = rc[-1] if nd else 0 @@ -837,7 +843,7 @@ def __calculate_recall_precision_scores( pr += diff inds = torch.searchsorted(rc, rec_thresholds.to(rc.device), right=False) - num_inds = inds.argmax() if inds.max() >= nd else nb_rec_thrs + num_inds = inds.argmax() if inds.max() >= nd else num_rec_thrs inds = inds[:num_inds] prec[:num_inds] = pr[inds] score[:num_inds] = det_scores_sorted[inds] diff --git a/src/torchmetrics/detection/panoptic_qualities.py b/src/torchmetrics/detection/panoptic_qualities.py index 387615f6cb4..b30dcd00c10 100644 --- a/src/torchmetrics/detection/panoptic_qualities.py +++ b/src/torchmetrics/detection/panoptic_qualities.py @@ -109,11 +109,11 @@ def __init__( self.allow_unknown_preds_category = allow_unknown_preds_category # per category intermediate metrics - n_categories = len(things) + len(stuffs) - self.add_state("iou_sum", default=torch.zeros(n_categories, dtype=torch.double), dist_reduce_fx="sum") - self.add_state("true_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") - self.add_state("false_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") - self.add_state("false_negatives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") + num_categories = len(things) + len(stuffs) + self.add_state("iou_sum", default=torch.zeros(num_categories, dtype=torch.double), dist_reduce_fx="sum") + self.add_state("true_positives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") + self.add_state("false_positives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") + self.add_state("false_negatives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") def update(self, preds: Tensor, target: Tensor) -> None: r"""Update state with predictions and targets. @@ -287,11 +287,11 @@ def __init__( self.allow_unknown_preds_category = allow_unknown_preds_category # per category intermediate metrics - n_categories = len(things) + len(stuffs) - self.add_state("iou_sum", default=torch.zeros(n_categories, dtype=torch.double), dist_reduce_fx="sum") - self.add_state("true_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") - self.add_state("false_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") - self.add_state("false_negatives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") + num_categories = len(things) + len(stuffs) + self.add_state("iou_sum", default=torch.zeros(num_categories, dtype=torch.double), dist_reduce_fx="sum") + self.add_state("true_positives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") + self.add_state("false_positives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") + self.add_state("false_negatives", default=torch.zeros(num_categories, dtype=torch.int), dist_reduce_fx="sum") def update(self, preds: Tensor, target: Tensor) -> None: r"""Update state with predictions and targets. diff --git a/src/torchmetrics/functional/audio/srmr.py b/src/torchmetrics/functional/audio/srmr.py index 35c259e279f..485c263e1dc 100644 --- a/src/torchmetrics/functional/audio/srmr.py +++ b/src/torchmetrics/functional/audio/srmr.py @@ -130,8 +130,8 @@ def _erb_filterbank(wave: Tensor, coefs: Tensor) -> Tensor: Tensor: shape [B, N, time] """ - n_batch, time = wave.shape - wave = wave.to(dtype=coefs.dtype).reshape(n_batch, 1, time) # [B, time] + num_batch, time = wave.shape + wave = wave.to(dtype=coefs.dtype).reshape(num_batch, 1, time) # [B, time] wave = wave.expand(-1, coefs.shape[0], -1) # [B, N, time] gain = coefs[:, 9] @@ -250,7 +250,7 @@ def speech_reverberation_modulation_energy_ratio( ) shape = preds.shape preds = preds.reshape(1, -1) if len(shape) == 1 else preds.reshape(-1, shape[-1]) - n_batch, time = preds.shape + num_batch, time = preds.shape # convert int type to float if not torch.is_floating_point(preds): preds = preds.to(torch.float64) / torch.finfo(preds.dtype).max @@ -272,7 +272,7 @@ def speech_reverberation_modulation_energy_ratio( mfs = 400.0 temp = [] preds_np = preds.detach().cpu().numpy() - for b in range(n_batch): + for b in range(num_batch): gt_env_b = fft_gtgram(preds_np[b], fs, 0.010, 0.0025, n_cochlear_filters, low_freq) temp.append(torch.tensor(gt_env_b)) gt_env = torch.stack(temp, dim=0).to(device=preds.device) @@ -291,7 +291,7 @@ def speech_reverberation_modulation_energy_ratio( min_cf, max_cf, n=8, fs=mfs, q=2, device=preds.device ) - n_frames = int(1 + (time - w_length) // w_inc) + num_frames = int(1 + (time - w_length) // w_inc) w = torch.hamming_window(w_length + 1, dtype=torch.float64, device=preds.device)[:-1] mod_out = lfilter( gt_env.unsqueeze(-2).expand(-1, -1, mf.shape[0], -1), mf[:, 1, :], mf[:, 0, :], clamp=False, batching=True @@ -300,7 +300,7 @@ def speech_reverberation_modulation_energy_ratio( padding = (0, max(ceil(time / w_inc) * w_inc - time, w_length - time)) mod_out_pad = pad(mod_out, pad=padding, mode="constant", value=0) mod_out_frame = mod_out_pad.unfold(-1, w_length, w_inc) - energy = ((mod_out_frame[..., :n_frames, :] * w) ** 2).sum(dim=-1) # [B, N_filters, 8, n_frames] + energy = ((mod_out_frame[..., :num_frames, :] * w) ** 2).sum(dim=-1) # [B, N_filters, 8, n_frames] if norm: energy = _normalize_energy(energy) @@ -308,7 +308,7 @@ def speech_reverberation_modulation_energy_ratio( erbs = torch.flipud(_calc_erbs(low_freq, fs, n_cochlear_filters, device=preds.device)) avg_energy = torch.mean(energy, dim=-1) - total_energy = torch.sum(avg_energy.reshape(n_batch, -1), dim=-1) + total_energy = torch.sum(avg_energy.reshape(num_batch, -1), dim=-1) ac_energy = torch.sum(avg_energy, dim=2) ac_perc = ac_energy * 100 / total_energy.reshape(-1, 1) ac_perc_cumsum = ac_perc.flip(-1).cumsum(-1) @@ -316,7 +316,7 @@ def speech_reverberation_modulation_energy_ratio( bw = erbs[k90perc_idx] temp = [] - for b in range(n_batch): + for b in range(num_batch): score = _cal_srmr_score(bw[b], avg_energy[b], cutoffs=cutoffs) temp.append(score) score = torch.stack(temp) diff --git a/src/torchmetrics/functional/classification/cohen_kappa.py b/src/torchmetrics/functional/classification/cohen_kappa.py index 94a3d3bad30..7cf63a24e7e 100644 --- a/src/torchmetrics/functional/classification/cohen_kappa.py +++ b/src/torchmetrics/functional/classification/cohen_kappa.py @@ -33,18 +33,18 @@ def _cohen_kappa_reduce(confmat: Tensor, weights: Optional[Literal["linear", "quadratic", "none"]] = None) -> Tensor: """Reduce an un-normalized confusion matrix of shape (n_classes, n_classes) into the cohen kappa score.""" confmat = confmat.float() if not confmat.is_floating_point() else confmat - n_classes = confmat.shape[0] + num_classes = confmat.shape[0] sum0 = confmat.sum(dim=0, keepdim=True) sum1 = confmat.sum(dim=1, keepdim=True) expected = sum1 @ sum0 / sum0.sum() # outer product if weights is None or weights == "none": w_mat = torch.ones_like(confmat).flatten() - w_mat[:: n_classes + 1] = 0 - w_mat = w_mat.reshape(n_classes, n_classes) + w_mat[:: num_classes + 1] = 0 + w_mat = w_mat.reshape(num_classes, num_classes) elif weights in ("linear", "quadratic"): w_mat = torch.zeros_like(confmat) - w_mat += torch.arange(n_classes, dtype=w_mat.dtype, device=w_mat.device) + w_mat += torch.arange(num_classes, dtype=w_mat.dtype, device=w_mat.device) w_mat = torch.abs(w_mat - w_mat.T) if weights == "linear" else torch.pow(w_mat - w_mat.T, 2.0) else: raise ValueError( diff --git a/src/torchmetrics/functional/classification/ranking.py b/src/torchmetrics/functional/classification/ranking.py index 613abce1f50..c49003d418d 100644 --- a/src/torchmetrics/functional/classification/ranking.py +++ b/src/torchmetrics/functional/classification/ranking.py @@ -33,8 +33,8 @@ def _rank_data(x: Tensor) -> Tensor: return ranks[inverse] -def _ranking_reduce(score: Tensor, n_elements: int) -> Tensor: - return score / n_elements +def _ranking_reduce(score: Tensor, num_elements: int) -> Tensor: + return score / num_elements def _multilabel_ranking_tensor_validation( @@ -115,17 +115,17 @@ def _multilabel_ranking_average_precision_update(preds: Tensor, target: Tensor) neg_preds = -preds score = torch.tensor(0.0, device=neg_preds.device) - n_preds, n_labels = neg_preds.shape - for i in range(n_preds): + num_preds, num_labels = neg_preds.shape + for i in range(num_preds): relevant = target[i] == 1 ranking = _rank_data(neg_preds[i][relevant]).float() - if len(ranking) > 0 and len(ranking) < n_labels: + if len(ranking) > 0 and len(ranking) < num_labels: rank = _rank_data(neg_preds[i])[relevant].float() score_idx = (ranking / rank).mean() else: score_idx = torch.ones_like(score) score += score_idx - return score, n_preds + return score, num_preds def multilabel_ranking_average_precision( @@ -178,8 +178,8 @@ def multilabel_ranking_average_precision( preds, target = _multilabel_confusion_matrix_format( preds, target, num_labels, threshold=0.0, ignore_index=ignore_index, should_threshold=False ) - score, n_elements = _multilabel_ranking_average_precision_update(preds, target) - return _ranking_reduce(score, n_elements) + score, num_elements = _multilabel_ranking_average_precision_update(preds, target) + return _ranking_reduce(score, num_elements) def _multilabel_ranking_loss_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, int]: @@ -191,26 +191,26 @@ def _multilabel_ranking_loss_update(preds: Tensor, target: Tensor) -> Tuple[Tens sample_weight: optional tensor with weight for each sample """ - n_preds, n_labels = preds.shape + num_preds, num_labels = preds.shape relevant = target == 1 - n_relevant = relevant.sum(dim=1) + num_relevant = relevant.sum(dim=1) # Ignore instances where number of true labels is 0 or n_labels - mask = (n_relevant > 0) & (n_relevant < n_labels) + mask = (num_relevant > 0) & (num_relevant < num_labels) preds = preds[mask] relevant = relevant[mask] - n_relevant = n_relevant[mask] + num_relevant = num_relevant[mask] # Nothing is relevant if len(preds) == 0: return torch.tensor(0.0, device=preds.device), 1 inverse = preds.argsort(dim=1).argsort(dim=1) - per_label_loss = ((n_labels - inverse) * relevant).to(torch.float32) - correction = 0.5 * n_relevant * (n_relevant + 1) - denom = n_relevant * (n_labels - n_relevant) + per_label_loss = ((num_labels - inverse) * relevant).to(torch.float32) + correction = 0.5 * num_relevant * (num_relevant + 1) + denom = num_relevant * (num_labels - num_relevant) loss = (per_label_loss.sum(dim=1) - correction) / denom - return loss.sum(), n_preds + return loss.sum(), num_preds def multilabel_ranking_loss( @@ -263,5 +263,5 @@ def multilabel_ranking_loss( preds, target = _multilabel_confusion_matrix_format( preds, target, num_labels, threshold=0.0, ignore_index=ignore_index, should_threshold=False ) - loss, n_elements = _multilabel_ranking_loss_update(preds, target) - return _ranking_reduce(loss, n_elements) + loss, num_elements = _multilabel_ranking_loss_update(preds, target) + return _ranking_reduce(loss, num_elements) diff --git a/src/torchmetrics/functional/classification/stat_scores.py b/src/torchmetrics/functional/classification/stat_scores.py index f0afe9b3fab..8efbfdf2e1e 100644 --- a/src/torchmetrics/functional/classification/stat_scores.py +++ b/src/torchmetrics/functional/classification/stat_scores.py @@ -842,10 +842,10 @@ def _drop_negative_ignored_indices( """ if mode == mode.MULTIDIM_MULTICLASS and preds.dtype == torch.float: # In case or multi-dimensional multi-class with logits - n_dims = len(preds.shape) + num_dims = len(preds.shape) num_classes = preds.shape[1] # move class dim to last so that we can flatten the additional dimensions into N: [N, C, ...] -> [N, ..., C] - preds = preds.transpose(1, n_dims - 1) + preds = preds.transpose(1, num_dims - 1) # flatten: [N, ..., C] -> [N', C] preds = preds.reshape(-1, num_classes) diff --git a/src/torchmetrics/functional/clustering/calinski_harabasz_score.py b/src/torchmetrics/functional/clustering/calinski_harabasz_score.py index 5634dbb2fab..2c934dfd44d 100644 --- a/src/torchmetrics/functional/clustering/calinski_harabasz_score.py +++ b/src/torchmetrics/functional/clustering/calinski_harabasz_score.py @@ -44,14 +44,14 @@ def calinski_harabasz_score(data: Tensor, labels: Tensor) -> Tensor: # convert to zero indexed labels unique_labels, labels = torch.unique(labels, return_inverse=True) - n_labels = len(unique_labels) - n_samples = data.shape[0] - _validate_intrinsic_labels_to_samples(n_labels, n_samples) + num_labels = len(unique_labels) + num_samples = data.shape[0] + _validate_intrinsic_labels_to_samples(num_labels, num_samples) mean = data.mean(dim=0) between_cluster_dispersion = torch.tensor(0.0, device=data.device) within_cluster_dispersion = torch.tensor(0.0, device=data.device) - for k in range(n_labels): + for k in range(num_labels): cluster_k = data[labels == k, :] mean_k = cluster_k.mean(dim=0) between_cluster_dispersion += ((mean_k - mean) ** 2).sum() * cluster_k.shape[0] @@ -59,4 +59,4 @@ def calinski_harabasz_score(data: Tensor, labels: Tensor) -> Tensor: if within_cluster_dispersion == 0: return torch.tensor(1.0, device=data.device, dtype=torch.float32) - return between_cluster_dispersion * (n_samples - n_labels) / (within_cluster_dispersion * (n_labels - 1.0)) + return between_cluster_dispersion * (num_samples - num_labels) / (within_cluster_dispersion * (num_labels - 1.0)) diff --git a/src/torchmetrics/functional/clustering/davies_bouldin_score.py b/src/torchmetrics/functional/clustering/davies_bouldin_score.py index d4854ac3ef4..cc3e530d7d9 100644 --- a/src/torchmetrics/functional/clustering/davies_bouldin_score.py +++ b/src/torchmetrics/functional/clustering/davies_bouldin_score.py @@ -44,13 +44,13 @@ def davies_bouldin_score(data: Tensor, labels: Tensor) -> Tensor: # convert to zero indexed labels unique_labels, labels = torch.unique(labels, return_inverse=True) - n_labels = len(unique_labels) - n_samples, dim = data.shape - _validate_intrinsic_labels_to_samples(n_labels, n_samples) + num_labels = len(unique_labels) + num_samples, dim = data.shape + _validate_intrinsic_labels_to_samples(num_labels, num_samples) - intra_dists = torch.zeros(n_labels, device=data.device) - centroids = torch.zeros((n_labels, dim), device=data.device) - for k in range(n_labels): + intra_dists = torch.zeros(num_labels, device=data.device) + centroids = torch.zeros((num_labels, dim), device=data.device) + for k in range(num_labels): cluster_k = data[labels == k, :] centroids[k] = cluster_k.mean(dim=0) intra_dists[k] = (cluster_k - centroids[k]).pow(2.0).sum(dim=1).sqrt().mean() diff --git a/src/torchmetrics/functional/clustering/utils.py b/src/torchmetrics/functional/clustering/utils.py index 463bf675c60..8588c305742 100644 --- a/src/torchmetrics/functional/clustering/utils.py +++ b/src/torchmetrics/functional/clustering/utils.py @@ -150,8 +150,8 @@ def calculate_contingency_matrix( preds_classes, preds_idx = torch.unique(preds, return_inverse=True) target_classes, target_idx = torch.unique(target, return_inverse=True) - n_classes_preds = preds_classes.size(0) - n_classes_target = target_classes.size(0) + num_classes_preds = preds_classes.size(0) + num_classes_target = target_classes.size(0) contingency = torch.sparse_coo_tensor( torch.stack( @@ -162,8 +162,8 @@ def calculate_contingency_matrix( ), torch.ones(target_idx.shape[0], dtype=preds_idx.dtype, device=preds_idx.device), ( - n_classes_target, - n_classes_preds, + num_classes_target, + num_classes_preds, ), ) @@ -205,12 +205,12 @@ def _validate_intrinsic_cluster_data(data: Tensor, labels: Tensor) -> None: raise ValueError(f"Expected 1D labels, got {labels.ndim}D labels instead") -def _validate_intrinsic_labels_to_samples(n_labels: int, n_samples: int) -> None: +def _validate_intrinsic_labels_to_samples(num_labels: int, num_samples: int) -> None: """Validate that the number of labels are in the correct range.""" - if not 1 < n_labels < n_samples: + if not 1 < num_labels < num_samples: raise ValueError( "Number of detected clusters must be greater than one and less than the number of samples." - f"Got {n_labels} clusters and {n_samples} samples." + f"Got {num_labels} clusters and {num_samples} samples." ) @@ -271,14 +271,14 @@ def calcualte_pair_cluster_confusion_matrix( if contingency is None: raise ValueError("Must provide `contingency` if `preds` and `target` are not provided.") - n_samples = contingency.sum() - n_c = contingency.sum(dim=1) - n_k = contingency.sum(dim=0) + num_samples = contingency.sum() + sum_c = contingency.sum(dim=1) + sum_k = contingency.sum(dim=0) sum_squared = (contingency**2).sum() pair_matrix = torch.zeros(2, 2, dtype=contingency.dtype, device=contingency.device) - pair_matrix[1, 1] = sum_squared - n_samples - pair_matrix[1, 0] = (contingency * n_k).sum() - sum_squared - pair_matrix[0, 1] = (contingency.T * n_c).sum() - sum_squared - pair_matrix[0, 0] = n_samples**2 - pair_matrix[0, 1] - pair_matrix[1, 0] - sum_squared + pair_matrix[1, 1] = sum_squared - num_samples + pair_matrix[1, 0] = (contingency * sum_k).sum() - sum_squared + pair_matrix[0, 1] = (contingency.T * sum_c).sum() - sum_squared + pair_matrix[0, 0] = num_samples**2 - pair_matrix[0, 1] - pair_matrix[1, 0] - sum_squared return pair_matrix diff --git a/src/torchmetrics/functional/detection/_panoptic_quality_common.py b/src/torchmetrics/functional/detection/_panoptic_quality_common.py index 8573d7f070f..9361039a7c4 100644 --- a/src/torchmetrics/functional/detection/_panoptic_quality_common.py +++ b/src/torchmetrics/functional/detection/_panoptic_quality_common.py @@ -343,11 +343,11 @@ def _panoptic_quality_update_sample( """ stuffs_modified_metric = stuffs_modified_metric or set() device = flatten_preds.device - n_categories = len(cat_id_to_continuous_id) - iou_sum = torch.zeros(n_categories, dtype=torch.double, device=device) - true_positives = torch.zeros(n_categories, dtype=torch.int, device=device) - false_positives = torch.zeros(n_categories, dtype=torch.int, device=device) - false_negatives = torch.zeros(n_categories, dtype=torch.int, device=device) + num_categories = len(cat_id_to_continuous_id) + iou_sum = torch.zeros(num_categories, dtype=torch.double, device=device) + true_positives = torch.zeros(num_categories, dtype=torch.int, device=device) + false_positives = torch.zeros(num_categories, dtype=torch.int, device=device) + false_negatives = torch.zeros(num_categories, dtype=torch.int, device=device) # calculate the area of each prediction, ground truth and pairwise intersection. # NOTE: mypy needs `cast()` because the annotation for `_get_color_areas` is too generic. @@ -421,11 +421,11 @@ def _panoptic_quality_update( """ device = flatten_preds.device - n_categories = len(cat_id_to_continuous_id) - iou_sum = torch.zeros(n_categories, dtype=torch.double, device=device) - true_positives = torch.zeros(n_categories, dtype=torch.int, device=device) - false_positives = torch.zeros(n_categories, dtype=torch.int, device=device) - false_negatives = torch.zeros(n_categories, dtype=torch.int, device=device) + num_categories = len(cat_id_to_continuous_id) + iou_sum = torch.zeros(num_categories, dtype=torch.double, device=device) + true_positives = torch.zeros(num_categories, dtype=torch.int, device=device) + false_positives = torch.zeros(num_categories, dtype=torch.int, device=device) + false_negatives = torch.zeros(num_categories, dtype=torch.int, device=device) # Loop over each sample independently: segments must not be matched across frames. for flatten_preds_single, flatten_target_single in zip(flatten_preds, flatten_target): diff --git a/src/torchmetrics/functional/image/psnr.py b/src/torchmetrics/functional/image/psnr.py index c7e52551e93..d4b12ff94bd 100644 --- a/src/torchmetrics/functional/image/psnr.py +++ b/src/torchmetrics/functional/image/psnr.py @@ -22,7 +22,7 @@ def _psnr_compute( sum_squared_error: Tensor, - n_obs: Tensor, + num_obs: Tensor, data_range: Tensor, base: float = 10.0, reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean", @@ -31,7 +31,7 @@ def _psnr_compute( Args: sum_squared_error: Sum of square of errors over all observations - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations data_range: the range of the data. If None, it is determined from the data (max - min). ``data_range`` must be given when ``dim`` is not None. base: a base of a logarithm to use @@ -45,12 +45,12 @@ def _psnr_compute( >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]]) >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]]) >>> data_range = target.max() - target.min() - >>> sum_squared_error, n_obs = _psnr_update(preds, target) - >>> _psnr_compute(sum_squared_error, n_obs, data_range) + >>> sum_squared_error, num_obs = _psnr_update(preds, target) + >>> _psnr_compute(sum_squared_error, num_obs, data_range) tensor(2.5527) """ - psnr_base_e = 2 * torch.log(data_range) - torch.log(sum_squared_error / n_obs) + psnr_base_e = 2 * torch.log(data_range) - torch.log(sum_squared_error / num_obs) psnr_vals = psnr_base_e * (10 / torch.log(tensor(base))) return reduce(psnr_vals, reduction=reduction) @@ -71,20 +71,20 @@ def _psnr_update( """ if dim is None: sum_squared_error = torch.sum(torch.pow(preds - target, 2)) - n_obs = tensor(target.numel(), device=target.device) - return sum_squared_error, n_obs + num_obs = tensor(target.numel(), device=target.device) + return sum_squared_error, num_obs diff = preds - target sum_squared_error = torch.sum(diff * diff, dim=dim) dim_list = [dim] if isinstance(dim, int) else list(dim) if not dim_list: - n_obs = tensor(target.numel(), device=target.device) + num_obs = tensor(target.numel(), device=target.device) else: - n_obs = tensor(target.size(), device=target.device)[dim_list].prod() - n_obs = n_obs.expand_as(sum_squared_error) + num_obs = tensor(target.size(), device=target.device)[dim_list].prod() + num_obs = num_obs.expand_as(sum_squared_error) - return sum_squared_error, n_obs + return sum_squared_error, num_obs def peak_signal_noise_ratio( @@ -150,5 +150,5 @@ def peak_signal_noise_ratio( else: data_range = tensor(float(data_range)) - sum_squared_error, n_obs = _psnr_update(preds, target, dim=dim) - return _psnr_compute(sum_squared_error, n_obs, data_range, base=base, reduction=reduction) + sum_squared_error, num_obs = _psnr_update(preds, target, dim=dim) + return _psnr_compute(sum_squared_error, num_obs, data_range, base=base, reduction=reduction) diff --git a/src/torchmetrics/functional/image/psnrb.py b/src/torchmetrics/functional/image/psnrb.py index 1c663f288ac..8e190d9f563 100644 --- a/src/torchmetrics/functional/image/psnrb.py +++ b/src/torchmetrics/functional/image/psnrb.py @@ -68,7 +68,7 @@ def _compute_bef(x: Tensor, block_size: int = 8) -> Tensor: def _psnrb_compute( sum_squared_error: Tensor, bef: Tensor, - n_obs: Tensor, + num_obs: Tensor, data_range: Tensor, ) -> Tensor: """Computes peak signal-to-noise ratio. @@ -76,11 +76,11 @@ def _psnrb_compute( Args: sum_squared_error: Sum of square of errors over all observations bef: block effect - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations data_range: the range of the data. If None, it is determined from the data (max - min). """ - sum_squared_error = sum_squared_error / n_obs + bef + sum_squared_error = sum_squared_error / num_obs + bef if data_range > 2: return 10 * torch.log10(data_range**2 / sum_squared_error) return 10 * torch.log10(1.0 / sum_squared_error) @@ -96,9 +96,9 @@ def _psnrb_update(preds: Tensor, target: Tensor, block_size: int = 8) -> Tuple[T """ sum_squared_error = torch.sum(torch.pow(preds - target, 2)) - n_obs = tensor(target.numel(), device=target.device) + num_obs = tensor(target.numel(), device=target.device) bef = _compute_bef(preds, block_size=block_size) - return sum_squared_error, bef, n_obs + return sum_squared_error, bef, num_obs def peak_signal_noise_ratio_with_blocked_effect( @@ -132,5 +132,5 @@ def peak_signal_noise_ratio_with_blocked_effect( """ data_range = target.max() - target.min() - sum_squared_error, bef, n_obs = _psnrb_update(preds, target, block_size=block_size) - return _psnrb_compute(sum_squared_error, bef, n_obs, data_range) + sum_squared_error, bef, num_obs = _psnrb_update(preds, target, block_size=block_size) + return _psnrb_compute(sum_squared_error, bef, num_obs, data_range) diff --git a/src/torchmetrics/functional/nominal/cramers.py b/src/torchmetrics/functional/nominal/cramers.py index f63d9b2d60d..6d5d9d0ca59 100644 --- a/src/torchmetrics/functional/nominal/cramers.py +++ b/src/torchmetrics/functional/nominal/cramers.py @@ -70,18 +70,18 @@ def _cramers_v_compute(confmat: Tensor, bias_correction: bool) -> Tensor: cm_sum = confmat.sum() chi_squared = _compute_chi_squared(confmat, bias_correction) phi_squared = chi_squared / cm_sum - n_rows, n_cols = confmat.shape + num_rows, num_cols = confmat.shape if bias_correction: phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values( - phi_squared, n_rows, n_cols, cm_sum + phi_squared, num_rows, num_cols, cm_sum ) if torch.min(rows_corrected, cols_corrected) == 1: _unable_to_use_bias_correction_warning(metric_name="Cramer's V") return torch.tensor(float("nan"), device=confmat.device) cramers_v_value = torch.sqrt(phi_squared_corrected / torch.min(rows_corrected - 1, cols_corrected - 1)) else: - cramers_v_value = torch.sqrt(phi_squared / min(n_rows - 1, n_cols - 1)) + cramers_v_value = torch.sqrt(phi_squared / min(num_rows - 1, num_cols - 1)) return cramers_v_value.clamp(0.0, 1.0) diff --git a/src/torchmetrics/functional/nominal/fleiss_kappa.py b/src/torchmetrics/functional/nominal/fleiss_kappa.py index efbdee89143..f33e11d07ef 100644 --- a/src/torchmetrics/functional/nominal/fleiss_kappa.py +++ b/src/torchmetrics/functional/nominal/fleiss_kappa.py @@ -49,8 +49,7 @@ def _fleiss_kappa_compute(counts: Tensor) -> Tensor: """ total = counts.shape[0] - n_rater = counts.sum(1) - num_raters = n_rater.max() + num_raters = counts.sum(1).max() p_i = counts.sum(dim=0) / (total * num_raters) p_j = ((counts**2).sum(dim=1) - num_raters) / (num_raters * (num_raters - 1)) diff --git a/src/torchmetrics/functional/nominal/tschuprows.py b/src/torchmetrics/functional/nominal/tschuprows.py index 549dbedaca9..64a55e4e4bf 100644 --- a/src/torchmetrics/functional/nominal/tschuprows.py +++ b/src/torchmetrics/functional/nominal/tschuprows.py @@ -70,19 +70,19 @@ def _tschuprows_t_compute(confmat: Tensor, bias_correction: bool) -> Tensor: cm_sum = confmat.sum() chi_squared = _compute_chi_squared(confmat, bias_correction) phi_squared = chi_squared / cm_sum - n_rows, n_cols = confmat.shape + num_rows, num_cols = confmat.shape if bias_correction: phi_squared_corrected, rows_corrected, cols_corrected = _compute_bias_corrected_values( - phi_squared, n_rows, n_cols, cm_sum + phi_squared, num_rows, num_cols, cm_sum ) if torch.min(rows_corrected, cols_corrected) == 1: _unable_to_use_bias_correction_warning(metric_name="Tschuprow's T") return torch.tensor(float("nan"), device=confmat.device) tschuprows_t_value = torch.sqrt(phi_squared_corrected / torch.sqrt((rows_corrected - 1) * (cols_corrected - 1))) else: - n_rows_tensor = torch.tensor(n_rows, device=phi_squared.device) - n_cols_tensor = torch.tensor(n_cols, device=phi_squared.device) + n_rows_tensor = torch.tensor(num_rows, device=phi_squared.device) + n_cols_tensor = torch.tensor(num_cols, device=phi_squared.device) tschuprows_t_value = torch.sqrt(phi_squared / torch.sqrt((n_rows_tensor - 1) * (n_cols_tensor - 1))) return tschuprows_t_value.clamp(0.0, 1.0) diff --git a/src/torchmetrics/functional/nominal/utils.py b/src/torchmetrics/functional/nominal/utils.py index 431fbc12ba3..c1baefb977f 100644 --- a/src/torchmetrics/functional/nominal/utils.py +++ b/src/torchmetrics/functional/nominal/utils.py @@ -82,29 +82,30 @@ def _drop_empty_rows_and_cols(confmat: Tensor) -> Tensor: def _compute_phi_squared_corrected( phi_squared: Tensor, - n_rows: int, - n_cols: int, + num_rows: int, + num_cols: int, confmat_sum: Tensor, ) -> Tensor: """Compute bias-corrected Phi Squared.""" return torch.max( - torch.tensor(0.0, device=phi_squared.device), phi_squared - ((n_rows - 1) * (n_cols - 1)) / (confmat_sum - 1) + torch.tensor(0.0, device=phi_squared.device), + phi_squared - ((num_rows - 1) * (num_cols - 1)) / (confmat_sum - 1), ) -def _compute_rows_and_cols_corrected(n_rows: int, n_cols: int, confmat_sum: Tensor) -> Tuple[Tensor, Tensor]: +def _compute_rows_and_cols_corrected(num_rows: int, num_cols: int, confmat_sum: Tensor) -> Tuple[Tensor, Tensor]: """Compute bias-corrected number of rows and columns.""" - rows_corrected = n_rows - (n_rows - 1) ** 2 / (confmat_sum - 1) - cols_corrected = n_cols - (n_cols - 1) ** 2 / (confmat_sum - 1) + rows_corrected = num_rows - (num_rows - 1) ** 2 / (confmat_sum - 1) + cols_corrected = num_cols - (num_cols - 1) ** 2 / (confmat_sum - 1) return rows_corrected, cols_corrected def _compute_bias_corrected_values( - phi_squared: Tensor, n_rows: int, n_cols: int, confmat_sum: Tensor + phi_squared: Tensor, num_rows: int, num_cols: int, confmat_sum: Tensor ) -> Tuple[Tensor, Tensor, Tensor]: """Compute bias-corrected Phi Squared and number of rows and columns.""" - phi_squared_corrected = _compute_phi_squared_corrected(phi_squared, n_rows, n_cols, confmat_sum) - rows_corrected, cols_corrected = _compute_rows_and_cols_corrected(n_rows, n_cols, confmat_sum) + phi_squared_corrected = _compute_phi_squared_corrected(phi_squared, num_rows, num_cols, confmat_sum) + rows_corrected, cols_corrected = _compute_rows_and_cols_corrected(num_rows, num_cols, confmat_sum) return phi_squared_corrected, rows_corrected, cols_corrected diff --git a/src/torchmetrics/functional/regression/explained_variance.py b/src/torchmetrics/functional/regression/explained_variance.py index bfcdf345d44..a6a6c4ff209 100644 --- a/src/torchmetrics/functional/regression/explained_variance.py +++ b/src/torchmetrics/functional/regression/explained_variance.py @@ -32,7 +32,7 @@ def _explained_variance_update(preds: Tensor, target: Tensor) -> Tuple[int, Tens """ _check_same_shape(preds, target) - n_obs = preds.size(0) + num_obs = preds.size(0) sum_error = torch.sum(target - preds, dim=0) diff = target - preds sum_squared_error = torch.sum(diff * diff, dim=0) @@ -40,11 +40,11 @@ def _explained_variance_update(preds: Tensor, target: Tensor) -> Tuple[int, Tens sum_target = torch.sum(target, dim=0) sum_squared_target = torch.sum(target * target, dim=0) - return n_obs, sum_error, sum_squared_error, sum_target, sum_squared_target + return num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target def _explained_variance_compute( - n_obs: Union[int, Tensor], + num_obs: Union[int, Tensor], sum_error: Tensor, sum_squared_error: Tensor, sum_target: Tensor, @@ -54,7 +54,7 @@ def _explained_variance_compute( """Compute Explained Variance. Args: - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations sum_error: Sum of errors over all observations sum_squared_error: Sum of square of errors over all observations sum_target: Sum of target values @@ -69,16 +69,16 @@ def _explained_variance_compute( Example: >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) - >>> n_obs, sum_error, ss_error, sum_target, ss_target = _explained_variance_update(preds, target) - >>> _explained_variance_compute(n_obs, sum_error, ss_error, sum_target, ss_target, multioutput='raw_values') + >>> num_obs, sum_error, ss_error, sum_target, ss_target = _explained_variance_update(preds, target) + >>> _explained_variance_compute(num_obs, sum_error, ss_error, sum_target, ss_target, multioutput='raw_values') tensor([0.9677, 1.0000]) """ - diff_avg = sum_error / n_obs - numerator = sum_squared_error / n_obs - (diff_avg * diff_avg) + diff_avg = sum_error / num_obs + numerator = sum_squared_error / num_obs - (diff_avg * diff_avg) - target_avg = sum_target / n_obs - denominator = sum_squared_target / n_obs - (target_avg * target_avg) + target_avg = sum_target / num_obs + denominator = sum_squared_target / num_obs - (target_avg * target_avg) # Take care of division by zero nonzero_numerator = numerator != 0 @@ -130,9 +130,9 @@ def explained_variance( """ if multioutput not in ALLOWED_MULTIOUTPUT: raise ValueError(f"Invalid input to argument `multioutput`. Choose one of the following: {ALLOWED_MULTIOUTPUT}") - n_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update(preds, target) + num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update(preds, target) return _explained_variance_compute( - n_obs, + num_obs, sum_error, sum_squared_error, sum_target, diff --git a/src/torchmetrics/functional/regression/log_cosh.py b/src/torchmetrics/functional/regression/log_cosh.py index 60687323df6..ef9402c740f 100644 --- a/src/torchmetrics/functional/regression/log_cosh.py +++ b/src/torchmetrics/functional/regression/log_cosh.py @@ -46,19 +46,19 @@ def _log_cosh_error_update(preds: Tensor, target: Tensor, num_outputs: int) -> T preds, target = _unsqueeze_tensors(preds, target) diff = preds - target sum_log_cosh_error = torch.log((torch.exp(diff) + torch.exp(-diff)) / 2).sum(0).squeeze() - n_obs = torch.tensor(target.shape[0], device=preds.device) - return sum_log_cosh_error, n_obs + num_obs = torch.tensor(target.shape[0], device=preds.device) + return sum_log_cosh_error, num_obs -def _log_cosh_error_compute(sum_log_cosh_error: Tensor, n_obs: Tensor) -> Tensor: +def _log_cosh_error_compute(sum_log_cosh_error: Tensor, num_obs: Tensor) -> Tensor: """Compute Mean Squared Error. Args: sum_log_cosh_error: Sum of LogCosh errors over all observations - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations """ - return (sum_log_cosh_error / n_obs).squeeze() + return (sum_log_cosh_error / num_obs).squeeze() def log_cosh_error(preds: Tensor, target: Tensor) -> Tensor: @@ -90,7 +90,7 @@ def log_cosh_error(preds: Tensor, target: Tensor) -> Tensor: tensor([0.9176, 0.4277, 0.2194]) """ - sum_log_cosh_error, n_obs = _log_cosh_error_update( + sum_log_cosh_error, num_obs = _log_cosh_error_update( preds, target, num_outputs=1 if preds.ndim == 1 else preds.shape[-1] ) - return _log_cosh_error_compute(sum_log_cosh_error, n_obs) + return _log_cosh_error_compute(sum_log_cosh_error, num_obs) diff --git a/src/torchmetrics/functional/regression/log_mse.py b/src/torchmetrics/functional/regression/log_mse.py index 0c157c88489..96d2938a8ee 100644 --- a/src/torchmetrics/functional/regression/log_mse.py +++ b/src/torchmetrics/functional/regression/log_mse.py @@ -29,27 +29,26 @@ def _mean_squared_log_error_update(preds: Tensor, target: Tensor) -> Tuple[Tenso """ _check_same_shape(preds, target) sum_squared_log_error = torch.sum(torch.pow(torch.log1p(preds) - torch.log1p(target), 2)) - n_obs = target.numel() - return sum_squared_log_error, n_obs + return sum_squared_log_error, target.numel() -def _mean_squared_log_error_compute(sum_squared_log_error: Tensor, n_obs: Union[int, Tensor]) -> Tensor: +def _mean_squared_log_error_compute(sum_squared_log_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: """Compute Mean Squared Log Error. Args: sum_squared_log_error: Sum of square of log errors over all observations ``(log error = log(target) - log(prediction))`` - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations Example: >>> preds = torch.tensor([0., 1, 2, 3]) >>> target = torch.tensor([0., 1, 2, 2]) - >>> sum_squared_log_error, n_obs = _mean_squared_log_error_update(preds, target) - >>> _mean_squared_log_error_compute(sum_squared_log_error, n_obs) + >>> sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) + >>> _mean_squared_log_error_compute(sum_squared_log_error, num_obs) tensor(0.0207) """ - return sum_squared_log_error / n_obs + return sum_squared_log_error / num_obs def mean_squared_log_error(preds: Tensor, target: Tensor) -> Tensor: @@ -73,5 +72,5 @@ def mean_squared_log_error(preds: Tensor, target: Tensor) -> Tensor: Half precision is only support on GPU for this metric """ - sum_squared_log_error, n_obs = _mean_squared_log_error_update(preds, target) - return _mean_squared_log_error_compute(sum_squared_log_error, n_obs) + sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) + return _mean_squared_log_error_compute(sum_squared_log_error, num_obs) diff --git a/src/torchmetrics/functional/regression/mae.py b/src/torchmetrics/functional/regression/mae.py index d35b988281c..e0982e6042f 100644 --- a/src/torchmetrics/functional/regression/mae.py +++ b/src/torchmetrics/functional/regression/mae.py @@ -33,26 +33,25 @@ def _mean_absolute_error_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, preds = preds if preds.is_floating_point else preds.float() # type: ignore[truthy-function] # todo target = target if target.is_floating_point else target.float() # type: ignore[truthy-function] # todo sum_abs_error = torch.sum(torch.abs(preds - target)) - n_obs = target.numel() - return sum_abs_error, n_obs + return sum_abs_error, target.numel() -def _mean_absolute_error_compute(sum_abs_error: Tensor, n_obs: Union[int, Tensor]) -> Tensor: +def _mean_absolute_error_compute(sum_abs_error: Tensor, num_obs: Union[int, Tensor]) -> Tensor: """Compute Mean Absolute Error. Args: sum_abs_error: Sum of absolute value of errors over all observations - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations Example: >>> preds = torch.tensor([0., 1, 2, 3]) >>> target = torch.tensor([0., 1, 2, 2]) - >>> sum_abs_error, n_obs = _mean_absolute_error_update(preds, target) - >>> _mean_absolute_error_compute(sum_abs_error, n_obs) + >>> sum_abs_error, num_obs = _mean_absolute_error_update(preds, target) + >>> _mean_absolute_error_compute(sum_abs_error, num_obs) tensor(0.2500) """ - return sum_abs_error / n_obs + return sum_abs_error / num_obs def mean_absolute_error(preds: Tensor, target: Tensor) -> Tensor: @@ -73,5 +72,5 @@ def mean_absolute_error(preds: Tensor, target: Tensor) -> Tensor: tensor(0.2500) """ - sum_abs_error, n_obs = _mean_absolute_error_update(preds, target) - return _mean_absolute_error_compute(sum_abs_error, n_obs) + sum_abs_error, num_obs = _mean_absolute_error_update(preds, target) + return _mean_absolute_error_compute(sum_abs_error, num_obs) diff --git a/src/torchmetrics/functional/regression/mse.py b/src/torchmetrics/functional/regression/mse.py index c7d6d47dbfe..f9649a87416 100644 --- a/src/torchmetrics/functional/regression/mse.py +++ b/src/torchmetrics/functional/regression/mse.py @@ -36,27 +36,26 @@ def _mean_squared_error_update(preds: Tensor, target: Tensor, num_outputs: int) target = target.view(-1) diff = preds - target sum_squared_error = torch.sum(diff * diff, dim=0) - n_obs = target.shape[0] - return sum_squared_error, n_obs + return sum_squared_error, target.shape[0] -def _mean_squared_error_compute(sum_squared_error: Tensor, n_obs: Union[int, Tensor], squared: bool = True) -> Tensor: +def _mean_squared_error_compute(sum_squared_error: Tensor, num_obs: Union[int, Tensor], squared: bool = True) -> Tensor: """Compute Mean Squared Error. Args: sum_squared_error: Sum of square of errors over all observations - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations squared: Returns RMSE value if set to False. Example: >>> preds = torch.tensor([0., 1, 2, 3]) >>> target = torch.tensor([0., 1, 2, 2]) - >>> sum_squared_error, n_obs = _mean_squared_error_update(preds, target, num_outputs=1) - >>> _mean_squared_error_compute(sum_squared_error, n_obs) + >>> sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=1) + >>> _mean_squared_error_compute(sum_squared_error, num_obs) tensor(0.2500) """ - return sum_squared_error / n_obs if squared else torch.sqrt(sum_squared_error / n_obs) + return sum_squared_error / num_obs if squared else torch.sqrt(sum_squared_error / num_obs) def mean_squared_error(preds: Tensor, target: Tensor, squared: bool = True, num_outputs: int = 1) -> Tensor: @@ -79,5 +78,5 @@ def mean_squared_error(preds: Tensor, target: Tensor, squared: bool = True, num_ tensor(0.2500) """ - sum_squared_error, n_obs = _mean_squared_error_update(preds, target, num_outputs=num_outputs) - return _mean_squared_error_compute(sum_squared_error, n_obs, squared=squared) + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=num_outputs) + return _mean_squared_error_compute(sum_squared_error, num_obs, squared=squared) diff --git a/src/torchmetrics/functional/regression/pearson.py b/src/torchmetrics/functional/regression/pearson.py index 3c3d4dfc2c9..b76c3a12992 100644 --- a/src/torchmetrics/functional/regression/pearson.py +++ b/src/torchmetrics/functional/regression/pearson.py @@ -30,7 +30,7 @@ def _pearson_corrcoef_update( var_x: Tensor, var_y: Tensor, corr_xy: Tensor, - n_prior: Tensor, + num_prior: Tensor, num_outputs: int, ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: """Update and returns variables required to compute Pearson Correlation Coefficient. @@ -45,36 +45,36 @@ def _pearson_corrcoef_update( var_x: current variance estimate of x tensor var_y: current variance estimate of y tensor corr_xy: current covariance estimate between x and y tensor - n_prior: current number of observed observations + num_prior: current number of observed observations num_outputs: Number of outputs in multioutput setting """ # Data checking _check_same_shape(preds, target) _check_data_shape_to_num_outputs(preds, target, num_outputs) - n_obs = preds.shape[0] - cond = n_prior.mean() > 0 or n_obs == 1 + num_obs = preds.shape[0] + cond = num_prior.mean() > 0 or num_obs == 1 if cond: - mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs) - my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs) + mx_new = (num_prior * mean_x + preds.sum(0)) / (num_prior + num_obs) + my_new = (num_prior * mean_y + target.sum(0)) / (num_prior + num_obs) else: mx_new = preds.mean(0) my_new = target.mean(0) - n_prior += n_obs + num_prior += num_obs if cond: var_x += ((preds - mx_new) * (preds - mean_x)).sum(0) var_y += ((target - my_new) * (target - mean_y)).sum(0) else: - var_x += preds.var(0) * (n_obs - 1) - var_y += target.var(0) * (n_obs - 1) + var_x += preds.var(0) * (num_obs - 1) + var_y += target.var(0) * (num_obs - 1) corr_xy += ((preds - mx_new) * (target - mean_y)).sum(0) mean_x = mx_new mean_y = my_new - return mean_x, mean_y, var_x, var_y, corr_xy, n_prior + return mean_x, mean_y, var_x, var_y, corr_xy, num_prior def _pearson_corrcoef_compute( diff --git a/src/torchmetrics/functional/regression/r2.py b/src/torchmetrics/functional/regression/r2.py index 076b44eafa3..100a94338dc 100644 --- a/src/torchmetrics/functional/regression/r2.py +++ b/src/torchmetrics/functional/regression/r2.py @@ -41,15 +41,14 @@ def _r2_score_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, Tensor, Ten sum_squared_obs = torch.sum(target * target, dim=0) residual = target - preds rss = torch.sum(residual * residual, dim=0) - n_obs = target.size(0) - return sum_squared_obs, sum_obs, rss, n_obs + return sum_squared_obs, sum_obs, rss, target.size(0) def _r2_score_compute( sum_squared_obs: Tensor, sum_obs: Tensor, rss: Tensor, - n_obs: Union[int, Tensor], + num_obs: Union[int, Tensor], adjusted: int = 0, multioutput: str = "uniform_average", ) -> Tensor: @@ -59,7 +58,7 @@ def _r2_score_compute( sum_squared_obs: Sum of square of all observations sum_obs: Sum of all observations rss: Residual sum of squares - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations adjusted: number of independent regressors for calculating adjusted r2 score. multioutput: Defines aggregation in the case of multiple output scores. Can be one of the following strings: @@ -70,15 +69,15 @@ def _r2_score_compute( Example: >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) - >>> sum_squared_obs, sum_obs, rss, n_obs = _r2_score_update(preds, target) - >>> _r2_score_compute(sum_squared_obs, sum_obs, rss, n_obs, multioutput="raw_values") + >>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + >>> _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, multioutput="raw_values") tensor([0.9654, 0.9082]) """ - if n_obs < 2: + if num_obs < 2: raise ValueError("Needs at least two samples to calculate r2 score.") - mean_obs = sum_obs / n_obs + mean_obs = sum_obs / num_obs tss = sum_squared_obs - sum_obs * mean_obs # Account for near constant targets @@ -107,16 +106,16 @@ def _r2_score_compute( raise ValueError("`adjusted` parameter should be an integer larger or equal to 0.") if adjusted != 0: - if adjusted > n_obs - 1: + if adjusted > num_obs - 1: rank_zero_warn( "More independent regressions than data points in" " adjusted r2 score. Falls back to standard r2 score.", UserWarning, ) - elif adjusted == n_obs - 1: + elif adjusted == num_obs - 1: rank_zero_warn("Division by zero in adjusted r2 score. Falls back to standard r2 score.", UserWarning) else: - return 1 - (1 - r2) * (n_obs - 1) / (n_obs - adjusted - 1) + return 1 - (1 - r2) * (num_obs - 1) / (num_obs - adjusted - 1) return r2 @@ -172,5 +171,5 @@ def r2_score( tensor([0.9654, 0.9082]) """ - sum_squared_obs, sum_obs, rss, n_obs = _r2_score_update(preds, target) - return _r2_score_compute(sum_squared_obs, sum_obs, rss, n_obs, adjusted, multioutput) + sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + return _r2_score_compute(sum_squared_obs, sum_obs, rss, num_obs, adjusted, multioutput) diff --git a/src/torchmetrics/functional/regression/rse.py b/src/torchmetrics/functional/regression/rse.py index d933f8992e0..4bb07002bfc 100644 --- a/src/torchmetrics/functional/regression/rse.py +++ b/src/torchmetrics/functional/regression/rse.py @@ -23,7 +23,7 @@ def _relative_squared_error_compute( sum_squared_obs: Tensor, sum_obs: Tensor, sum_squared_error: Tensor, - n_obs: Union[int, Tensor], + num_obs: Union[int, Tensor], squared: bool = True, ) -> Tensor: """Computes Relative Squared Error. @@ -32,20 +32,20 @@ def _relative_squared_error_compute( sum_squared_obs: Sum of square of all observations sum_obs: Sum of all observations sum_squared_error: Residual sum of squares - n_obs: Number of predictions or observations + num_obs: Number of predictions or observations squared: Returns RRSE value if set to False. Example: >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]]) >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]]) >>> # RSE uses the same update function as R2 score. - >>> sum_squared_obs, sum_obs, rss, n_obs = _r2_score_update(preds, target) - >>> _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, n_obs, squared=True) + >>> sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + >>> _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=True) tensor(0.0632) """ epsilon = torch.finfo(sum_squared_error.dtype).eps - rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / n_obs, min=epsilon) + rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / num_obs, min=epsilon) if not squared: rse = torch.sqrt(rse) return torch.mean(rse) @@ -76,5 +76,5 @@ def relative_squared_error(preds: Tensor, target: Tensor, squared: bool = True) tensor(0.0514) """ - sum_squared_obs, sum_obs, rss, n_obs = _r2_score_update(preds, target) - return _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, n_obs, squared=squared) + sum_squared_obs, sum_obs, rss, num_obs = _r2_score_update(preds, target) + return _relative_squared_error_compute(sum_squared_obs, sum_obs, rss, num_obs, squared=squared) diff --git a/src/torchmetrics/image/fid.py b/src/torchmetrics/image/fid.py index ea460bb46d8..afa706b3425 100644 --- a/src/torchmetrics/image/fid.py +++ b/src/torchmetrics/image/fid.py @@ -313,13 +313,13 @@ def __init__( raise ValueError("Argument `normalize` expected to be a bool") self.normalize = normalize - mx_nb_feets = (num_features, num_features) + mx_num_feets = (num_features, num_features) self.add_state("real_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum") - self.add_state("real_features_cov_sum", torch.zeros(mx_nb_feets).double(), dist_reduce_fx="sum") + self.add_state("real_features_cov_sum", torch.zeros(mx_num_feets).double(), dist_reduce_fx="sum") self.add_state("real_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum") self.add_state("fake_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum") - self.add_state("fake_features_cov_sum", torch.zeros(mx_nb_feets).double(), dist_reduce_fx="sum") + self.add_state("fake_features_cov_sum", torch.zeros(mx_num_feets).double(), dist_reduce_fx="sum") self.add_state("fake_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum") def update(self, imgs: Tensor, real: bool) -> None: diff --git a/src/torchmetrics/image/psnr.py b/src/torchmetrics/image/psnr.py index 83f4cdacbda..3e63bd585de 100644 --- a/src/torchmetrics/image/psnr.py +++ b/src/torchmetrics/image/psnr.py @@ -128,7 +128,7 @@ def update(self, preds: Tensor, target: Tensor) -> None: preds = self.clamping_fn(preds) target = self.clamping_fn(target) - sum_squared_error, n_obs = _psnr_update(preds, target, dim=self.dim) + sum_squared_error, num_obs = _psnr_update(preds, target, dim=self.dim) if self.dim is None: if self.data_range is None: # keep track of min and max target values @@ -136,10 +136,10 @@ def update(self, preds: Tensor, target: Tensor) -> None: self.max_target = torch.maximum(target.max(), self.max_target) self.sum_squared_error += sum_squared_error - self.total += n_obs + self.total += num_obs else: self.sum_squared_error.append(sum_squared_error) - self.total.append(n_obs) + self.total.append(num_obs) def compute(self) -> Tensor: """Compute peak signal-to-noise ratio over state.""" diff --git a/src/torchmetrics/image/psnrb.py b/src/torchmetrics/image/psnrb.py index 45b8d493f6c..6d82381e5e9 100644 --- a/src/torchmetrics/image/psnrb.py +++ b/src/torchmetrics/image/psnrb.py @@ -87,10 +87,10 @@ def __init__( def update(self, preds: Tensor, target: Tensor) -> None: """Update state with predictions and targets.""" - sum_squared_error, bef, n_obs = _psnrb_update(preds, target, block_size=self.block_size) + sum_squared_error, bef, num_obs = _psnrb_update(preds, target, block_size=self.block_size) self.sum_squared_error += sum_squared_error self.bef += bef - self.total += n_obs + self.total += num_obs self.data_range = torch.maximum(self.data_range, torch.max(target) - torch.min(target)) def compute(self) -> Tensor: diff --git a/src/torchmetrics/regression/explained_variance.py b/src/torchmetrics/regression/explained_variance.py index ea9a0c4b427..855c097c1a1 100644 --- a/src/torchmetrics/regression/explained_variance.py +++ b/src/torchmetrics/regression/explained_variance.py @@ -87,7 +87,7 @@ class ExplainedVariance(Metric): plot_lower_bound: float = 0.0 plot_upper_bound: float = 1.0 - n_obs: Tensor + num_obs: Tensor sum_error: Tensor sum_squared_error: Tensor sum_target: Tensor @@ -109,12 +109,14 @@ def __init__( self.add_state("sum_squared_error", default=tensor(0.0), dist_reduce_fx="sum") self.add_state("sum_target", default=tensor(0.0), dist_reduce_fx="sum") self.add_state("sum_squared_target", default=tensor(0.0), dist_reduce_fx="sum") - self.add_state("n_obs", default=tensor(0.0), dist_reduce_fx="sum") + self.add_state("num_obs", default=tensor(0.0), dist_reduce_fx="sum") def update(self, preds: Tensor, target: Tensor) -> None: """Update state with predictions and targets.""" - n_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update(preds, target) - self.n_obs = self.n_obs + n_obs + num_obs, sum_error, sum_squared_error, sum_target, sum_squared_target = _explained_variance_update( + preds, target + ) + self.num_obs = self.num_obs + num_obs self.sum_error = self.sum_error + sum_error self.sum_squared_error = self.sum_squared_error + sum_squared_error self.sum_target = self.sum_target + sum_target @@ -123,7 +125,7 @@ def update(self, preds: Tensor, target: Tensor) -> None: def compute(self) -> Union[Tensor, Sequence[Tensor]]: """Compute explained variance over state.""" return _explained_variance_compute( - self.n_obs, + self.num_obs, self.sum_error, self.sum_squared_error, self.sum_target, diff --git a/src/torchmetrics/regression/log_cosh.py b/src/torchmetrics/regression/log_cosh.py index 864fa11e07e..ca9395f9a50 100644 --- a/src/torchmetrics/regression/log_cosh.py +++ b/src/torchmetrics/regression/log_cosh.py @@ -90,9 +90,9 @@ def update(self, preds: Tensor, target: Tensor) -> None: If ``preds`` or ``target`` has multiple outputs when ``num_outputs=1`` """ - sum_log_cosh_error, n_obs = _log_cosh_error_update(preds, target, self.num_outputs) + sum_log_cosh_error, num_obs = _log_cosh_error_update(preds, target, self.num_outputs) self.sum_log_cosh_error += sum_log_cosh_error - self.total += n_obs + self.total += num_obs def compute(self) -> Tensor: """Compute LogCosh error over state.""" diff --git a/src/torchmetrics/regression/log_mse.py b/src/torchmetrics/regression/log_mse.py index 0aab6718849..70feb31558c 100644 --- a/src/torchmetrics/regression/log_mse.py +++ b/src/torchmetrics/regression/log_mse.py @@ -75,10 +75,10 @@ def __init__( def update(self, preds: Tensor, target: Tensor) -> None: """Update state with predictions and targets.""" - sum_squared_log_error, n_obs = _mean_squared_log_error_update(preds, target) + sum_squared_log_error, num_obs = _mean_squared_log_error_update(preds, target) self.sum_squared_log_error += sum_squared_log_error - self.total += n_obs + self.total += num_obs def compute(self) -> Tensor: """Compute mean squared logarithmic error over state.""" diff --git a/src/torchmetrics/regression/mae.py b/src/torchmetrics/regression/mae.py index 5e141b84a9d..4461f40e53d 100644 --- a/src/torchmetrics/regression/mae.py +++ b/src/torchmetrics/regression/mae.py @@ -72,10 +72,10 @@ def __init__( def update(self, preds: Tensor, target: Tensor) -> None: """Update state with predictions and targets.""" - sum_abs_error, n_obs = _mean_absolute_error_update(preds, target) + sum_abs_error, num_obs = _mean_absolute_error_update(preds, target) self.sum_abs_error += sum_abs_error - self.total += n_obs + self.total += num_obs def compute(self) -> Tensor: """Compute mean absolute error over state.""" diff --git a/src/torchmetrics/regression/mse.py b/src/torchmetrics/regression/mse.py index 34aaf196803..c88eb84350e 100644 --- a/src/torchmetrics/regression/mse.py +++ b/src/torchmetrics/regression/mse.py @@ -98,10 +98,10 @@ def __init__( def update(self, preds: Tensor, target: Tensor) -> None: """Update state with predictions and targets.""" - sum_squared_error, n_obs = _mean_squared_error_update(preds, target, num_outputs=self.num_outputs) + sum_squared_error, num_obs = _mean_squared_error_update(preds, target, num_outputs=self.num_outputs) self.sum_squared_error += sum_squared_error - self.total += n_obs + self.total += num_obs def compute(self) -> Tensor: """Compute mean squared error over state."""