Skip to main content

安全且可解释的机器学习库

项目描述

SecML:Python 中安全且可解释的机器学习

状态阿尔法 Python 3.6 |  3.7 |  3.8 平台 Linux |  macOS |  视窗 阿帕奇许可证 2.0

SecML 是一个开源 Python 库,用于机器学习算法的安全评估。它配备了规避投毒对抗性机器学习攻击,它可以包装来自其他不同框架的模型和攻击。

目录

入门

SecML 可以在 Python >= 3.6 上运行,无需额外的配置步骤,因为它的所有依赖项都可以作为主要 macOS 版本、Linux 发行版和 Windows 的轮包提供。

安装

  1. 安装最新版本setuptools
pip install -U setuptools
  1. 从官方 PyPI 存储库安装:
pip install secml

在所有情况下,安装过程都会尝试安装正确的依赖项。如果在安装过程中出现问题,请尝试通过调用首先安装依赖项:

pip install -r requirements.txt

额外组件

SecML 附带了一组附加组件,如果需要,可以安装这些组件。要指定要安装的额外组件,请[extras]在调用pip install. extras将是您要安装的组件的逗号分隔列表。例子:

pip install secml[extra1,extra2]

可以使用以下额外组件:

  • pytorch: 通过PyTorch深度学习平台的神经网络 (NNs) 。
    安装:torch >= 1.4torchvision >= 0.5
    仅限 Windows:安装档案的 url 应手动提供为 pip install secml[pytorch] -f https://download.pytorch.org/whl/torch_stable.html.
  • foolbox: Foolbox的包装器,一个 Python 工具箱,用于创建欺骗神经网络的对抗性示例。
    安装:foolbox >= 3.3.0, eagerpy >= 0.29.0, torch >= 1.4,torchvision >= 0.5
  • cleverhansCleverHans的包装器,这是一个 Python 库,用于将机器学习系统的漏洞基准测试为对抗性示例。
    安装:tensorflow >= 1.14.*, < 2cleverhans < 3.1
    警告:不适用于python >= 3.8
  • tf-gpu:安装带有 GPU 支持的软件包的快捷方式TensorFlow(仅限 Linux 和 Windows)。
    安装:tensorflow-gpu >= 1.14.*, < 2
    警告:不适用于python >= 3.8

高级功能

要支持其他高级功能(如 GPU 的使用),可能需要更多软件包,具体取决于所使用的操作系统:

用法

在这里,我们展示了 SecML 库的一些关键特性。

广泛支持的 ML 算法。支持的所有监督学习算法scikit-learn均可用:

# Wrapping a scikit-learn classifier
from sklearn.svm import SVC
from secml.ml.classifiers import CClassifierSkLearn
model = SVC()
secml_model = CClassifierSkLearn(model)

此外,SecML 通过PyTorch深度学习平台支持神经网络 (NN):

# Wrapping a Pytorch network
from torchvision.models import resnet18
from secml.ml.classifiers import CClassifierPyTorch
model = resnet18(pretrained=True)
secml_model = CClassifierPyTorch(model, input_shape=(3, 224, 224))

数据集的管理。SecML 可以将样本和标签捆绑在一个对象中:

from secml.array import CArray
from secml.data import CDataset

x = CArray.randn((200, 10))
y = CArray.zeros(200)
dataset = CDataset(x, y)

此外,您还可以加载著名的数据集:

from secml.data.loader import CDataLoaderMNIST
digits = (1, 5, 9)  # load subset of digits
loader = CDataLoaderMNIST()
num_samples = 200
train_set = loader.load('training', digits=digits)
test_set = loader.load('testing', digits=digits, num_samples=num_samples)

内置攻击算法。基于定制开发的快速求解器的规避和中毒攻击。此外,我们还提供与其他第三方对抗机器学习库的连接器。

from secml.adv.attacks import CAttackEvasionPGD

distance = 'l2'  # type of perturbation 'l1' or 'l2'
dmax = 2.5  # maximum perturbation
lb, ub = 0., 1.  # bounds of the attack space. None for unbounded
y_target = None  # None if untargeted, specify target label otherwise

# Should be chosen depending on the optimization problem
solver_params = {
    'eta': 0.5, # step size of the attack
    'max_iter': 100, # number of gradient descent steps
}

attack = CAttackEvasionPGD(classifier=secml_model,
                           distance=distance,
                           dmax=dmax,
                           solver_params=solver_params,
                           y_target=y_target)

adv_pred, scores, adv_ds, f_obj = attack.run(x, y)

可以在此笔记本中找到涵盖 SecML 中内置的规避和中毒攻击的更详细示例。

其他对抗性框架的包装。也可以使用其他框架来实例化攻击。特别是,SecML 可以利用foolbox和的算法cleverhans

from secml.adv.attacks import CFoolboxPGDL2
y_target = None
steps = 100
epsilon = 1.0 # maximum perturbation
attack = CFoolboxPGDL2(classifier=secml_model,
                       y_target=y_target,
                       epsilons=epsilon,
                       steps=steps)

adv_pred, scores, adv_ds, f_obj = attack.run(x, y)

可以在笔记本中找到涵盖从其他库包装的攻击的更详细示例。

密集/稀疏数据支持。我们在单个数据结构中为密集(通过numpy库)和稀疏数据(通过库)提供全面、透明的支持。scipy

from secml.array import CArray

x = CArray.zeros((4, 4))
x[0, 2] = 1
print(x)

"""
>> CArray([[0. 0. 1. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]])
"""
x = x.tosparse()
print(x) 

"""
>>  CArray((0, 2)  1.0)
"""

可以在笔记本中找到更详细的示例,该示例涵盖了在 Android 恶意软件分类中的应用程序使用稀疏数据。

可视化您的结果。我们提供基于广为人知的库matplotlib的可视化和绘图框架。

from secml.figure import CFigure
from secml.optim.constraints import CConstraintL2

fig = CFigure(width=5, height=5, markersize=12)

fig.subplot(1, 2, 1)

# Plot the attack objective function
fig.sp.plot_fun(attack.objective_function, 
                plot_levels=False,
                n_grid_points=200)

# Plot the decision boundaries of the classifier
fig.sp.plot_decision_regions(secml_model, 
                             plot_background=False, 
                             n_grid_points=200)

# Plot the optimization sequence
fig.sp.plot_path(attack.x_seq)

# Plot a constraint
fig.sp.plot_constraint(constraint)

fig.title("SecML example")

fig.show()

解释你的结果。可解释的机器学习方法,通过有影响力的特征和原型来解释模型决策。

from src.secml.explanation import CExplainerIntegratedGradients

# Compute explanations (attributions) w.r.t. each class
attributions = CArray.empty(shape=(dataset.num_classes, x.size))
for c in dataset.classes:
    attributions_c = CExplainerIntegratedGradients(clf).explain(x, y=c)
    attributions[c, :] = attributions_c

# Visualize the explanations
fig = CFigure()

# Threshold to plot positive and negative relevance values symmetrically
threshold = max(abs(attributions.min()), abs(attributions.max()))

# Plot explanations
for c in dataset.classes:
    fig.sp.imshow(attributions[c, :].reshape((dataset.header.img_h, 
                                              dataset.header.img_w)),
                  cmap='seismic', vmin=-1 * threshold, vmax=threshold)
    fig.sp.yticks([])
    fig.sp.xticks([])
fig.show()

可以在笔记本中找到涵盖可解释性技术的更详细示例。

模型动物园。使用我们预先训练的模型来节省时间并轻松复制科学结果。

from secml.model_zoo import load_model
clf = load_model('mnist159-cnn')

教程

我们提供了涵盖 SecML 更高级用法的教程,它们可以在教程文件夹中找到。

贡献

贡献和开发者指南可在以下网址获得: https ://secml.readthedocs.io/en/latest/developers/

如何引用 SecML

如果您在科学出版物中使用 SecML,请引用以下论文:

secml:用于安全和可解释机器学习的 Python 库,Melis等人。, arXiv 预印本 arXiv:1912.10013 (2019)。

@article{melis2019secml,
  title={secml: A Python Library for Secure and Explainable Machine Learning},
  author={Melis, Marco and Demontis, Ambra and Pintor, Maura and Sotgiu, Angelo and Biggio, Battista},
  journal={arXiv preprint arXiv:1912.10013},
  year={2019}
}

联系人

联系我们的最佳方式是打开问题。但是,如果您想联系我们,您可以发送电子邮件至:

致谢

SecML 在欧盟的 ALOHA 项目Horizo​​n 2020 研究和创新计划的支持下得到了部分开发,授权协议号 780788。

版权

SecML 由PRALab - 模式识别和应用实验室Pluribus One srlApache 许可证 2.0下开发。版权所有。