|
""" |
|
|
|
Alzantot Genetic Algorithm |
|
======================================= |
|
(Generating Natural Language Adversarial Examples) |
|
|
|
.. warning:: |
|
This attack uses a very slow language model. Consider using the ``fast-alzantot`` |
|
recipe instead. |
|
|
|
""" |
|
|
|
from textattack import Attack |
|
from textattack.constraints.grammaticality.language_models import ( |
|
Google1BillionWordsLanguageModel, |
|
) |
|
from textattack.constraints.overlap import MaxWordsPerturbed |
|
from textattack.constraints.pre_transformation import ( |
|
InputColumnModification, |
|
RepeatModification, |
|
StopwordModification, |
|
) |
|
from textattack.constraints.semantics import WordEmbeddingDistance |
|
from textattack.goal_functions import UntargetedClassification |
|
from textattack.search_methods import AlzantotGeneticAlgorithm |
|
from textattack.transformations import WordSwapEmbedding |
|
|
|
from .attack_recipe import AttackRecipe |
|
|
|
|
|
class GeneticAlgorithmAlzantot2018(AttackRecipe): |
|
"""Alzantot, M., Sharma, Y., Elgohary, A., Ho, B., Srivastava, M.B., & |
|
Chang, K. (2018). |
|
|
|
Generating Natural Language Adversarial Examples. |
|
|
|
https://arxiv.org/abs/1804.07998 |
|
""" |
|
|
|
@staticmethod |
|
def build(model_wrapper): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
transformation = WordSwapEmbedding(max_candidates=8) |
|
|
|
|
|
|
|
constraints = [RepeatModification(), StopwordModification()] |
|
|
|
|
|
|
|
|
|
input_column_modification = InputColumnModification( |
|
["premise", "hypothesis"], {"premise"} |
|
) |
|
constraints.append(input_column_modification) |
|
|
|
|
|
|
|
constraints.append(MaxWordsPerturbed(max_percent=0.2)) |
|
|
|
|
|
|
|
constraints.append( |
|
WordEmbeddingDistance(max_mse_dist=0.5, compare_against_original=False) |
|
) |
|
|
|
|
|
|
|
constraints.append( |
|
Google1BillionWordsLanguageModel( |
|
top_n_per_index=4, compare_against_original=False |
|
) |
|
) |
|
|
|
|
|
|
|
goal_function = UntargetedClassification(model_wrapper) |
|
|
|
|
|
|
|
search_method = AlzantotGeneticAlgorithm( |
|
pop_size=60, max_iters=20, post_crossover_check=False |
|
) |
|
|
|
return Attack(goal_function, constraints, transformation, search_method) |
|
|