class_docstr: Implementation of Sleeper Agent Attack
  
  | Paper link: https://arxiv.org/pdf/2106.08970.pdf
class_docstr_tok: ["Implementation","of","Sleeper","Agent","Attack","|","Paper","link",":","https",":","\/\/arxiv.org\/pdf\/2106.08970.pdf"]
docstr: Select indices of poisoned samples
  
  :classifier: Substitute Model.
  :x_samples: Samples of poison. [x_samples are normalised]
  :y_samples: Labels of samples of poison.
  :num_poison: Number of poisoned samples to be selected out of all x_samples.
  :return indices - Indices of samples to be poisoned.
docstr_tok: ["Select","indices","of","poisoned","samples",":","classifier",":","Substitute","Model",".",":","x_samples",":","Samples","of","poison",".","[","x_samples","are","normalised","]",":","y_samples",":","Labels","of","samples","of","poison",".",":","num_poison",":","Number","of","poisoned","samples","to","be","selected","out","of","all","x_samples",".",":","return","indices","-","Indices","of","samples","to","be","poisoned","."]
code: def _select_poison_indices(
      self,
      classifier: "CLASSIFIER_NEURALNETWORK_TYPE",
      x_samples: np.ndarray,
      y_samples: np.ndarray,
      num_poison: int,
  ) -> np.ndarray:
      """
      Select indices of poisoned samples
  
      :classifier: Substitute Model.
      :x_samples: Samples of poison. [x_samples are normalised]
      :y_samples: Labels of samples of poison.
      :num_poison: Number of poisoned samples to be selected out of all x_samples.
      :return indices - Indices of samples to be poisoned.
      """
      if isinstance(self.substitute_classifier, PyTorchClassifier):
          import torch
  
          device = torch.device(self.device_name)
          grad_norms = []
          criterion = torch.nn.CrossEntropyLoss()
          model = classifier.model
          model.eval()
          differentiable_params = [
              p
              for p in classifier.model.parameters()
              if p.requires_grad
          ]
          for x, y in zip(x_samples, y_samples):
              image = (
                  torch.tensor(x, dtype=torch.float32)
                  .float()
                  .to(device)
              )
              label = torch.tensor(y).to(device)
              loss_pt = criterion(
                  model(image.unsqueeze(0)), label.unsqueeze(0)
              )
              gradients = list(
                  torch.autograd.grad(
                      loss_pt, differentiable_params, only_inputs=True
                  )
              )
              grad_norm = torch.tensor(0, dtype=torch.float32).to(
                  device
              )
              for grad in gradients:
                  grad_norm += grad.detach().pow(2).sum()
              grad_norms.append(grad_norm.sqrt())
      elif isinstance(
          self.substitute_classifier, TensorFlowV2Classifier
      ):
          import tensorflow as tf
  
          model_trainable = classifier.model.trainable
          classifier.model.trainable = False
          grad_norms = []
          for i in range(len(x_samples) - 1):
              image = tf.constant(x_samples[i : i + 1])
              label = tf.constant(y_samples[i : i + 1])
              with tf.GradientTape() as t:  # pylint: disable=C0103
                  t.watch(classifier.model.weights)
                  output = classifier.model(image, training=False)
                  loss_tf = classifier.loss_object(label, output)  # type: ignore
                  gradients = list(
                      t.gradient(loss_tf, classifier.model.weights)
                  )
                  gradients = [w for w in gradients if w is not None]
                  grad_norm = tf.constant(0, dtype=tf.float32)
                  for grad in gradients:
                      grad_norm += tf.reduce_sum(tf.math.square(grad))
                  grad_norms.append(tf.math.sqrt(grad_norm))
          classifier.model.trainable = model_trainable
      else:
          raise NotImplementedError(
              "SleeperAgentAttack is currently implemented only for PyTorch and TensorFlowV2."
          )
      indices = sorted(range(len(grad_norms)), key=lambda k: grad_norms[k])  # type: ignore
      indices = indices[-num_poison:]
      return np.array(indices)
  
imports: from __future__ import absolute_import, division, print_function, unicode_literals
  import logging
  from typing import Tuple, TYPE_CHECKING, List, Union
  import random
  import numpy
  from tqdm.auto import trange
  from art.attacks.poisoning.gradient_matching_attack import GradientMatchingAttack
  from art.estimators.classification.pytorch import PyTorchClassifier
  from art.estimators.classification import TensorFlowV2Classifier
  from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch
  from art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow
label_desc: Use image node_id 7 for calling the SleeperAgentAttack obj's underlying member method code with example usage: obj._select_poison_indices(classifier, x_samples, y_samples, num_poison) and returns: np