Skip to main content

Deep logic: Interpretable neural networks in Python.

Project description

Welcome to Deep Logic

Travis (.org) Codecov

Read the Docs (version) Requires.io

PyPI license PyPI

Deep Logic is a python package providing a set of utilities to build deep learning models that are explainable by design.

This library provides APIs to get first-order logic explanations from neural networks.

Quick start

You can install Deep Logic along with all its dependencies from PyPI:

pip install -r requirements.txt deep-logic

Example

First of all we need to import some useful libraries:

import torch
import numpy as np
import deep_logic as dl

In most cases it is recommended to fix the random seed for reproducibility:

set_seed(0)

For this simple experiment, let’s set up a simple toy problem as the XOR problem (plus 2 dummy features):

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()

We can instantiate a simple feed-forward neural network with 3 layers:

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)

Before training the network, we should validate the input data. The only requirement is the following for all the input features to be in [0,1].

dl.validate_data(x_train)

We can now train the network:

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}')

Once trained we can extract first-order logic formulas describing local explanations of the prediction for a specific input by looking at the reduced model:

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)

The local explanation will be a given in terms of conjunctions of input features which are locally relevant (the dummy features will be discarded thanks to pruning). For this specific input, the explanation would be ~f1 AND f2.

Finally the fol package can be used to generate global explanations of the predictions for a specific class:

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}')

The global explanation is given in a disjunctive normal form for a specified class. For this problem the generated explanation for class y=1 is (f1 AND ~f2) OR (f2 AND ~f1) which corresponds to f1 XOR f2 (i.e. the exclusive OR function).

Theory

Theoretical foundations can be found in the following papers.

Learning of constraints:

@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}
}

Learning with constraints:

@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}
}

Constraints theory in machine learning:

@book{gori2017machine,
  title={Machine Learning: A constraint-based approach},
  author={Gori, Marco},
  year={2017},
  publisher={Morgan Kaufmann}
}

Authors

  • Pietro Barbiero, University ofCambridge, UK.

  • Francesco Giannini, University of Florence, IT.

  • Gabriele Ciravegna, University of Florence, IT.

  • Dobrik Georgiev, University of Cambridge, UK.

Licence

Copyright 2020 Pietro Barbiero, Francesco Giannini, Gabriele Ciravegna, and Dobrik Georgiev.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and limitations under the License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deep-logic-4.0.2.tar.gz (66.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

deep_logic-4.0.2-py3-none-any.whl (96.7 kB view details)

Uploaded Python 3

File details

Details for the file deep-logic-4.0.2.tar.gz.

File metadata

  • Download URL: deep-logic-4.0.2.tar.gz
  • Upload date:
  • Size: 66.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.22.0 setuptools/45.2.0.post20200210 requests-toolbelt/0.9.1 tqdm/4.42.1 CPython/3.8.1

File hashes

Hashes for deep-logic-4.0.2.tar.gz
Algorithm Hash digest
SHA256 1835dfe4cea01a4687210da1fd4e893c971a6935d8ea54dce2f5bd2e79787ce9
MD5 66060cbb3e5cab9ec110f6bd336ef0c3
BLAKE2b-256 5acbabd929fe26fbf4503e12315ebf049b50f689b69138d4f1eab27af997de1e

See more details on using hashes here.

File details

Details for the file deep_logic-4.0.2-py3-none-any.whl.

File metadata

  • Download URL: deep_logic-4.0.2-py3-none-any.whl
  • Upload date:
  • Size: 96.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.22.0 setuptools/45.2.0.post20200210 requests-toolbelt/0.9.1 tqdm/4.42.1 CPython/3.8.1

File hashes

Hashes for deep_logic-4.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 75f2691c10938bc4a445953d0fccac3d37006225b01456a5c056cfcb2b2ecfc5
MD5 343e40bfed9370dafeeca0d984812e0d
BLAKE2b-256 0fed2d07bd3fc4c159aaf92f19e82c1cfb08544686bb48fe1e8bf0b880c54cf0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page