如何使用OpenAttack進(jìn)行文本對抗攻擊
關(guān)于OpenAttack
OpenAttack是一款專為文本對抗攻擊設(shè)計(jì)的開源工具套件,該工具基于Python開發(fā),可以處理文本對抗攻擊的整個(gè)過程,包括預(yù)處理文本、訪問目標(biāo)用戶模型、生成對抗示例和評估攻擊模型等等。
功能&使用
OpenAttack支持以下幾種功能:
- 高可用性:OpenAttack提供了易于使用的API,可以支持文本對抗攻擊的整個(gè)過程;
- 全面覆蓋攻擊模型類型:OpenAttack支持句子/單詞/字符級擾動和梯度/分?jǐn)?shù)/基于決策/盲攻擊模型;
- 靈活性強(qiáng)&可擴(kuò)展:我們可以輕松攻擊定制目標(biāo)用戶模型,或開發(fā)和評估定制的攻擊模型;
- 綜合評估:OpenAttack可以從攻擊有效性、對抗示例質(zhì)量和攻擊效率等方面全面評估攻擊模型;
OpenAttack的使用范圍非常廣,其中包括但不限于:
- 為攻擊模型提供各種評估基線;
- 使用其全面評估指標(biāo)綜合評估攻擊模型;
- 借助通用攻擊組件,協(xié)助快速開發(fā)新的攻擊模型;
- 評估機(jī)器學(xué)習(xí)模型對各種對抗攻擊的魯棒性;
- 通過使用生成的對抗示例豐富訓(xùn)練數(shù)據(jù),進(jìn)行對抗訓(xùn)練以提高機(jī)器學(xué)習(xí)模型的魯棒性;
工具模塊
工具安裝
我們可以使用pip安裝,或者克隆該項(xiàng)目源碼來安裝OpenAttack。
使用pip安裝(推薦):
- pip install OpenAttack
克隆代碼庫:
- git clone https://github.com/thunlp/OpenAttack.git
- cd OpenAttack
- python setup.py install
安裝完成之后,我們可以嘗試運(yùn)行“demo.py”來檢測OpenAttack是否能夠正常工作:
使用樣例
(1) 基礎(chǔ)使用:使用內(nèi)置攻擊模型
OpenAttack內(nèi)置了一些常用的文本分類模型,如LSTM和BERT,以及用于情感分析的SST和用于自然語言推理的SNLI等數(shù)據(jù)集。
以下代碼段顯示了如何使用基于遺傳算法的攻擊模型攻擊SST數(shù)據(jù)集上的BERT:
- import OpenAttack as oa
- # choose a trained victim classification model
- victim = oa.DataManager.load("Victim.BERT.SST")
- # choose an evaluation dataset
- dataset = oa.DataManager.load("Dataset.SST.sample")
- # choose Genetic as the attacker and initialize it with default parameters
- attacker = oa.attackers.GeneticAttacker()
- # prepare for attacking
- attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)
- # launch attacks and print attack results
- attack_eval.eval(dataset, visualize=True)
(2) 高級使用:攻擊自定義目標(biāo)用戶模型
下面的代碼段顯示了如何使用基于遺傳算法的攻擊模型攻擊SST上的自定義情緒分析模型:
- import OpenAttack as oa
- import numpy as np
- from nltk.sentiment.vader import SentimentIntensityAnalyzer
- # configure access interface of the customized victim model
- class MyClassifier(oa.Classifier):
- def __init__(self):
- self.model = SentimentIntensityAnalyzer()
- # access to the classification probability scores with respect input sentences
- def get_prob(self, input_):
- rt = []
- for sent in input_:
- rs = self.model.polarity_scores(sent)
- prob = rs["pos"] / (rs["neg"] + rs["pos"])
- rt.append(np.array([1 - prob, prob]))
- return np.array(rt)
- # choose the costomized classifier as the victim model
- victim = MyClassifier()
- # choose an evaluation dataset
- dataset = oa.DataManager.load("Dataset.SST.sample")
- # choose Genetic as the attacker and initialize it with default parameters
- attacker = oa.attackers.GeneticAttacker()
- # prepare for attacking
- attack_eval = oa.attack_evals.DefaultAttackEval(attacker, victim)
- # launch attacks and print attack results
- attack_eval.eval(dataset, visualize=True)
項(xiàng)目地址
OpenAttack:【GitHub傳送門】