code: def balance_data(
      data_list, key="labels", shuffle=True, exclude_labels=None
  ):
      """
      Given a list of acts, balance the list by label.
      """
      if len(data_list) == 0:
          # empty set
          return data_list
  
      def get_lst_sample(lst, sample_size):
          if len(lst) == sample_size:
              return lst
  
          sampled = []
          sample_times = sample_size // len(lst)
          for _ in range(sample_times):
              sampled += lst
          differential = sample_size - len(sampled)
          if differential > 0:
              extra_examples = random.sample(lst, differential)
              sampled += extra_examples
  
          return sampled
  
      separate_data = {}
      excluded_data = []
      for x in data_list:
          label = x[key]
          if isinstance(label, list):
              label = label[0]
          if exclude_labels is not None and label in exclude_labels:
              # exclude this from the balancing, but
              # add it later
              excluded_data.append(x)
          else:
              separate_data.setdefault(label, [])
              separate_data[label].append(x)
  
      max_len = max(len(value) for value in separate_data.values())
      new_data = []
      for _, data in separate_data.items():
          exs = get_lst_sample(data, max_len)
          new_data += exs
  
      assert len(new_data) == max_len * len(separate_data)
  
      # now add back data that was excluded from balancing
      new_data += excluded_data
  
      if shuffle:
          random.shuffle(new_data)
  
      return new_data
  
file_path: ParlAI/parlai/tasks/md_gender/utils.py
imports: import os
  import random
  from collections import defaultdict
  from parlai.tasks.md_gender.build import build
label_desc: Use image node_id 3 for calling a global function with example usage: balance_data(data_list, key, shuffle, exclude_labels) and returns: new_data, data_list, sampled, lst