深层逻辑:Python 中可解释的神经网络。
项目描述
欢迎来到深度逻辑
Deep Logic 是一个 python 包,提供了一组实用程序来构建可通过设计解释的深度学习模型。
该库提供 API 以从神经网络中获取一阶逻辑解释。
快速开始
您可以从PyPI安装 Deep Logic 及其所有依赖 项:
pip install -r requirements.txt deep-logic
例子
首先我们需要导入一些有用的库:
import torch
import numpy as np
import deep_logic as dl
在大多数情况下,建议修复随机种子以获得可重复性:
set_seed(0)
对于这个简单的实验,让我们设置一个简单的玩具问题作为 XOR 问题(加上 2 个虚拟特征):
x_train = torch.tensor([
[0, 0, 0, 1],
[0, 1, 0, 1],
[1, 0, 0, 1],
[1, 1, 0, 1],
], dtype=torch.float)
y_train = torch.tensor([0, 1, 1, 0], dtype=torch.float).unsqueeze(1)
xnp = x_train.detach().numpy()
ynp = y_train.detach().numpy().ravel()
我们可以实例化一个简单的 3 层前馈神经网络:
layers = [
torch.nn.Linear(x_train.size(1), 10),
torch.nn.LeakyReLU(),
torch.nn.Linear(10, 4),
torch.nn.LeakyReLU(),
torch.nn.Linear(4, 1),
torch.nn.Sigmoid(),
]
model = torch.nn.Sequential(*layers)
在训练网络之前,我们应该验证输入数据。唯一的要求是所有输入特征都在[0,1]中。
dl.validate_data(x_train)
我们现在可以训练网络:
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
model.train()
need_pruning = True
for epoch in range(1000):
# forward pass
optimizer.zero_grad()
y_pred = model(x_train)
# Compute Loss
loss = torch.nn.functional.binary_crossentropy_loss(y_pred, y_train)
# A bit of L1 regularization will encourage sparsity
for module in model.children():
if isinstance(module, torch.nn.Linear):
loss += 0.001 * torch.norm(module.weight, 1)
# We can use sparsity to prune dummy features
if epoch > 500 and need_pruning:
dl.utils.relu_nn.prune_features(model, n_classes)
need_pruning = False
# backward pass
loss.backward()
optimizer.step()
# compute accuracy
if epoch % 100 == 0:
y_pred_d = (y_pred > 0.5)
accuracy = (y_pred_d.eq(y_train).sum(dim=1) == y_train.size(1)).sum().item() / y_train.size(0)
print(f'Epoch {epoch}: train accuracy: {accuracy:.4f}')
一旦经过训练,我们可以通过查看简化模型来提取描述特定输入预测的局部解释的一阶逻辑公式:
explanation = dl.logic.explain_local(model, x_train, y_train, x_sample=x[1],
method='pruning', target_class=1,
concept_names=['f1', 'f2', 'f3', 'f4'])
print(explanation)
局部解释将根据与局部相关的输入特征的结合给出(由于修剪,虚拟特征将被丢弃)。对于这个特定的输入,解释是 ~f1 AND f2。
最后,fol包可用于生成特定类预测的全局解释:
global_explanation, _, _ = dl.logic.relu_nn.combine_local_explanations(model, x_train,
y_train.squeeze(),
target_class=1,
method='pruning')
accuracy, _ = dl.logic.base.test_explanation(global_explanation, target_class=1, x_train, y_train)
explanation = dl.logic.base.replace_names(global_explanation, concept_names=['f1', 'f2', 'f3', 'f4'])
print(f'Accuracy when using the formula {explanation}: {accuracy:.4f}')
全局解释以指定类的析取范式给出。对于这个问题,生成的类y=1的解释是 (f1 AND ~f2) OR (f2 AND ~f1) ,它对应于f1 XOR f2 (即异或函数)。
理论
理论基础可以在以下论文中找到。
学习约束:
@inproceedings{ciravegna2020constraint,
title={A Constraint-Based Approach to Learning and Explanation.},
author={Ciravegna, Gabriele and Giannini, Francesco and Melacci, Stefano and Maggini, Marco and Gori, Marco},
booktitle={AAAI},
pages={3658--3665},
year={2020}
}
有约束的学习:
@inproceedings{marra2019lyrics,
title={LYRICS: A General Interface Layer to Integrate Logic Inference and Deep Learning},
author={Marra, Giuseppe and Giannini, Francesco and Diligenti, Michelangelo and Gori, Marco},
booktitle={Joint European Conference on Machine Learning and Knowledge Discovery in Databases},
pages={283--298},
year={2019},
organization={Springer}
}
机器学习中的约束理论:
@book{gori2017machine,
title={Machine Learning: A constraint-based approach},
author={Gori, Marco},
year={2017},
publisher={Morgan Kaufmann}
}
执照
版权所有 2020 Pietro Barbiero、Francesco Giannini、Gabriele Ciravegna 和 Dobrik Georgiev。
根据 Apache 许可证 2.0 版(“许可证”)获得许可;除非遵守许可,否则您不得使用此文件。您可以在以下网址获取许可证副本:http: //www.apache.org/licenses/LICENSE-2.0。
除非适用法律要求或书面同意,否则根据许可分发的软件将按“原样”分发,没有任何明示或暗示的保证或条件。
有关许可下的特定语言管理权限和限制,请参阅许可。