一、背景
TextAttack是弗吉尼亞大學和MIT開發的一個關於快速實現文本對抗攻擊的一個工具包。國內有一個清華開發的工具OpenAttack。但是目前比較活躍的是TextAttack,寫這篇博客的時候,TextAttack還做了更新。
二、安裝
TextAttack發行了PyPI的包,直接通過下面的指令安裝,要求是Python高於3.6的版本:
pip install textattack
三、使用
3.1 端到端的使用
TextAttack可以使用以下的指令在端到端實現攻擊。
textattack attack
--model bert-base-uncased
--num-examples -1
--transformation word-swap-embedding
--constraints use repeat stopword max-words-perturbed^max_num_words=3 embedding^min_cos_sim=0.8 part-of-speech
--goal-function untargeted-classification
--attack-recipe textfooler
--log-to-csv ./bert_convid_textfooler.csv
--dataset-from-file subjectivity_data_trans.py
參數名 | 含義 |
---|---|
model | 指定使用的模型,可以從huggingface下載,也可以在本地加載,需要使用pytorch |
num-examples | 轉換的數量,-1表示所有 |
transformation | 對文本輸入的轉換,分爲轉義和同義詞兩大類 |
constraints | 對抗攻擊需要的約束 |
goal-function | 攻擊的目標 |
attack-recipe | 攻擊的方法,可用的攻擊方法 |
log-to-csv | 輸出到文件的信息 |
dataset-from-file | 使用自定的數據集,也可以使用內置的數據,如果使用內置的數據就是在模型後面帶上數據集 |
3.2 dataset-from-file的例子
使用下面的代碼,就可以完成加載自己的數據集。
import pandas as pd
from textattack.datasets import Dataset
dataset_name = "convid"
# 讀取自定義數據集
pf = pd.read_csv(f"./{dataset_name}_test.csv")
dataset = Dataset(list(zip(pf["text"], pf["label"])))