def remove_unecessary_ema(variables_to_restore, no_ema_collection=None):
  """Remap and Remove EMA variable that are not created during training.

  ExponentialMovingAverage.variables_to_restore() returns a map of EMA names
  to tf variables to restore. E.g.:
  {
      conv/batchnorm/gamma/ExponentialMovingAverage: conv/batchnorm/gamma,
      conv_4/conv2d_params/ExponentialMovingAverage: conv_4/conv2d_params,
      global_step: global_step
  }
  This function takes care of the extra ExponentialMovingAverage variables
  that get created during eval but aren't available in the checkpoint, by
  remapping the key to the shallow copy of the variable itself, and remove
  the entry of its EMA from the variables to restore. An example resulting
  dictionary would look like:
  {
      conv/batchnorm/gamma: conv/batchnorm/gamma,
      conv_4/conv2d_params: conv_4/conv2d_params,
      global_step: global_step
  }
  Args:
    variables_to_restore: A dictionary created by ExponentialMovingAverage.
      variables_to_restore().
    no_ema_collection: A list of namescope substrings to match the variables
      to eliminate EMA.

  Returns:
    A variables_to_restore dictionary excluding the collection of unwanted
    EMA mapping.
  """
  if no_ema_collection is None:
    return variables_to_restore

  for key in variables_to_restore:
    if "ExponentialMovingAverage" in key:
      for name in no_ema_collection:
        if name in key:
          variables_to_restore[key.replace("/ExponentialMovingAverage",
                                           "")] = variables_to_restore[key]
          del variables_to_restore[key]
  return variables_to_restore