docstr: Gets a dataset and a model as input. Calculates losses for each sample in the dataset.
  Sorts samples by `sort_by` (e.g. one of the losses). Runs model predictions on samples.
  Plots the top sorted `n_samples` and returns losses + predictions + losses_stats.
  
  Arguments
  ---------
  model: nn.Module
  dataset: Dataset
  sort_by: (str) the loss to sort samples by
  n_samples: how many samples to show
  batch_size: used when creating the infer dataloader to get model predictions on the dataset
  
  Returns
  -------
  sorted_samples: those are the samples (dictionaries) contained in the original dataset
                  enriched with losses and sorted by `sort_by`.
  sorted_preds: `model` predictions on `sorted_samples`. Same order as `sorted_samples`.
  losses_stats: dictionary containing losses stats (min, max, mean, 1-25-50-75-99 quantiles)
              for each one of the losses.
docstr_tok: ["Gets","a","dataset","and","a","model","as","input",".","Calculates","losses","for","each","sample","in","the","dataset",".","Sorts","samples","by","`","sort_by","`","(","e.g",".","one","of","the","losses",")",".","Runs","model","predictions","on","samples",".","Plots","the","top","sorted","`","n_samples","`","and","returns","losses","+","predictions","+","losses_stats",".","Arguments","--","--","--","--","-","model",":","nn.Module","dataset",":","Dataset","sort_by",":","(","str",")","the","loss","to","sort","samples","by","n_samples",":","how","many","samples","to","show","batch_size",":","used","when","creating","the","infer","dataloader","to","get","model","predictions","on","the","dataset","Returns","--","--","--","-","sorted_samples",":","those","are","the","samples","(","dictionaries",")","contained","in","the","original","dataset","enriched","with","losses","and","sorted","by","`","sort_by","`",".","sorted_preds",":","`","model","`","predictions","on","`","sorted_samples","`",".","Same","order","as","`","sorted_samples","`",".","losses_stats",":","dictionary","containing","losses","stats","(","min",",","max",",","mean",",","1-25-50-75-99","quantiles",")","for","each","one","of","the","losses","."]
code: def plot_top_losses(
      self,
      model: nn.Module,
      dataset: Dataset,
      sort_by: str = "loss_total",
      n_samples: int = 5,
      batch_size: int = 8,
      device: torch.device = None,
  ) -> Tuple[List[dict], List[dict], dict]:
      """
      Gets a dataset and a model as input. Calculates losses for each sample in the dataset.
      Sorts samples by `sort_by` (e.g. one of the losses). Runs model predictions on samples.
      Plots the top sorted `n_samples` and returns losses + predictions + losses_stats.
  
      Arguments
      ---------
      model: nn.Module
      dataset: Dataset
      sort_by: (str) the loss to sort samples by
      n_samples: how many samples to show
      batch_size: used when creating the infer dataloader to get model predictions on the dataset
  
      Returns
      -------
      sorted_samples: those are the samples (dictionaries) contained in the original dataset
                      enriched with losses and sorted by `sort_by`.
      sorted_preds: `model` predictions on `sorted_samples`. Same order as `sorted_samples`.
      losses_stats: dictionary containing losses stats (min, max, mean, 1-25-50-75-99 quantiles)
                  for each one of the losses.
      """
      logger.info(
          f"Losses returned by model: {[l for l in list(_prepend_str(self.losses_dict, 'loss').keys()) if l!='loss_total']}",
      )
  
      samples, losses_stats = self.get_losses(model, dataset)
      samples = add_annotations(samples)
  
      dl = self.infer_dl(dataset, batch_size=batch_size)
      preds = self.predict_from_dl(model=model, infer_dl=dl)
      preds = [p.pred for p in preds]
  
      sorted_samples, sorted_preds, annotations = sort_losses(
          samples, preds, by=sort_by
      )
      assert (
          len(sorted_samples)
          == len(samples)
          == len(preds)
          == len(sorted_preds)
      )
  
      anns = []
      for ann in annotations:
          ann = ann.split("\n")
          ann1 = "\n".join(ann[:4])
          ann2 = "\n".join(ann[4:])
          anns.append((ann1, ann2))
  
      # Ensure that segmentation ground truth masks are loaded
      if hasattr(sorted_samples[0], "segmentation") and (
          not sorted_samples[0].segmentation.mask_array
      ):
          for ii in range(len(sorted_samples)):
              w, h = sorted_samples[0].img_size
              sorted_samples[ii].segmentation.mask_array = (
                  sorted_samples[ii]
                  .segmentation.masks[0]
                  .to_mask(h=h, w=w, pad_dim=False)
              )
  
      sorted_preds = [
          Prediction(pred=p, ground_truth=s)
          for s, p in zip(sorted_samples, sorted_preds)
      ]
  
      show_preds(
          preds=sorted_preds[:n_samples],
          annotations=anns[:n_samples],
      )
      model.train()
      return sorted_samples, sorted_preds, losses_stats
  
file_path: icevision/icevision/models/interpretation.py
imports: from icevision.imports import *
  from icevision.utils import *
  from icevision.core import *
  from icevision.data import *
  from icevision.visualize.show_data import show_preds
  from icevision.core.record_components import LossesRecordComponent
label_desc: Use image node_id 6 for calling the Interpretation obj's underlying member method code with example usage: obj.plot_top_losses(model, dataset, sort_by, n_samples, batch_size, device) and returns: sorted_samples,  sorted_preds,  losses_stats