You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 9.2 kB

1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <div align="center">
  2. [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ablkit)](https://pypi.org/project/ablkit/)
  3. [![PyPI version](https://badgen.net/pypi/v/ablkit)](https://pypi.org/project/ablkit/)
  4. [![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/AbductiveLearning/ABLKit/blob/main/LICENSE)
  5. [![flake8 Lint](https://github.com/AbductiveLearning/ABLKit/actions/workflows/lint.yaml/badge.svg)](https://github.com/AbductiveLearning/ABLKit/actions/workflows/lint.yaml)
  6. [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
  7. [![ABLKit-CI](https://github.com/AbductiveLearning/ABLKit/actions/workflows/build-and-test.yaml/badge.svg)](https://github.com/AbductiveLearning/ABLKit/actions/workflows/build-and-test.yaml)
  8. [📘Documentation](https://www.lamda.nju.edu.cn/abl_test/docs/build/html/index.html) |
  9. [📚Examples](https://github.com/AbductiveLearning/ABLKit/tree/main/examples) |
  10. [💬Reporting Issues](https://github.com/AbductiveLearning/ABLKit/issues/new)
  11. </div>
  12. # Abductive Learning (ABL) Kit
  13. **ABL Kit** is an efficient Python toolkit for **Abductive Learning (ABL)**.
  14. ABL is a novel paradigm that integrates machine learning and
  15. logical reasoning in a unified framework. It is suitable for tasks
  16. where both data and (logical) domain knowledge are available.
  17. Key Features of ABL Kit:
  18. - **Great Flexibility**: Adaptable to various machine learning modules and logical reasoning components.
  19. - **User-Friendly**: Provide data, model, and KB, and get started with just a few lines of code.
  20. - **High-Performance**: Optimization for high accuracy and fast training speed.
  21. ABL Kit encapsulates advanced ABL techniques, providing users with
  22. an efficient and convenient toolkit to develop dual-driven ABL systems,
  23. which leverage the power of both data and knowledge.
  24. ## Installation
  25. ### Install from PyPI
  26. The easiest way to install ABL Kit is using ``pip``:
  27. ```bash
  28. pip install ablkit
  29. ```
  30. ### Install from Source
  31. Alternatively, to install from source code, sequentially run following commands in your terminal/command line.
  32. ```bash
  33. git clone https://github.com/AbductiveLearning/ABLKit.git
  34. cd ABLKit
  35. pip install -v -e .
  36. ```
  37. ### (Optional) Install SWI-Prolog
  38. If the use of a [Prolog-based knowledge base](https://www.lamda.nju.edu.cn/abl_test/docs/build/html/Intro/Reasoning.html#prolog) is necessary, please also install [SWI-Prolog](https://www.swi-prolog.org/):
  39. For Linux users:
  40. ```bash
  41. sudo apt-get install swi-prolog
  42. ```
  43. For Windows and Mac users, please refer to the [SWI-Prolog Install Guide](https://github.com/yuce/pyswip/blob/master/INSTALL.md).
  44. ## Quick Start
  45. We use the MNIST Addition task as a quick start example. In this task, pairs of MNIST handwritten images and their sums are given, alongwith a domain knowledge base which contains information on how to perform addition operations. Our objective is to input a pair of handwritten images and accurately determine their sum.
  46. <details>
  47. <summary>Working with Data</summary>
  48. <br>
  49. ABL Kit requires data in the format of `(X, gt_pseudo_label, Y)` where `X` is a list of input examples containing instances, `gt_pseudo_label` is the ground-truth label of each example in `X` and `Y` is the ground-truth reasoning result of each example in `X`. Note that `gt_pseudo_label` is only used to evaluate the machine learning model's performance but not to train it.
  50. In the MNIST Addition task, the data loading looks like:
  51. ```python
  52. # The 'datasets' module below is located in 'examples/mnist_add/'
  53. from datasets import get_dataset
  54. # train_data and test_data are tuples in the format of (X, gt_pseudo_label, Y)
  55. train_data = get_dataset(train=True)
  56. test_data = get_dataset(train=False)
  57. ```
  58. </details>
  59. <details>
  60. <summary>Building the Learning Part</summary>
  61. <br>
  62. Learning part is constructed by first defining a base model for machine learning. ABL Kit offers considerable flexibility, supporting any base model that conforms to the scikit-learn style (which requires the implementation of fit and predict methods), or a PyTorch-based neural network (which has defined the architecture and implemented forward method). In this example, we build a simple LeNet5 network as the base model.
  63. ```python
  64. # The 'models' module below is located in 'examples/mnist_add/'
  65. from models.nn import LeNet5
  66. cls = LeNet5(num_classes=10)
  67. ```
  68. To facilitate uniform processing, ABL Kit provides the `BasicNN` class to convert a PyTorch-based neural network into a format compatible with scikit-learn models. To construct a `BasicNN` instance, aside from the network itself, we also need to define a loss function, an optimizer, and the computing device.
  69. ```python
  70. ​import torch
  71. ​from ablkit.learning import BasicNN
  72. ​loss_fn = torch.nn.CrossEntropyLoss()
  73. ​optimizer = torch.optim.RMSprop(cls.parameters(), lr=0.001, alpha=0.9)
  74. ​device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  75. ​base_model = BasicNN(model=cls, loss_fn=loss_fn, optimizer=optimizer, device=device)
  76. ```
  77. The base model built above is trained to make predictions on instance-level data (e.g., a single image), while ABL deals with example-level data. To bridge this gap, we wrap the base_model into an instance of `ABLModel`. This class serves as a unified wrapper for base models, facilitating the learning part to train, test, and predict on example-level data, (e.g., images that comprise an equation).
  78. ```python
  79. from ablkit.learning import ABLModel
  80. ​model = ABLModel(base_model)
  81. ```
  82. </details>
  83. <details>
  84. <summary>Building the Reasoning Part</summary>
  85. <br>
  86. To build the reasoning part, we first define a knowledge base by creating a subclass of `KBBase`. In the subclass, we initialize the `pseudo_label_list` parameter and override the `logic_forward` method, which specifies how to perform (deductive) reasoning that processes pseudo-labels of an example to the corresponding reasoning result. Specifically, for the MNIST Addition task, this `logic_forward` method is tailored to execute the sum operation.
  87. ```python
  88. from ablkit.reasoning import KBBase
  89. class AddKB(KBBase):
  90. def __init__(self, pseudo_label_list=list(range(10))):
  91. super().__init__(pseudo_label_list)
  92. ​ def logic_forward(self, nums):
  93. return sum(nums)
  94. kb = AddKB()
  95. ```
  96. Next, we create a reasoner by instantiating the class `Reasoner`, passing the knowledge base as a parameter. Due to the indeterminism of abductive reasoning, there could be multiple candidate pseudo-labels compatible to the knowledge base. In such scenarios, the reasoner can minimize inconsistency and return the pseudo-label with the highest consistency.
  97. ```python
  98. from ablkit.reasoning import Reasoner
  99. reasoner = Reasoner(kb)
  100. ```
  101. </details>
  102. <details>
  103. <summary>Building Evaluation Metrics</summary>
  104. <br>
  105. ABL Kit provides two basic metrics, namely `SymbolAccuracy` and `ReasoningMetric`, which are used to evaluate the accuracy of the machine learning model's predictions and the accuracy of the `logic_forward` results, respectively.
  106. ```python
  107. from ablkit.data.evaluation import ReasoningMetric, SymbolAccuracy
  108. metric_list = [SymbolAccuracy(), ReasoningMetric(kb=kb)]
  109. ```
  110. </details>
  111. <details>
  112. <summary>Bridging Learning and Reasoning</summary>
  113. <br>
  114. Now, we use `SimpleBridge` to combine learning and reasoning in a
  115. unified ABL framework.
  116. ```python
  117. from ablkit.bridge import SimpleBridge
  118. bridge = SimpleBridge(model, reasoner, metric_list)
  119. ```
  120. Finally, we proceed with training and testing.
  121. ```python
  122. ​bridge.train(train_data, loops=1, segment_size=0.01)
  123. bridge.test(test_data)
  124. ```
  125. </details>
  126. To explore detailed tutorials and information, please refer to - [document](https://www.lamda.nju.edu.cn/abl_test/docs/build/html/index.html).
  127. ## Examples
  128. We provide several examples in `examples/`. Each example is stored in a separate folder containing a README file.
  129. + [MNIST Addition](https://github.com/AbductiveLearning/ABLKit/tree/main/examples/mnist_add)
  130. + [Handwritten Formula (HWF)](https://github.com/AbductiveLearning/ABLKit/tree/main/examples/hwf)
  131. + [Handwritten Equation Decipherment](https://github.com/AbductiveLearning/ABLKit/tree/main/examples/hed)
  132. + [Zoo](https://github.com/AbductiveLearning/ABLKit/tree/main/examples/zoo)
  133. ## References
  134. For more information about ABL, please refer to: [Zhou, 2019](http://scis.scichina.com/en/2019/076101.pdf) and [Zhou and Huang, 2022](https://www.lamda.nju.edu.cn/publication/chap_ABL.pdf).
  135. ```latex
  136. @article{zhou2019abductive,
  137. title = {Abductive learning: towards bridging machine learning and logical reasoning},
  138. author = {Zhou, Zhi-Hua},
  139. journal = {Science China Information Sciences},
  140. volume = {62},
  141. number = {7},
  142. pages = {76101},
  143. year = {2019}
  144. }
  145. @incollection{zhou2022abductive,
  146. title = {Abductive Learning},
  147. author = {Zhou, Zhi-Hua and Huang, Yu-Xuan},
  148. booktitle = {Neuro-Symbolic Artificial Intelligence: The State of the Art},
  149. editor = {Pascal Hitzler and Md. Kamruzzaman Sarker},
  150. publisher = {{IOS} Press},
  151. pages = {353--369},
  152. address = {Amsterdam},
  153. year = {2022}
  154. }
  155. ```

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.