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.

hed_example.ipynb 7.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": null,
  6. "metadata": {},
  7. "outputs": [],
  8. "source": [
  9. "import numpy as np\n",
  10. "import torch.nn as nn\n",
  11. "import torch\n",
  12. "\n",
  13. "from abl.reasoning.reasoner import ReasonerBase\n",
  14. "from abl.reasoning.kb import prolog_KB\n",
  15. "\n",
  16. "from abl.utils.plog import logger\n",
  17. "from abl.learning.basic_nn import BasicNN\n",
  18. "from abl.learning.abl_model import ABLModel\n",
  19. "from abl.utils.utils import reform_idx\n",
  20. "\n",
  21. "from models.nn import SymbolNet\n",
  22. "from datasets.get_hed import get_hed, split_equation\n",
  23. "import framework_hed"
  24. ]
  25. },
  26. {
  27. "cell_type": "code",
  28. "execution_count": null,
  29. "metadata": {},
  30. "outputs": [],
  31. "source": [
  32. "# Initialize logger\n",
  33. "recorder = logger()"
  34. ]
  35. },
  36. {
  37. "attachments": {},
  38. "cell_type": "markdown",
  39. "metadata": {},
  40. "source": [
  41. "### Logic Part"
  42. ]
  43. },
  44. {
  45. "cell_type": "code",
  46. "execution_count": null,
  47. "metadata": {},
  48. "outputs": [],
  49. "source": [
  50. "# Initialize knowledge base and abducer\n",
  51. "class HED_prolog_KB(prolog_KB):\n",
  52. " def __init__(self, pseudo_label_list, pl_file):\n",
  53. " super().__init__(pseudo_label_list, pl_file)\n",
  54. " \n",
  55. " def consist_rule(self, exs, rules):\n",
  56. " rules = str(rules).replace(\"\\'\",\"\")\n",
  57. " return len(list(self.prolog.query(\"eval_inst_feature(%s, %s).\" % (exs, rules)))) != 0\n",
  58. "\n",
  59. " def abduce_rules(self, pred_res):\n",
  60. " prolog_result = list(self.prolog.query(\"consistent_inst_feature(%s, X).\" % pred_res))\n",
  61. " if len(prolog_result) == 0:\n",
  62. " return None\n",
  63. " prolog_rules = prolog_result[0]['X']\n",
  64. " rules = [rule.value for rule in prolog_rules]\n",
  65. " return rules\n",
  66. " \n",
  67. " \n",
  68. "kb = HED_prolog_KB(pseudo_label_list=[1, 0, '+', '='], pl_file='./datasets/learn_add.pl')\n",
  69. "\n",
  70. "class HED_Abducer(ReasonerBase):\n",
  71. " def __init__(self, kb, dist_func='hamming'):\n",
  72. " super().__init__(kb, dist_func, zoopt=True)\n",
  73. " \n",
  74. " def _revise_by_idxs(self, pred_res, key, all_address_flag, idxs):\n",
  75. " pred = []\n",
  76. " k = []\n",
  77. " address_flag = []\n",
  78. " for idx in idxs:\n",
  79. " pred.append(pred_res[idx])\n",
  80. " k.append(key[idx])\n",
  81. " address_flag += list(all_address_flag[idx])\n",
  82. " address_idx = np.where(np.array(address_flag) != 0)[0] \n",
  83. " candidate = self.revise_by_idx(pred, k, address_idx)\n",
  84. " return candidate\n",
  85. " \n",
  86. " def zoopt_revision_score(self, pred_res, pseudo_label, pred_res_prob, key, sol): \n",
  87. " all_address_flag = reform_idx(sol.get_x(), pseudo_label)\n",
  88. " lefted_idxs = [i for i in range(len(pred_res))]\n",
  89. " candidate_size = [] \n",
  90. " while lefted_idxs:\n",
  91. " idxs = []\n",
  92. " idxs.append(lefted_idxs.pop(0))\n",
  93. " max_candidate_idxs = []\n",
  94. " found = False\n",
  95. " for idx in range(-1, len(pred_res)):\n",
  96. " if (not idx in idxs) and (idx >= 0):\n",
  97. " idxs.append(idx)\n",
  98. " candidate = self._revise_by_idxs(pseudo_label, key, all_address_flag, idxs)\n",
  99. " if len(candidate) == 0:\n",
  100. " if len(idxs) > 1:\n",
  101. " idxs.pop()\n",
  102. " else:\n",
  103. " if len(idxs) > len(max_candidate_idxs):\n",
  104. " found = True\n",
  105. " max_candidate_idxs = idxs.copy() \n",
  106. " removed = [i for i in lefted_idxs if i in max_candidate_idxs]\n",
  107. " if found:\n",
  108. " candidate_size.append(len(removed) + 1)\n",
  109. " lefted_idxs = [i for i in lefted_idxs if i not in max_candidate_idxs]\n",
  110. " candidate_size.sort()\n",
  111. " score = 0\n",
  112. " import math\n",
  113. " for i in range(0, len(candidate_size)):\n",
  114. " score -= math.exp(-i) * candidate_size[i]\n",
  115. " return score\n",
  116. "\n",
  117. " def abduce_rules(self, pred_res):\n",
  118. " return self.kb.abduce_rules(pred_res)\n",
  119. " \n",
  120. "abducer = HED_Abducer(kb)"
  121. ]
  122. },
  123. {
  124. "attachments": {},
  125. "cell_type": "markdown",
  126. "metadata": {},
  127. "source": [
  128. "### Machine Learning Part"
  129. ]
  130. },
  131. {
  132. "cell_type": "code",
  133. "execution_count": null,
  134. "metadata": {},
  135. "outputs": [],
  136. "source": [
  137. "# Initialize necessary component for machine learning part\n",
  138. "cls = SymbolNet(\n",
  139. " num_classes=len(kb.pseudo_label_list),\n",
  140. " image_size=(28, 28, 1),\n",
  141. ")\n",
  142. "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
  143. "criterion = nn.CrossEntropyLoss()\n",
  144. "optimizer = torch.optim.RMSprop(cls.parameters(), lr=0.001, weight_decay=1e-6)"
  145. ]
  146. },
  147. {
  148. "cell_type": "code",
  149. "execution_count": null,
  150. "metadata": {},
  151. "outputs": [],
  152. "source": [
  153. "# Pretrain NN classifier\n",
  154. "framework_hed.hed_pretrain(kb, cls, recorder)"
  155. ]
  156. },
  157. {
  158. "cell_type": "code",
  159. "execution_count": null,
  160. "metadata": {},
  161. "outputs": [],
  162. "source": [
  163. "# Initialize BasicNN\n",
  164. "# The function of BasicNN is to wrap NN models into the form of an sklearn estimator\n",
  165. "base_model = BasicNN(\n",
  166. " cls,\n",
  167. " criterion,\n",
  168. " optimizer,\n",
  169. " device,\n",
  170. " save_interval=1,\n",
  171. " save_dir=recorder.save_dir,\n",
  172. " batch_size=32,\n",
  173. " num_epochs=1,\n",
  174. " recorder=recorder,\n",
  175. ")"
  176. ]
  177. },
  178. {
  179. "attachments": {},
  180. "cell_type": "markdown",
  181. "metadata": {},
  182. "source": [
  183. "### Use ABL model to join two parts"
  184. ]
  185. },
  186. {
  187. "cell_type": "code",
  188. "execution_count": null,
  189. "metadata": {},
  190. "outputs": [],
  191. "source": [
  192. "model = ABLModel(base_model)"
  193. ]
  194. },
  195. {
  196. "attachments": {},
  197. "cell_type": "markdown",
  198. "metadata": {},
  199. "source": [
  200. "### Dataset"
  201. ]
  202. },
  203. {
  204. "cell_type": "code",
  205. "execution_count": null,
  206. "metadata": {},
  207. "outputs": [],
  208. "source": [
  209. "total_train_data = get_hed(train=True)\n",
  210. "train_data, val_data = split_equation(total_train_data, 3, 1)\n",
  211. "test_data = get_hed(train=False)"
  212. ]
  213. },
  214. {
  215. "attachments": {},
  216. "cell_type": "markdown",
  217. "metadata": {},
  218. "source": [
  219. "### Train and save"
  220. ]
  221. },
  222. {
  223. "cell_type": "code",
  224. "execution_count": 9,
  225. "metadata": {},
  226. "outputs": [],
  227. "source": [
  228. "model, mapping = framework_hed.train_with_rule(model, abducer, train_data, val_data, select_num=10, min_len=5, max_len=8)\n",
  229. "framework_hed.hed_test(model, abducer, mapping, train_data, test_data, min_len=5, max_len=8)\n",
  230. "\n",
  231. "recorder.dump()"
  232. ]
  233. }
  234. ],
  235. "metadata": {
  236. "kernelspec": {
  237. "display_name": "ABL",
  238. "language": "python",
  239. "name": "python3"
  240. },
  241. "language_info": {
  242. "codemirror_mode": {
  243. "name": "ipython",
  244. "version": 3
  245. },
  246. "file_extension": ".py",
  247. "mimetype": "text/x-python",
  248. "name": "python",
  249. "nbconvert_exporter": "python",
  250. "pygments_lexer": "ipython3",
  251. "version": "3.8.16"
  252. },
  253. "orig_nbformat": 4,
  254. "vscode": {
  255. "interpreter": {
  256. "hash": "fb6f4ceeabb9a733f366948eb80109f83aedf798cc984df1e68fb411adb27d58"
  257. }
  258. }
  259. },
  260. "nbformat": 4,
  261. "nbformat_minor": 2
  262. }

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