Source code for textattack.search_methods.differential_evolution

import numpy as np
from scipy.optimize import differential_evolution

from textattack.goal_function_results import GoalFunctionResult
from textattack.search_methods import SearchMethod
from textattack.shared import AttackedText
from textattack.shared.validators import (
    transformation_consists_of_word_swaps_differential_evolution,
)


[docs]class DifferentialEvolution(SearchMethod): """A black-box adversarial search method using Differential Evolution (DE). This method searches for adversarial text examples by evolving a population of perturbation vectors and applying them to the input text. Only works with transformations that extend :class:`~textattack.transformations.word_swaps.WordSwapDifferentialEvolution`. """ def __init__(self, popsize=3, maxiter=5, verbose=False, max_perturbs=1): """A black-box adversarial search method that uses Differential Evolution to find perturbations that are imperceptible but fool a model.""" self.popsize = popsize self.maxiter = maxiter self.verbose = verbose self.max_perturbs = max_perturbs
[docs] def check_transformation_compatibility(self, transformation): if transformation_consists_of_word_swaps_differential_evolution(transformation): self.apply_perturbation = transformation.apply_perturbation self.get_bounds_and_precomputed = transformation.get_bounds_and_precomputed return True return False
@property def is_black_box(self): return True
[docs] def extra_repr_keys(self): return ["popsize", "maxiter", "max_perturbs", "verbose"]