|
""" |
|
|
|
Improved Genetic Algorithm |
|
============================= |
|
|
|
(Natural Language Adversarial Attacks and Defenses in Word Level) |
|
|
|
""" |
|
from textattack import Attack |
|
from textattack.constraints.overlap import MaxWordsPerturbed |
|
from textattack.constraints.pre_transformation import StopwordModification |
|
from textattack.constraints.semantics import WordEmbeddingDistance |
|
from textattack.goal_functions import UntargetedClassification |
|
from textattack.search_methods import ImprovedGeneticAlgorithm |
|
from textattack.transformations import WordSwapEmbedding |
|
|
|
from .attack_recipe import AttackRecipe |
|
|
|
|
|
class IGAWang2019(AttackRecipe): |
|
"""Xiaosen Wang, Hao Jin, Kun He (2019). |
|
|
|
Natural Language Adversarial Attack and Defense in Word Level. |
|
|
|
http://arxiv.org/abs/1909.06723 |
|
""" |
|
|
|
@staticmethod |
|
def build(model_wrapper): |
|
|
|
|
|
|
|
|
|
|
|
transformation = WordSwapEmbedding(max_candidates=50) |
|
|
|
|
|
|
|
constraints = [StopwordModification()] |
|
|
|
|
|
|
|
constraints.append(MaxWordsPerturbed(max_percent=0.2)) |
|
|
|
|
|
|
|
constraints.append( |
|
WordEmbeddingDistance(max_mse_dist=0.5, compare_against_original=False) |
|
) |
|
|
|
|
|
|
|
goal_function = UntargetedClassification(model_wrapper) |
|
|
|
|
|
|
|
|
|
search_method = ImprovedGeneticAlgorithm( |
|
pop_size=60, |
|
max_iters=20, |
|
max_replace_times_per_index=5, |
|
post_crossover_check=False, |
|
) |
|
|
|
return Attack(goal_function, constraints, transformation, search_method) |
|
|