forked from dice-group/Ontolearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcept_learner.py
1642 lines (1429 loc) · 82.1 KB
/
concept_learner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -----------------------------------------------------------------------------
# MIT License
#
# Copyright (c) 2024 Ontolearn Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -----------------------------------------------------------------------------
"""Concept learning algorithms of Ontolearn."""
import logging
import operator
import random
import time
from contextlib import contextmanager
from itertools import islice, chain
from typing import Any, Callable, Dict, FrozenSet, Set, List, Tuple, Iterable, Optional, Union
import pandas as pd
import torch
from owlapy.class_expression import OWLClassExpression
from owlapy.owl_individual import OWLNamedIndividual
from owlapy.owl_literal import OWLLiteral
from owlapy.owl_property import OWLDataProperty
from owlapy.owl_reasoner import OWLReasoner
from torch.utils.data import DataLoader
from torch.functional import F
from torch.nn.utils.rnn import pad_sequence
from deap import gp, tools, base, creator
from ontolearn.knowledge_base import KnowledgeBase
from ontolearn.abstracts import AbstractFitness, AbstractScorer, BaseRefinement, \
AbstractHeuristic, EncodedPosNegLPStandardKind
from ontolearn.base_concept_learner import BaseConceptLearner, RefinementBasedConceptLearner
from owlapy.utils import EvaluatedDescriptionSet, ConceptOperandSorter, OperandSetTransform
from ontolearn.data_struct import NCESDataLoader, NCESDataLoaderInference, CLIPDataLoader, CLIPDataLoaderInference
from ontolearn.ea_algorithms import AbstractEvolutionaryAlgorithm, EASimple
from ontolearn.ea_initialization import AbstractEAInitialization, EARandomInitialization, EARandomWalkInitialization
from ontolearn.ea_utils import PrimitiveFactory, OperatorVocabulary, ToolboxVocabulary, Tree, escape, ind_to_string, \
owlliteral_to_primitive_string
from ontolearn.fitness_functions import LinearPressureFitness
from ontolearn.heuristics import OCELHeuristic
from ontolearn.learning_problem import PosNegLPStandard, EncodedPosNegLPStandard
from ontolearn.metrics import Accuracy
from ontolearn.refinement_operators import ExpressRefinement
from ontolearn.search import EvoLearnerNode, NCESNode, HeuristicOrderedNode, LBLNode, OENode, TreeNode, \
LengthOrderedNode, \
QualityOrderedNode, EvaluatedConcept
from ontolearn.utils import oplogging
from ontolearn.utils.static_funcs import init_length_metric, compute_tp_fn_fp_tn
from ontolearn.value_splitter import AbstractValueSplitter, BinningValueSplitter, EntropyValueSplitter
from ontolearn.base_nces import BaseNCES
from ontolearn.nces_architectures import LSTM, GRU, SetTransformer
from ontolearn.clip_architectures import LengthLearner_LSTM, LengthLearner_GRU, LengthLearner_CNN, \
LengthLearner_SetTransformer
from ontolearn.nces_trainer import NCESTrainer, before_pad
from ontolearn.clip_trainer import CLIPTrainer
from ontolearn.nces_utils import SimpleSolution
from owlapy.render import DLSyntaxObjectRenderer
from owlapy.parser import DLSyntaxParser
from owlapy.utils import OrderedOWLObject
from sortedcontainers import SortedSet
import os
logger = logging.getLogger(__name__)
_concept_operand_sorter = ConceptOperandSorter()
class CELOE(RefinementBasedConceptLearner[OENode]):
"""Class Expression Learning for Ontology Engineering.
Attributes:
best_descriptions (EvaluatedDescriptionSet[OENode, QualityOrderedNode]): Best hypotheses ordered.
best_only (bool): If False pick only nodes with quality < 1.0, else pick without quality restrictions.
calculate_min_max (bool): Calculate minimum and maximum horizontal expansion? Statistical purpose only.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic.
heuristic_queue (SortedSet[OENode]): A sorted set that compares the nodes based on Heuristic.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
max_child_length (int): Limit the length of concepts generated by the refinement operator.
max_he (int): Maximal value of horizontal expansion.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
max_runtime (int): Limit to stop the algorithm after n seconds.
min_he (int): Minimal value of horizontal expansion.
name (str): Name of the model = 'celoe_python'.
_number_of_tested_concepts (int): Yes, you got it. This stores the number of tested concepts.
operator (BaseRefinement): Operator used to generate refinements.
quality_func (AbstractScorer) The quality function to be used.
reasoner (OWLReasoner): The reasoner that this model is using.
search_tree (Dict[OWLClassExpression, TreeNode[OENode]]): Dict to store the TreeNode for a class expression.
start_class (OWLClassExpression): The starting class expression for the refinement operation.
start_time (float): The time when :meth:`fit` starts the execution. Used to calculate the total time :meth:`fit`
takes to execute.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found.
"""
__slots__ = 'best_descriptions', 'max_he', 'min_he', 'best_only', 'calculate_min_max', 'heuristic_queue', \
'search_tree', '_learning_problem', '_max_runtime', '_seen_norm_concepts'
name = 'celoe_python'
kb: KnowledgeBase
max_he: int
min_he: int
best_only: bool
calculate_min_max: bool
search_tree: Dict[OWLClassExpression, TreeNode[OENode]]
seen_norm_concepts: Set[OWLClassExpression]
heuristic_queue: 'SortedSet[OENode]'
best_descriptions: EvaluatedDescriptionSet[OENode, QualityOrderedNode]
_learning_problem: Optional[EncodedPosNegLPStandardKind]
def __init__(self,
knowledge_base: KnowledgeBase,
reasoner: Optional[OWLReasoner] = None,
refinement_operator: Optional[BaseRefinement[OENode]] = None,
quality_func: Optional[AbstractScorer] = None,
heuristic_func: Optional[AbstractHeuristic] = None,
terminate_on_goal: Optional[bool] = None,
iter_bound: Optional[int] = None,
max_num_of_concepts_tested: Optional[int] = None,
max_runtime: Optional[int] = None,
max_results: int = 10,
best_only: bool = False,
calculate_min_max: bool = True):
""" Create a new instance of CELOE.
Args:
best_only (bool): If False pick only nodes with quality < 1.0, else pick without quality restrictions.
Defaults to False.
calculate_min_max (bool): Calculate minimum and maximum horizontal expansion? Statistical purpose only.
Defaults to True.
refinement_operator (BaseRefinement[OENode]): Operator used to generate refinements.
Defaults to `ModifiedCELOERefinement`.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic. Defaults to `CELOEHeuristic`.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done. Defaults to 10'000.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested. Defaults to 10'000.
max_runtime (int): Limit to stop the algorithm after n seconds. Defaults to 5.
max_results (int): Maximum hypothesis to store. Defaults to 10.
quality_func (AbstractScorer) The quality function to be used. Defaults to `F1`.
reasoner (OWLReasoner): Optionally use a different reasoner. If reasoner=None, the reasoner of
the :attr:`knowledge_base` is used.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found. Defaults to True.
"""
super().__init__(knowledge_base=knowledge_base,
reasoner=reasoner,
refinement_operator=refinement_operator,
quality_func=quality_func,
heuristic_func=heuristic_func,
terminate_on_goal=terminate_on_goal,
iter_bound=iter_bound,
max_num_of_concepts_tested=max_num_of_concepts_tested,
max_runtime=max_runtime)
self.search_tree = dict()
self.heuristic_queue = SortedSet(key=HeuristicOrderedNode)
self._seen_norm_concepts = set()
self.best_descriptions = EvaluatedDescriptionSet(max_size=max_results, ordering=QualityOrderedNode)
self.best_only = best_only
self.calculate_min_max = calculate_min_max
self.max_he = 0
self.min_he = 1
# TODO: CD: This could be defined in BaseConceptLearner as it is used in all classes that inherits from
# TODO: CD: BaseConceptLearner
self._learning_problem = None
self._max_runtime = None
def next_node_to_expand(self, step: int) -> OENode:
if not self.best_only:
for node in reversed(self.heuristic_queue):
if node.quality < 1.0:
return node
else:
raise ValueError("No Node with lesser accuracy found")
else:
# from reimplementation, pick without quality criterion
return self.heuristic_queue[-1]
# Original reimplementation of CELOE: Sort search tree at each step. Quite inefficient.
# self.search_tree.sort_search_tree_by_decreasing_order(key='heuristic')
# if self.verbose > 1:
# self.search_tree.show_search_tree(step)
# for n in self.search_tree:
# return n
# raise ValueError('Search Tree can not be empty.')
def best_hypotheses(self, n: int = 1, return_node: bool = False) -> Union[Union[
OWLClassExpression, Iterable[OWLClassExpression]], Union[OENode, Iterable[OENode]]]:
x = islice(self.best_descriptions, n)
if n == 1:
if return_node:
return next(x)
else:
return next(x).concept
else:
if return_node:
return [i for i in x]
else:
return [i.concept for i in x]
def make_node(self, c: OWLClassExpression, parent_node: Optional[OENode] = None, is_root: bool = False) -> OENode:
"""
Create a node for CELOE.
Args:
c: The class expression of this node.
parent_node: Parent node.
is_root: Is this the root node?
Returns:
OENode: The node.
"""
r = OENode(c, self.kb.concept_len(c), parent_node=parent_node, is_root=is_root)
return r
@contextmanager
def updating_node(self, node: OENode):
"""
Removes the node from the heuristic sorted set and inserts it again.
Args:
Node to update.
Yields:
The node itself.
"""
self.heuristic_queue.discard(node)
yield node
self.heuristic_queue.add(node)
def downward_refinement(self, node: OENode) -> Iterable[OENode]:
assert isinstance(node, OENode)
with self.updating_node(node):
# TODO: NNF
refinements = SortedSet(
map(_concept_operand_sorter.sort,
self.operator.refine(
node.concept,
max_length=node.h_exp,
current_domain=self.start_class)
) # noqa: E203
,
key=OrderedOWLObject)
node.increment_h_exp()
node.refinement_count = len(refinements)
self.heuristic_func.apply(node, None, self._learning_problem)
def make_node_with_parent(c: OWLClassExpression):
return self.make_node(c, parent_node=node)
return map(make_node_with_parent, refinements)
def fit(self, *args, **kwargs):
"""
Find hypotheses that explain pos and neg.
"""
self.clean()
max_runtime = kwargs.pop("max_runtime", None)
learning_problem = self.construct_learning_problem(PosNegLPStandard, args, kwargs)
assert not self.search_tree
self._learning_problem = learning_problem.encode_kb(self.kb)
if max_runtime is not None:
self._max_runtime = max_runtime
else:
self._max_runtime = self.max_runtime
root = self.make_node(_concept_operand_sorter.sort(self.start_class), is_root=True)
self._add_node(root, None)
assert len(self.heuristic_queue) == 1
# TODO:CD:suggest to add another assert,e.g. assert #. of instance in root > 1
self.start_time = time.time()
for j in range(1, self.iter_bound):
most_promising = self.next_node_to_expand(j)
tree_parent = self.tree_node(most_promising)
minimum_length = most_promising.h_exp
if logger.isEnabledFor(oplogging.TRACE):
logger.debug("now refining %s", most_promising)
for ref in self.downward_refinement(most_promising):
# we ignore all refinements with lower length
# (this also avoids duplicate node children)
# TODO: ignore too high depth
if ref.len < minimum_length:
# ignoring refinement, it does not satisfy minimum_length condition
continue
# note: tree_parent has to be equal to node_tree_parent(ref.parent_node)!
added = self._add_node(ref, tree_parent)
goal_found = added and ref.quality == 1.0
if goal_found and self.terminate_on_goal:
return self.terminate()
if self.calculate_min_max:
# This is purely a statistical function, it does not influence CELOE
self.update_min_max_horiz_exp(most_promising)
if time.time() - self.start_time > self._max_runtime:
return self.terminate()
if self.number_of_tested_concepts >= self.max_num_of_concepts_tested:
return self.terminate()
if logger.isEnabledFor(oplogging.TRACE) and j % 100 == 0:
self._log_current_best(j)
return self.terminate()
async def fit_async(self, *args, **kwargs):
"""
Async method of fit.
"""
self.clean()
max_runtime = kwargs.pop("max_runtime", None)
learning_problem = self.construct_learning_problem(PosNegLPStandard, args, kwargs)
assert not self.search_tree
self._learning_problem = learning_problem.encode_kb(self.kb)
if max_runtime is not None:
self._max_runtime = max_runtime
else:
self._max_runtime = self.max_runtime
root = self.make_node(_concept_operand_sorter.sort(self.start_class), is_root=True)
self._add_node(root, None)
assert len(self.heuristic_queue) == 1
# TODO:CD:suggest to add another assert,e.g. assert #. of instance in root > 1
self.start_time = time.time()
for j in range(1, self.iter_bound):
most_promising = self.next_node_to_expand(j)
tree_parent = self.tree_node(most_promising)
minimum_length = most_promising.h_exp
if logger.isEnabledFor(oplogging.TRACE):
logger.debug("now refining %s", most_promising)
evaluated_refs = []
for ref in self.downward_refinement(most_promising):
# we ignore all refinements with lower length
# (this also avoids duplicate node children)
# TODO: ignore too high depth
if ref.len < minimum_length:
# ignoring refinement, it does not satisfy minimum_length condition
continue
if ref.concept in self.search_tree:
# ignoring refinement, it has been refined from another parent
continue
evaluated_refs.append(self._eval_node_async(ref))
import asyncio
for task in asyncio.as_completed(evaluated_refs):
ref, eval_ = await task
# for task in await asyncio.gather(*evaluated_refs):
# ref, eval_ = task
# note: tree_parent has to be equal to node_tree_parent(ref.parent_node)!
added = self._add_node_evald(ref, eval_, tree_parent)
goal_found = added and ref.quality == 1.0
if goal_found and self.terminate_on_goal:
return self.terminate()
if self.calculate_min_max:
# This is purely a statistical function, it does not influence CELOE
self.update_min_max_horiz_exp(most_promising)
if time.time() - self.start_time > self._max_runtime:
return self.terminate()
if self.number_of_tested_concepts >= self.max_num_of_concepts_tested:
return self.terminate()
if logger.isEnabledFor(oplogging.TRACE) and j % 100 == 0:
self._log_current_best(j)
return self.terminate()
def encoded_learning_problem(self) -> Optional[EncodedPosNegLPStandardKind]:
"""Fetch the most recently used learning problem from the fit method."""
return self._learning_problem
def tree_node(self, node: OENode) -> TreeNode[OENode]:
"""
Get the TreeNode of the given node.
Args:
node: The node.
Returns:
TreeNode of the given node.
"""
tree_parent = self.search_tree[node.concept]
return tree_parent
def _add_node(self, ref: OENode, tree_parent: Optional[TreeNode[OENode]]):
# TODO:CD: Why have this constraint ?
# We should not ignore a concept due to this constraint.
# It might be the case that new path to ref.concept is a better path. Hence, we should update its parent
# depending on the new heuristic value.
# Solution: If concept exists we should compare its first heuristic value with the new one
if ref.concept in self.search_tree:
# ignoring refinement, it has been refined from another parent
return False
norm_concept = OperandSetTransform().simplify(ref.concept)
if norm_concept in self._seen_norm_concepts:
norm_seen = True
else:
norm_seen = False
self._seen_norm_concepts.add(norm_concept)
self.search_tree[ref.concept] = TreeNode(ref, tree_parent, is_root=ref.is_root)
e = self.kb.evaluate_concept(ref.concept, self.quality_func, self._learning_problem)
ref.quality = e.q
self._number_of_tested_concepts += 1
if ref.quality == 0: # > too weak
return False
assert 0 <= ref.quality <= 1.0
# TODO: expression rewriting
self.heuristic_func.apply(ref, e.inds, self._learning_problem)
if not norm_seen and self.best_descriptions.maybe_add(ref):
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Better description found: %s", ref)
self.heuristic_queue.add(ref)
# TODO: implement noise
return True
async def _eval_node_async(self, ref: OENode):
# TODO:CD: Why have this constraint ?
# We should not ignore a concept due to this constraint.
# It might be the case that new path to ref.concept is a better path. Hence, we should update its parent
# depending on the new heuristic value.
# Solution: If concept exists we should compare its first heuristic value with the new one
res = await self.kb.evaluate_concept_async(ref.concept, self.quality_func, self._learning_problem)
return ref, res
def _add_node_evald(self, ref: OENode, eval_: EvaluatedConcept, tree_parent: Optional[TreeNode[OENode]]):
norm_concept = OperandSetTransform().simplify(ref.concept)
if norm_concept in self._seen_norm_concepts:
norm_seen = True
else:
norm_seen = False
self._seen_norm_concepts.add(norm_concept)
self.search_tree[ref.concept] = TreeNode(ref, tree_parent, is_root=ref.is_root)
ref.quality = eval_.q
self._number_of_tested_concepts += 1
if ref.quality == 0: # > too weak
return False
assert 0 <= ref.quality <= 1.0
# TODO: expression rewriting
self.heuristic_func.apply(ref, eval_.inds, self._learning_problem)
if not norm_seen and self.best_descriptions.maybe_add(ref):
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Better description found: %s", ref)
self.heuristic_queue.add(ref)
# TODO: implement noise
return True
def _log_current_best(self, heading_step, top_n: int = 10) -> None:
logger.debug('######## %s step Best Hypotheses ###########', heading_step)
predictions = list(self.best_hypotheses(top_n, return_node=True))
for ith, node in enumerate(predictions):
logger.debug('{0}-\t{1}\t{2}:{3}\tHeuristic:{4}:'.format(
ith + 1, DLSyntaxObjectRenderer().render(node.concept),
type(self.quality_func).name, node.quality,
node.heuristic))
def show_search_tree(self, heading_step: str, top_n: int = 10) -> None:
"""
Show search tree.
"""
rdr = DLSyntaxObjectRenderer()
print('######## ', heading_step, 'step Search Tree ###########')
def tree_node_as_length_ordered_concept(tn: TreeNode[OENode]):
return LengthOrderedNode(tn.node, tn.node.len)
def print_partial_tree_recursive(tn: TreeNode[OENode], depth: int = 0):
if tn.node.heuristic is not None:
heur_idx = len(self.heuristic_queue) - self.heuristic_queue.index(tn.node)
else:
heur_idx = None
if tn.node in self.best_descriptions:
best_idx = len(self.best_descriptions.items) - self.best_descriptions.items.index(tn.node)
else:
best_idx = None
render_str = rdr.render(tn.node.concept)
depths = "`" * depth
if best_idx is not None or heur_idx is not None:
if best_idx is None:
best_idx = ""
if heur_idx is None:
heur_idx = ""
print("[%3s] [%4s] %s %s \t HE:%s Q:%f Heur:%s |RC|:%s" % (best_idx, heur_idx, depths, render_str,
tn.node.h_exp, tn.node.quality,
tn.node.heuristic, tn.node.refinement_count))
for c in sorted(tn.children, key=tree_node_as_length_ordered_concept):
print_partial_tree_recursive(c, depth + 1)
print_partial_tree_recursive(self.search_tree[self.start_class])
print('######## ', heading_step, 'step Best Hypotheses ###########')
predictions = list(self.best_hypotheses(top_n, return_node=True))
for ith, node in enumerate(predictions):
print('{0}-\t{1}\t{2}:{3}\tHeuristic:{4}:'.format(ith + 1, rdr.render(node.concept),
type(self.quality_func).name, node.quality,
node.heuristic))
print('######## Search Tree ###########\n')
def update_min_max_horiz_exp(self, node: OENode):
he = node.h_exp
# update maximum value
self.max_he = max(self.max_he, he)
if self.min_he == he - 1:
threshold_score = node.heuristic + 1 - node.quality
for n in reversed(self.heuristic_queue):
if n == node:
continue
if n.h_exp == self.min_he:
""" we can stop instantly when another node with min. """
return
if n.heuristic < threshold_score:
""" we can stop traversing nodes when their score is too low. """
break
# inc. minimum since we found no other node which also has min. horiz. exp.
self.min_he += 1
if logger.isEnabledFor(oplogging.TRACE):
logger.info("minimum horizontal expansion is now %d", self.min_he)
def clean(self):
self.heuristic_queue.clear()
self.best_descriptions.clean()
self.search_tree.clear()
self._seen_norm_concepts.clear()
self.max_he = 0
self.min_he = 1
self._learning_problem = None
self._max_runtime = None
super().clean()
class OCEL(CELOE):
"""A limited version of CELOE.
Attributes:
best_descriptions (EvaluatedDescriptionSet[OENode, QualityOrderedNode]): Best hypotheses ordered.
best_only (bool): If False pick only nodes with quality < 1.0, else pick without quality restrictions.
calculate_min_max (bool): Calculate minimum and maximum horizontal expansion? Statistical purpose only.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic.
heuristic_queue (SortedSet[OENode]): A sorted set that compares the nodes based on Heuristic.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
max_child_length (int): Limit the length of concepts generated by the refinement operator.
max_he (int): Maximal value of horizontal expansion.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
max_runtime (int): Limit to stop the algorithm after n seconds.
min_he (int): Minimal value of horizontal expansion.
name (str): Name of the model = 'ocel_python'.
_number_of_tested_concepts (int): Yes, you got it. This stores the number of tested concepts.
operator (BaseRefinement): Operator used to generate refinements.
quality_func (AbstractScorer) The quality function to be used.
reasoner (OWLReasoner): The reasoner that this model is using.
search_tree (Dict[OWLClassExpression, TreeNode[OENode]]): Dict to store the TreeNode for a class expression.
start_class (OWLClassExpression): The starting class expression for the refinement operation.
start_time (float): The time when :meth:`fit` starts the execution. Used to calculate the total time :meth:`fit`
takes to execute.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found.
"""
__slots__ = ()
name = 'ocel_python'
def __init__(self,
knowledge_base: KnowledgeBase,
reasoner: Optional[OWLReasoner] = None,
refinement_operator: Optional[BaseRefinement[OENode]] = None,
quality_func: Optional[AbstractScorer] = None,
heuristic_func: Optional[AbstractHeuristic] = None,
terminate_on_goal: Optional[bool] = None,
iter_bound: Optional[int] = None,
max_num_of_concepts_tested: Optional[int] = None,
max_runtime: Optional[int] = None,
max_results: int = 10,
best_only: bool = False,
calculate_min_max: bool = True):
""" Create a new instance of OCEL.
Args:
best_only (bool): If False pick only nodes with quality < 1.0, else pick without quality restrictions.
Defaults to False.
calculate_min_max (bool): Calculate minimum and maximum horizontal expansion? Statistical purpose only.
Defaults to True.
refinement_operator (BaseRefinement[OENode]): Operator used to generate refinements.
Defaults to `ModifiedCELOERefinement`.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic. Defaults to `OCELHeuristic`.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done. Defaults to 10'000.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested. Defaults to 10'000.
max_runtime (int): Limit to stop the algorithm after n seconds. Defaults to 5.
max_results (int): Maximum hypothesis to store. Defaults to 10.
quality_func (AbstractScorer) The quality function to be used. Defaults to `F1`.
reasoner (OWLReasoner): Optionally use a different reasoner. If reasoner=None, the reasoner of
the :attr:`knowledge_base` is used.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found. Defaults to True.
"""
if heuristic_func is None:
heuristic_func = OCELHeuristic()
super().__init__(knowledge_base=knowledge_base,
reasoner=reasoner,
refinement_operator=refinement_operator,
quality_func=quality_func,
heuristic_func=heuristic_func,
terminate_on_goal=terminate_on_goal,
iter_bound=iter_bound,
max_num_of_concepts_tested=max_num_of_concepts_tested,
max_runtime=max_runtime,
max_results=max_results,
best_only=best_only,
calculate_min_max=calculate_min_max)
def make_node(self, c: OWLClassExpression, parent_node: Optional[OENode] = None, is_root: bool = False) -> OENode:
"""
Create a node for OCEL.
Args:
c: The class expression of this node.
parent_node: Parent node.
is_root: Is this the root node?
Returns:
OENode: The node.
"""
assert parent_node is None or isinstance(parent_node, LBLNode)
r = LBLNode(c, self.kb.concept_len(c), self.kb.individuals_set(c), parent_node=parent_node, is_root=is_root)
if parent_node is not None:
parent_node.add_child(r)
return r
class EvoLearner(BaseConceptLearner[EvoLearnerNode]):
"""An evolutionary approach to learn concepts in ALCQ(D).
Attributes:
algorithm (AbstractEvolutionaryAlgorithm): The evolutionary algorithm.
card_limit (int): The upper cardinality limit if using cardinality restriction on object properties.
fitness_func (AbstractFitness): Fitness function.
height_limit (int): The maximum value allowed for the height of the Crossover and Mutation operations.
init_method (AbstractEAInitialization): The evolutionary algorithm initialization method.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int): Limit to stop the algorithm after n concepts tested.
max_runtime (int): max_runtime: Limit to stop the algorithm after n seconds.
mut_uniform_gen (AbstractEAInitialization): The initialization method to create the tree for mutation operation.
name (str): Name of the model = 'evolearner'.
num_generations (int): Number of generation for the evolutionary algorithm.
_number_of_tested_concepts (int): Yes, you got it. This stores the number of tested concepts.
population_size (int): Population size for the evolutionary algorithm.
pset (gp.PrimitiveSetTyped): Contains the primitives that can be used to solve a Strongly Typed GP problem.
quality_func: Function to evaluate the quality of solution concepts.
reasoner (OWLReasoner): The reasoner that this model is using.
start_time (float): The time when :meth:`fit` starts the execution. Used to calculate the total time :meth:`fit`
takes to execute.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found.
toolbox (base.Toolbox): A toolbox for evolution that contains the evolutionary operators.
tournament_size (int): The number of evolutionary individuals participating in each tournament.
use_card_restrictions (bool): Use cardinality restriction for object properties?
use_data_properties (bool): Consider data properties?
use_inverse (bool): Consider inversed concepts?
value_splitter (AbstractValueSplitter): Used to calculate the splits for data properties values.
"""
__slots__ = 'fitness_func', 'init_method', 'algorithm', 'value_splitter', 'tournament_size', \
'population_size', 'num_generations', 'height_limit', 'use_data_properties', 'pset', 'toolbox', \
'_learning_problem', '_result_population', 'mut_uniform_gen', '_dp_to_prim_type', '_dp_splits', \
'_split_properties', '_cache', 'use_card_restrictions', 'card_limit', 'use_inverse', 'total_fits'
name = 'evolearner'
kb: KnowledgeBase
fitness_func: AbstractFitness
init_method: AbstractEAInitialization
algorithm: AbstractEvolutionaryAlgorithm
mut_uniform_gen: AbstractEAInitialization
value_splitter: AbstractValueSplitter
use_data_properties: bool
use_card_restrictions: bool
use_inverse: bool
tournament_size: int
card_limit: int
population_size: int
num_generations: int
height_limit: int
pset: gp.PrimitiveSetTyped
toolbox: base.Toolbox
_learning_problem: EncodedPosNegLPStandard
_result_population: Optional[List[Tree]]
_dp_to_prim_type: Dict[OWLDataProperty, Any]
_dp_splits: Dict[OWLDataProperty, List[OWLLiteral]]
_split_properties: List[OWLDataProperty]
_cache: Dict[str, Tuple[float, float]]
def __init__(self,
knowledge_base: KnowledgeBase,
reasoner: Optional[OWLReasoner] = None,
quality_func: Optional[AbstractScorer] = None,
fitness_func: Optional[AbstractFitness] = None,
init_method: Optional[AbstractEAInitialization] = None,
algorithm: Optional[AbstractEvolutionaryAlgorithm] = None,
mut_uniform_gen: Optional[AbstractEAInitialization] = None,
value_splitter: Optional[AbstractValueSplitter] = None,
terminate_on_goal: Optional[bool] = None,
max_runtime: Optional[int] = None,
use_data_properties: bool = True,
use_card_restrictions: bool = True,
use_inverse: bool = False,
tournament_size: int = 7,
card_limit: int = 10,
population_size: int = 800,
num_generations: int = 200,
height_limit: int = 17):
""" Create a new instance of EvoLearner
Args:
algorithm (AbstractEvolutionaryAlgorithm): The evolutionary algorithm. Defaults to `EASimple`.
card_limit (int): The upper cardinality limit if using cardinality restriction for object properties. Defaults to 10.
fitness_func (AbstractFitness): Fitness function. Defaults to `LinearPressureFitness`.
height_limit (int): The maximum value allowed for the height of the Crossover and Mutation operations.
Defaults to 17.
init_method (AbstractEAInitialization): The evolutionary algorithm initialization method. Defaults
to EARandomWalkInitialization.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
max_runtime (int): max_runtime: Limit to stop the algorithm after n seconds. Defaults to 5.
mut_uniform_gen (AbstractEAInitialization): The initialization method to create the tree for mutation
operation. Defaults to
EARandomInitialization(min_height=1, max_height=3).
num_generations (int): Number of generation for the evolutionary algorithm. Defaults to 200.
population_size (int): Population size for the evolutionary algorithm. Defaults to 800.
quality_func: Function to evaluate the quality of solution concepts. Defaults to `Accuracy`.
reasoner (OWLReasoner): Optionally use a different reasoner. If reasoner=None, the reasoner of
the :attr:`knowledge_base` is used.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found. Defaults to True.
tournament_size (int): The number of evolutionary individuals participating in each tournament.
Defaults to 7.
use_card_restrictions (bool): Use cardinality restriction for object properties? Default to True.
use_data_properties (bool): Consider data properties? Defaults to True.
use_inverse (bool): Consider inversed concepts? Defaults to False.
value_splitter (AbstractValueSplitter): Used to calculate the splits for data properties values. Defaults to
`EntropyValueSplitter`.
"""
if quality_func is None:
quality_func = Accuracy()
super().__init__(knowledge_base=knowledge_base,
reasoner=reasoner,
quality_func=quality_func,
terminate_on_goal=terminate_on_goal,
max_runtime=max_runtime)
self.reasoner = reasoner
self.fitness_func = fitness_func
self.init_method = init_method
self.algorithm = algorithm
self.mut_uniform_gen = mut_uniform_gen
self.value_splitter = value_splitter
self.use_data_properties = use_data_properties
self.use_card_restrictions = use_card_restrictions
self.use_inverse = use_inverse
self.tournament_size = tournament_size
self.card_limit = card_limit
self.population_size = population_size
self.num_generations = num_generations
self.height_limit = height_limit
self.total_fits = 0
self.__setup()
def __setup(self):
self.clean(partial=True)
self._cache = dict()
if self.fitness_func is None:
self.fitness_func = LinearPressureFitness()
if self.init_method is None:
self.init_method = EARandomWalkInitialization()
if self.algorithm is None:
self.algorithm = EASimple()
if self.mut_uniform_gen is None:
self.mut_uniform_gen = EARandomInitialization(min_height=1, max_height=3)
if self.value_splitter is None:
self.value_splitter = EntropyValueSplitter()
self._result_population = None
self._dp_to_prim_type = dict()
self._dp_splits = dict()
self._split_properties = []
self.pset = self.__build_primitive_set()
self.toolbox = self.__build_toolbox()
def __build_primitive_set(self) -> gp.PrimitiveSetTyped:
factory = PrimitiveFactory()
union = factory.create_union()
intersection = factory.create_intersection()
pset = gp.PrimitiveSetTyped("concept_tree", [], OWLClassExpression)
pset.addPrimitive(self.kb.generator.negation, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.NEGATION)
pset.addPrimitive(union, [OWLClassExpression, OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.UNION)
pset.addPrimitive(intersection, [OWLClassExpression, OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.INTERSECTION)
for op in self.kb.get_object_properties():
name = escape(op.iri.get_remainder())
existential, universal = factory.create_existential_universal(op)
pset.addPrimitive(existential, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.EXISTENTIAL + name)
pset.addPrimitive(universal, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.UNIVERSAL + name)
if self.use_inverse:
existential, universal = factory.create_existential_universal(op.get_inverse_property())
pset.addPrimitive(existential, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.INVERSE + OperatorVocabulary.EXISTENTIAL + name)
pset.addPrimitive(universal, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.INVERSE + OperatorVocabulary.UNIVERSAL + name)
if self.use_data_properties:
class Bool(object):
pass
false_ = OWLLiteral(False)
true_ = OWLLiteral(True)
pset.addTerminal(false_, Bool, name=owlliteral_to_primitive_string(false_))
pset.addTerminal(true_, Bool, name=owlliteral_to_primitive_string(true_))
for bool_dp in self.kb.get_boolean_data_properties():
name = escape(bool_dp.iri.get_remainder())
self._dp_to_prim_type[bool_dp] = Bool
data_has_value = factory.create_data_has_value(bool_dp)
pset.addPrimitive(data_has_value, [Bool], OWLClassExpression,
name=OperatorVocabulary.DATA_HAS_VALUE + name)
for split_dp in chain(self.kb.get_time_data_properties(), self.kb.get_numeric_data_properties()):
name = escape(split_dp.iri.get_remainder())
type_ = type(name, (object,), {})
self._dp_to_prim_type[split_dp] = type_
self._split_properties.append(split_dp)
min_inc, max_inc, _, _ = factory.create_data_some_values(split_dp)
pset.addPrimitive(min_inc, [type_], OWLClassExpression,
name=OperatorVocabulary.DATA_MIN_INCLUSIVE + name)
pset.addPrimitive(max_inc, [type_], OWLClassExpression,
name=OperatorVocabulary.DATA_MAX_INCLUSIVE + name)
# pset.addPrimitive(min_exc, [type_], OWLClassExpression,
# name=OperatorVocabulary.DATA_MIN_EXCLUSIVE + name)
# pset.addPrimitive(max_exc, [type_], OWLClassExpression,
# name=OperatorVocabulary.DATA_MAX_EXCLUSIVE + name)
if self.use_card_restrictions:
for i in range(1, self.card_limit + 1):
pset.addTerminal(i, int)
for op in self.kb.get_object_properties():
name = escape(op.iri.get_remainder())
card_min, card_max, _ = factory.create_card_restrictions(op)
pset.addPrimitive(card_min, [int, OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.CARD_MIN + name)
pset.addPrimitive(card_max, [int, OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.CARD_MAX + name)
# pset.addPrimitive(card_exact, [int, OWLClassExpression], OWLClassExpression,
# name=OperatorVocabulary.CARD_EXACT + name)
for class_ in self.kb.get_concepts():
pset.addTerminal(class_, OWLClassExpression, name=escape(class_.iri.get_remainder()))
pset.addTerminal(self.kb.generator.thing, OWLClassExpression,
name=escape(self.kb.generator.thing.iri.get_remainder()))
pset.addTerminal(self.kb.generator.nothing, OWLClassExpression,
name=escape(self.kb.generator.nothing.iri.get_remainder()))
return pset
def __build_toolbox(self) -> base.Toolbox:
creator.create("Fitness", base.Fitness, weights=(1.0,))
creator.create("Quality", base.Fitness, weights=(1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.Fitness, quality=creator.Quality)
toolbox = base.Toolbox()
toolbox.register(ToolboxVocabulary.INIT_POPULATION, self.init_method.get_population,
creator.Individual, self.pset)
toolbox.register(ToolboxVocabulary.COMPILE, gp.compile, pset=self.pset)
toolbox.register(ToolboxVocabulary.FITNESS_FUNCTION, self._fitness_func)
toolbox.register(ToolboxVocabulary.SELECTION, tools.selTournament, tournsize=self.tournament_size)
toolbox.register(ToolboxVocabulary.CROSSOVER, gp.cxOnePoint)
toolbox.register("create_tree_mut", self.mut_uniform_gen.get_expression)
toolbox.register(ToolboxVocabulary.MUTATION, gp.mutUniform, expr=toolbox.create_tree_mut, pset=self.pset)
toolbox.decorate(ToolboxVocabulary.CROSSOVER,
gp.staticLimit(key=operator.attrgetter(ToolboxVocabulary.HEIGHT_KEY),
max_value=self.height_limit))
toolbox.decorate(ToolboxVocabulary.MUTATION,
gp.staticLimit(key=operator.attrgetter(ToolboxVocabulary.HEIGHT_KEY),
max_value=self.height_limit))
toolbox.register("get_top_hypotheses", self._get_top_hypotheses)
toolbox.register("terminate_on_goal", lambda: self.terminate_on_goal)
toolbox.register("max_runtime", lambda: self.max_runtime)
toolbox.register("pset", lambda: self.pset)
return toolbox
def __set_splitting_values(self):
for p in self._dp_splits:
if len(self._dp_splits[p]) == 0:
if p in self.kb.get_numeric_data_properties():
self._dp_splits[p].append(OWLLiteral(0))
else:
pass # TODO:
# Remove terminal for multiple fits, unfortunately there exists no better way in DEAP
# This removal is probably not needed, the important one is removal from the context below
self.pset.terminals.pop(self._dp_to_prim_type[p], None)
for split in self._dp_splits[p]:
terminal_name = owlliteral_to_primitive_string(split, p)
# Remove terminal for multiple fits, unfortunately there exists no better way in DEAP
self.pset.context.pop(terminal_name, None)
self.pset.addTerminal(split, self._dp_to_prim_type[p], name=terminal_name)
def register_op(self, alias: str, function: Callable, *args, **kargs):
"""Register a *function* in the toolbox under the name *alias*.
You may provide default arguments that will be passed automatically when
calling the registered function. Fixed arguments can then be overriden
at function call time.
Args:
alias: The name the operator will take in the toolbox. If the
alias already exist it will overwrite the operator
already present.
function: The function to which refer the alias.
args: One or more argument (and keyword argument) to pass
automatically to the registered function when called,
optional.
"""
self.toolbox.register(alias, function, *args, **kargs)