Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.

def initialize(decision_function, sample, shape, clip_min, clip_max):
  """
  Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
  """
  success = 0
  num_evals = 0

  # Find a misclassified random noise.
  while True:
    random_noise = np.random.uniform(clip_min, clip_max, size=shape)
    success = decision_function(random_noise[None])[0]
    if success:
      break
    num_evals += 1
    message = "Initialization failed! Try to use a misclassified image as `target_image`"
    assert num_evals < 1e4, message

  # Binary search to minimize l2 distance to original image.
  low = 0.0
  high = 1.0
  while high - low > 0.001:
    mid = (high + low) / 2.0
    blended = (1 - mid) * sample + mid * random_noise
    success = decision_function(blended[None])[0]
    if success:
      high = mid
    else:
      low = mid

  initialization = (1 - high) * sample + high * random_noise
  return initialization