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 10 kB

1 year ago
1 year ago
1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <div align="center">
  2. <img src="https://raw.githubusercontent.com/AbductiveLearning/ABLkit/main/docs/_static/img/logo.png" width="180">
  3. [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ablkit)](https://pypi.org/project/ablkit/) [![PyPI version](https://badgen.net/pypi/v/ablkit)](https://pypi.org/project/ablkit/) [![Documentation Status](https://readthedocs.org/projects/ablkit/badge/?version=latest)](https://ablkit.readthedocs.io/en/latest/?badge=latest) [![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/AbductiveLearning/ABLkit/blob/main/LICENSE) [![flake8 Lint](https://github.com/AbductiveLearning/ABLkit/actions/workflows/lint.yaml/badge.svg)](https://github.com/AbductiveLearning/ABLkit/actions/workflows/lint.yaml) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![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)
  4. [📘Documentation](https://ablkit.readthedocs.io/en/latest/index.html) | [📄Paper](https://journal.hep.com.cn/fcs/EN/10.1007/s11704-024-40085-7) | [📚Examples](https://github.com/AbductiveLearning/ABLkit/tree/main/examples) | [💬Reporting Issues](https://github.com/AbductiveLearning/ABLkit/issues/new)
  5. </div>
  6. # ABLkit: A Toolkit for Abductive Learning
  7. **ABLkit** is an efficient Python toolkit for [**Abductive Learning (ABL)**](https://www.lamda.nju.edu.cn/publication/chap_ABL.pdf). ABL is a novel paradigm that integrates machine learning and logical reasoning in a unified framework. It is suitable for tasks where both data and (logical) domain knowledge are available.
  8. <p align="center">
  9. <img src="https://raw.githubusercontent.com/AbductiveLearning/ABLkit/main/docs/_static/img/ABL.png" alt="Abductive Learning" style="width: 80%;"/>
  10. </p>
  11. Key Features of ABLkit:
  12. - **High Flexibility**: Compatible with various machine learning modules and logical reasoning components.
  13. - **Easy-to-Use Interface**: Provide data, model, and knowledge, and get started with just a few lines of code.
  14. - **Optimized Performance**: Optimization for high performance and accelerated training speed.
  15. ABLkit encapsulates advanced ABL techniques, providing users with an efficient and convenient toolkit to develop dual-driven ABL systems, which leverage the power of both data and knowledge.
  16. <p align="center">
  17. <img src="https://raw.githubusercontent.com/AbductiveLearning/ABLkit/main/docs/_static/img/ABLkit.png" alt="ABLkit" style="width: 80%;"/>
  18. </p>
  19. ## Installation
  20. ### Install from PyPI
  21. The easiest way to install ABLkit is using ``pip``:
  22. ```bash
  23. pip install ablkit
  24. ```
  25. ### Install from Source
  26. Alternatively, to install from source code, sequentially run following commands in your terminal/command line.
  27. ```bash
  28. git clone https://github.com/AbductiveLearning/ABLkit.git
  29. cd ABLkit
  30. pip install -v -e .
  31. ```
  32. ### (Optional) Install SWI-Prolog
  33. If the use of a [Prolog-based knowledge base](https://ablkit.readthedocs.io/en/latest/Intro/Reasoning.html#prolog) is necessary, please also install [SWI-Prolog](https://www.swi-prolog.org/):
  34. For Linux users:
  35. ```bash
  36. sudo apt-get install swi-prolog
  37. ```
  38. For Windows and Mac users, please refer to the [SWI-Prolog Install Guide](https://github.com/yuce/pyswip/blob/master/INSTALL.md).
  39. ## Quick Start
  40. 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.
  41. <details>
  42. <summary>Working with Data</summary>
  43. <br>
  44. ABLkit 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.
  45. In the MNIST Addition task, the data loading looks like:
  46. ```python
  47. # The 'datasets' module below is located in 'examples/mnist_add/'
  48. from datasets import get_dataset
  49. # train_data and test_data are tuples in the format of (X, gt_pseudo_label, Y)
  50. train_data = get_dataset(train=True)
  51. test_data = get_dataset(train=False)
  52. ```
  53. </details>
  54. <details>
  55. <summary>Building the Learning Part</summary>
  56. <br>
  57. Learning part is constructed by first defining a base model for machine learning. ABLkit 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.
  58. ```python
  59. # The 'models' module below is located in 'examples/mnist_add/'
  60. from models.nn import LeNet5
  61. cls = LeNet5(num_classes=10)
  62. ```
  63. To facilitate uniform processing, ABLkit 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.
  64. ```python
  65. ​import torch
  66. ​from ablkit.learning import BasicNN
  67. ​loss_fn = torch.nn.CrossEntropyLoss()
  68. ​optimizer = torch.optim.RMSprop(cls.parameters(), lr=0.001, alpha=0.9)
  69. ​device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  70. ​base_model = BasicNN(model=cls, loss_fn=loss_fn, optimizer=optimizer, device=device)
  71. ```
  72. 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).
  73. ```python
  74. from ablkit.learning import ABLModel
  75. ​model = ABLModel(base_model)
  76. ```
  77. </details>
  78. <details>
  79. <summary>Building the Reasoning Part</summary>
  80. <br>
  81. 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.
  82. ```python
  83. from ablkit.reasoning import KBBase
  84. class AddKB(KBBase):
  85. def __init__(self, pseudo_label_list=list(range(10))):
  86. super().__init__(pseudo_label_list)
  87. ​ def logic_forward(self, nums):
  88. return sum(nums)
  89. kb = AddKB()
  90. ```
  91. 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.
  92. ```python
  93. from ablkit.reasoning import Reasoner
  94. reasoner = Reasoner(kb)
  95. ```
  96. </details>
  97. <details>
  98. <summary>Building Evaluation Metrics</summary>
  99. <br>
  100. ABLkit 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.
  101. ```python
  102. from ablkit.data.evaluation import ReasoningMetric, SymbolAccuracy
  103. metric_list = [SymbolAccuracy(), ReasoningMetric(kb=kb)]
  104. ```
  105. </details>
  106. <details>
  107. <summary>Bridging Learning and Reasoning</summary>
  108. <br>
  109. Now, we use `SimpleBridge` to combine learning and reasoning in a unified ABL framework.
  110. ```python
  111. from ablkit.bridge import SimpleBridge
  112. bridge = SimpleBridge(model, reasoner, metric_list)
  113. ```
  114. Finally, we proceed with training and testing.
  115. ```python
  116. ​bridge.train(train_data, loops=1, segment_size=0.01)
  117. bridge.test(test_data)
  118. ```
  119. </details>
  120. To explore detailed tutorials and information, please refer to: [Documentation on Read the Docs](https://ablkit.readthedocs.io/en/latest/index.html).
  121. ## Examples
  122. We provide several examples in `examples/`. Each example is stored in a separate folder containing a README file.
  123. + [MNIST Addition](https://github.com/AbductiveLearning/ABLkit/tree/main/examples/mnist_add)
  124. + [Handwritten Formula (HWF)](https://github.com/AbductiveLearning/ABLkit/tree/main/examples/hwf)
  125. + [Handwritten Equation Decipherment](https://github.com/AbductiveLearning/ABLkit/tree/main/examples/hed)
  126. + [Zoo](https://github.com/AbductiveLearning/ABLkit/tree/main/examples/zoo)
  127. ## References
  128. 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).
  129. ```
  130. @article{zhou2019abductive,
  131. title = {Abductive learning: towards bridging machine learning and logical reasoning},
  132. author = {Zhou, Zhi-Hua},
  133. journal = {Science China Information Sciences},
  134. volume = {62},
  135. number = {7},
  136. pages = {76101},
  137. year = {2019}
  138. }
  139. @incollection{zhou2022abductive,
  140. title = {Abductive Learning},
  141. author = {Zhou, Zhi-Hua and Huang, Yu-Xuan},
  142. booktitle = {Neuro-Symbolic Artificial Intelligence: The State of the Art},
  143. editor = {Pascal Hitzler and Md. Kamruzzaman Sarker},
  144. publisher = {{IOS} Press},
  145. pages = {353--369},
  146. address = {Amsterdam},
  147. year = {2022}
  148. }
  149. ```
  150. ## Citation
  151. To cite ABLkit, please cite the following paper: [Huang et al., 2024](https://journal.hep.com.cn/fcs/EN/10.1007/s11704-024-40085-7).
  152. ```
  153. @article{ABLkit2024,
  154. author = {Huang, Yu-Xuan and Hu, Wen-Chao and Gao, En-Hao and Jiang, Yuan},
  155. title = {ABLkit: a Python toolkit for abductive learning},
  156. journal = {Frontiers of Computer Science},
  157. volume = {18},
  158. number = {6},
  159. pages = {186354},
  160. year = {2024}
  161. }
  162. ```

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