ontolearn.learners ================== .. py:module:: ontolearn.learners Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/ontolearn/learners/celoe/index /autoapi/ontolearn/learners/drill/index /autoapi/ontolearn/learners/nero/index /autoapi/ontolearn/learners/ocel/index /autoapi/ontolearn/learners/sparql_query_learner/index /autoapi/ontolearn/learners/tree_learner/index Classes ------- .. autoapisummary:: ontolearn.learners.Drill ontolearn.learners.TDL ontolearn.learners.CELOE ontolearn.learners.OCEL Package Contents ---------------- .. py:class:: Drill(knowledge_base: ontolearn.abstracts.AbstractKnowledgeBase, path_embeddings: str = None, refinement_operator: ontolearn.refinement_operators.LengthBasedRefinement = None, use_inverse: bool = True, use_data_properties: bool = True, use_card_restrictions: bool = True, use_nominals: bool = True, min_cardinality_restriction: int = 2, max_cardinality_restriction: int = 5, positive_type_bias: int = 1, quality_func: Callable = None, reward_func: object = None, batch_size=None, num_workers: int = 1, iter_bound=None, max_num_of_concepts_tested=None, verbose: int = 0, terminate_on_goal=None, max_len_replay_memory=256, epsilon_decay: float = 0.01, epsilon_min: float = 0.0, num_epochs_per_replay: int = 2, num_episodes_per_replay: int = 2, learning_rate: float = 0.001, max_runtime=None, num_of_sequential_actions=3, stop_at_goal=True, num_episode: int = 10) Bases: :py:obj:`ontolearn.base_concept_learner.RefinementBasedConceptLearner` Neuro-Symbolic Class Expression Learning (https://www.ijcai.org/proceedings/2023/0403.pdf) .. py:attribute:: name :value: 'DRILL' .. py:attribute:: verbose :value: 0 .. py:attribute:: learning_problem :value: None .. py:attribute:: num_workers :value: 1 .. py:attribute:: learning_rate :value: 0.001 .. py:attribute:: num_episode :value: 10 .. py:attribute:: num_of_sequential_actions :value: 3 .. py:attribute:: num_epochs_per_replay :value: 2 .. py:attribute:: max_len_replay_memory :value: 256 .. py:attribute:: epsilon_decay :value: 0.01 .. py:attribute:: epsilon_min :value: 0.0 .. py:attribute:: batch_size :value: None .. py:attribute:: num_episodes_per_replay :value: 2 .. py:attribute:: seen_examples .. py:attribute:: pos :type: FrozenSet[owlapy.owl_individual.OWLNamedIndividual] :value: None .. py:attribute:: neg :type: FrozenSet[owlapy.owl_individual.OWLNamedIndividual] :value: None .. py:attribute:: positive_type_bias :value: 1 .. py:attribute:: start_time :value: None .. py:attribute:: goal_found :value: False .. py:attribute:: search_tree .. py:attribute:: stop_at_goal :value: True .. py:attribute:: epsilon :value: 1 .. py:method:: initialize_training_class_expression_learning_problem(pos: FrozenSet[owlapy.owl_individual.OWLNamedIndividual], neg: FrozenSet[owlapy.owl_individual.OWLNamedIndividual]) -> ontolearn.search.RL_State Initialize .. py:method:: rl_learning_loop(pos_uri: FrozenSet[owlapy.owl_individual.OWLNamedIndividual], neg_uri: FrozenSet[owlapy.owl_individual.OWLNamedIndividual]) -> List[float] Reinforcement Learning Training Loop Initialize RL environment for a given learning problem (E^+ pos_iri and E^- neg_iri ) Training: 2.1 Obtain a trajectory: A sequence of RL states/DL concepts T, Person, (Female and orall hasSibling Female). Rewards at each transition are also computed .. py:method:: train(dataset: Optional[Iterable[Tuple[str, Set, Set]]] = None, num_of_target_concepts: int = 1, num_learning_problems: int = 1) Training RL agent (1) Generate Learning Problems (2) For each learning problem, perform the RL loop .. py:method:: save(directory: str = None) -> None save weights of the deep Q-network .. py:method:: load(directory: str = None) -> None load weights of the deep Q-network .. py:method:: fit(learning_problem: ontolearn.learning_problem.PosNegLPStandard, max_runtime=None) Run the concept learning algorithm according to its configuration. Once finished, the results can be queried with the `best_hypotheses` function. .. py:method:: init_embeddings_of_examples(pos_uri: FrozenSet[owlapy.owl_individual.OWLNamedIndividual], neg_uri: FrozenSet[owlapy.owl_individual.OWLNamedIndividual]) .. py:method:: create_rl_state(c: owlapy.class_expression.OWLClassExpression, parent_node: Optional[ontolearn.search.RL_State] = None, is_root: bool = False) -> ontolearn.search.RL_State Create an RL_State instance. .. py:method:: compute_quality_of_class_expression(state: ontolearn.search.RL_State) -> None Compute Quality of owl class expression. # (1) Perform concept retrieval # (2) Compute the quality w.r.t. (1), positive and negative examples # (3) Increment the number of tested concepts attribute. .. py:method:: apply_refinement(rl_state: ontolearn.search.RL_State) -> Generator Downward refinements .. py:method:: select_next_state(current_state, next_rl_states) -> Tuple[ontolearn.search.RL_State, float] .. py:method:: sequence_of_actions(root_rl_state: ontolearn.search.RL_State) -> Tuple[List[Tuple[ontolearn.search.RL_State, ontolearn.search.RL_State]], List[SupportsFloat]] Performing sequence of actions in an RL env whose root state is ⊤ .. py:method:: form_experiences(state_pairs: List, rewards: List) -> None Form experiences from a sequence of concepts and corresponding rewards. state_pairs - A list of tuples containing two consecutive states. reward - A list of reward. Gamma is 1. Return X - A list of embeddings of current concept, next concept, positive examples, negative examples. y - Argmax Q value. .. py:method:: learn_from_replay_memory() -> None Learning by replaying memory. .. py:method:: update_search(concepts, predicted_Q_values=None) @param concepts: @param predicted_Q_values: @return: .. py:method:: get_embeddings_individuals(individuals: List[str]) -> torch.FloatTensor .. py:method:: get_individuals(rl_state: ontolearn.search.RL_State) -> List[str] .. py:method:: assign_embeddings(rl_state: ontolearn.search.RL_State) -> None Assign embeddings to a rl state. A rl state is represented with vector representation of all individuals belonging to a respective OWLClassExpression. .. py:method:: save_weights(path: str = None) -> None Save weights DQL .. py:method:: exploration_exploitation_tradeoff(current_state: ontolearn.abstracts.AbstractNode, next_states: List[ontolearn.abstracts.AbstractNode]) -> ontolearn.abstracts.AbstractNode Exploration vs Exploitation tradeoff at finding next state. (1) Exploration. (2) Exploitation. .. py:method:: exploitation(current_state: ontolearn.abstracts.AbstractNode, next_states: List[ontolearn.abstracts.AbstractNode]) -> ontolearn.search.RL_State Find next node that is assigned with highest predicted Q value. (1) Predict Q values : predictions.shape => torch.Size([n, 1]) where n = len(next_states). (2) Find the index of max value in predictions. (3) Use the index to obtain next state. (4) Return next state. .. py:method:: predict_values(current_state: ontolearn.search.RL_State, next_states: List[ontolearn.search.RL_State]) -> torch.Tensor Predict promise of next states given current state. :returns: Predicted Q values. .. py:method:: retrieve_concept_chain(rl_state: ontolearn.search.RL_State) -> List[ontolearn.search.RL_State] :staticmethod: .. py:method:: generate_learning_problems(num_of_target_concepts, num_learning_problems) -> List[Tuple[str, Set, Set]] Generate learning problems if none is provided. Time complexity: O(n^2) n = named concepts .. py:method:: learn_from_illustration(sequence_of_goal_path: List[ontolearn.search.RL_State]) :param sequence_of_goal_path: ⊤,Parent,Parent ⊓ Daughter. .. py:method:: best_hypotheses(n=1, return_node: bool = False) -> Union[owlapy.class_expression.OWLClassExpression, List[owlapy.class_expression.OWLClassExpression]] Get the current best found hypotheses according to the quality. :param n: Maximum number of results. :returns: Iterable with hypotheses in form of search tree nodes. .. py:method:: clean() Clear all states of the concept learner. .. py:method:: next_node_to_expand() -> ontolearn.search.RL_State Return a node that maximizes the heuristic function at time t. .. py:method:: downward_refinement(*args, **kwargs) Execute one refinement step of a refinement based learning algorithm. :param node: the search tree node on which to refine. :type node: _N :returns: Refinement results as new search tree nodes (they still need to be added to the tree). :rtype: Iterable[_N] .. py:method:: show_search_tree(heading_step: str, top_n: int = 10) -> None A debugging function to print out the current search tree and the current n best found hypotheses to standard output. :param heading_step: A message to display at the beginning of the output. :param top_n: The number of current best hypotheses to print out. .. py:method:: terminate_training() .. py:class:: TDL(knowledge_base, use_inverse: bool = False, use_data_properties: bool = False, use_nominals: bool = False, use_card_restrictions: bool = False, kwargs_classifier: dict = None, max_runtime: int = 1, grid_search_over: dict = None, grid_search_apply: bool = False, report_classification: bool = True, plot_tree: bool = False, plot_embeddings: bool = False, plot_feature_importance: bool = False, verbose: int = 10, verbalize: bool = False) Tree-based Description Logic Concept Learner .. py:attribute:: use_nominals :value: False .. py:attribute:: use_card_restrictions :value: False .. py:attribute:: grid_search_over :value: None .. py:attribute:: knowledge_base .. py:attribute:: report_classification :value: True .. py:attribute:: plot_tree :value: False .. py:attribute:: plot_embeddings :value: False .. py:attribute:: plot_feature_importance :value: False .. py:attribute:: clf :value: None .. py:attribute:: kwargs_classifier .. py:attribute:: max_runtime :value: 1 .. py:attribute:: features :value: None .. py:attribute:: disjunction_of_conjunctive_concepts :value: None .. py:attribute:: conjunctive_concepts :value: None .. py:attribute:: owl_class_expressions .. py:attribute:: cbd_mapping :type: Dict[str, Set[Tuple[str, str]]] .. py:attribute:: types_of_individuals .. py:attribute:: verbose :value: 10 .. py:attribute:: verbalize :value: False .. py:attribute:: data_property_cast .. py:attribute:: X :value: None .. py:attribute:: y :value: None .. py:method:: extract_expressions_from_owl_individuals(individuals: List[owlapy.owl_individual.OWLNamedIndividual]) -> Tuple[Dict[str, owlapy.class_expression.OWLClassExpression], Dict[str, str]] .. py:method:: construct_sparse_binary_representations(features: List[owlapy.class_expression.OWLClassExpression], examples: List[owlapy.owl_individual.OWLNamedIndividual], examples_to_features) -> numpy.array .. py:method:: create_training_data(learning_problem: ontolearn.learning_problem.PosNegLPStandard) -> Tuple[pandas.DataFrame, pandas.DataFrame] .. py:method:: construct_owl_expression_from_tree(X: pandas.DataFrame, y: pandas.DataFrame) -> List[owlapy.class_expression.OWLObjectIntersectionOf] Construct an OWL class expression from a decision tree .. py:method:: fit(learning_problem: ontolearn.learning_problem.PosNegLPStandard = None, max_runtime: int = None) Fit the learner to the given learning problem (1) Extract multi-hop information about E^+ and E^-. (2) Create OWL Class Expressions from (1) (3) Build a binary sparse training data X where first |E+| rows denote the binary representations of positives Remaining rows denote the binary representations of E⁻ (4) Create binary labels. (4) Construct a set of DL concept for each e \in E^+ (5) Union (4) :param learning_problem: The learning problem :param max_runtime:total runtime of the learning .. py:property:: classification_report :type: str .. py:method:: best_hypotheses(n=1) -> Tuple[owlapy.class_expression.OWLClassExpression, List[owlapy.class_expression.OWLClassExpression]] Return the prediction .. py:method:: predict(X: List[owlapy.owl_individual.OWLNamedIndividual], proba=True) -> numpy.ndarray :abstractmethod: Predict the likelihoods of individuals belonging to the classes .. py:class:: CELOE(knowledge_base: ontolearn.abstracts.AbstractKnowledgeBase = None, reasoner: Optional[owlapy.abstracts.AbstractOWLReasoner] = None, refinement_operator: Optional[ontolearn.abstracts.BaseRefinement[ontolearn.search.OENode]] = None, quality_func: Optional[ontolearn.abstracts.AbstractScorer] = None, heuristic_func: Optional[ontolearn.abstracts.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) Bases: :py:obj:`ontolearn.base_concept_learner.RefinementBasedConceptLearner` Class Expression Learning for Ontology Engineering. .. attribute:: best_descriptions Best hypotheses ordered. :type: EvaluatedDescriptionSet[OENode, QualityOrderedNode] .. attribute:: best_only If False pick only nodes with quality < 1.0, else pick without quality restrictions. :type: bool .. attribute:: calculate_min_max Calculate minimum and maximum horizontal expansion? Statistical purpose only. :type: bool .. attribute:: heuristic_func Function to guide the search heuristic. :type: AbstractHeuristic .. attribute:: heuristic_queue A sorted set that compares the nodes based on Heuristic. :type: SortedSet[OENode] .. attribute:: iter_bound Limit to stop the algorithm after n refinement steps are done. :type: int .. attribute:: kb The knowledge base that the concept learner is using. :type: AbstractKnowledgeBase .. attribute:: max_child_length Limit the length of concepts generated by the refinement operator. :type: int .. attribute:: max_he Maximal value of horizontal expansion. :type: int .. attribute:: max_num_of_concepts_tested :type: int .. attribute:: max_runtime Limit to stop the algorithm after n seconds. :type: int .. attribute:: min_he Minimal value of horizontal expansion. :type: int .. attribute:: name Name of the model = 'celoe_python'. :type: str .. attribute:: _number_of_tested_concepts Yes, you got it. This stores the number of tested concepts. :type: int .. attribute:: operator Operator used to generate refinements. :type: BaseRefinement .. attribute:: quality_func :type: AbstractScorer .. attribute:: reasoner The reasoner that this model is using. :type: AbstractOWLReasoner .. attribute:: search_tree Dict to store the TreeNode for a class expression. :type: Dict[OWLClassExpression, TreeNode[OENode]] .. attribute:: start_class The starting class expression for the refinement operation. :type: OWLClassExpression .. attribute:: start_time The time when :meth:`fit` starts the execution. Used to calculate the total time :meth:`fit` takes to execute. :type: float .. attribute:: terminate_on_goal Whether to stop the algorithm if a perfect solution is found. :type: bool .. py:attribute:: __slots__ :value: ('best_descriptions', 'max_he', 'min_he', 'best_only', 'calculate_min_max', 'heuristic_queue',... .. py:attribute:: name :value: 'celoe_python' .. py:attribute:: search_tree :type: Dict[owlapy.class_expression.OWLClassExpression, ontolearn.search.TreeNode[ontolearn.search.OENode]] .. py:attribute:: heuristic_queue .. py:attribute:: best_descriptions .. py:attribute:: best_only :value: False .. py:attribute:: calculate_min_max :value: True .. py:attribute:: max_he :value: 0 .. py:attribute:: min_he :value: 1 .. py:method:: next_node_to_expand(step: int) -> ontolearn.search.OENode Return from the search tree the most promising search tree node to use for the next refinement step. :returns: Next search tree node to refine. :rtype: _N .. py:method:: best_hypotheses(n: int = 1, return_node: bool = False) -> Union[owlapy.class_expression.OWLClassExpression | Iterable[owlapy.class_expression.OWLClassExpression], ontolearn.search.OENode | Iterable[ontolearn.search.OENode]] Get the current best found hypotheses according to the quality. :param n: Maximum number of results. :returns: Iterable with hypotheses in form of search tree nodes. .. py:method:: make_node(c: owlapy.class_expression.OWLClassExpression, parent_node: Optional[ontolearn.search.OENode] = None, is_root: bool = False) -> ontolearn.search.OENode .. py:method:: updating_node(node: ontolearn.search.OENode) Removes the node from the heuristic sorted set and inserts it again. :param Node to update.: :Yields: The node itself. .. py:method:: downward_refinement(node: ontolearn.search.OENode) -> Iterable[ontolearn.search.OENode] Execute one refinement step of a refinement based learning algorithm. :param node: the search tree node on which to refine. :type node: _N :returns: Refinement results as new search tree nodes (they still need to be added to the tree). :rtype: Iterable[_N] .. py:method:: fit(*args, **kwargs) Find hypotheses that explain pos and neg. .. py:method:: encoded_learning_problem() -> Optional[ontolearn.abstracts.EncodedPosNegLPStandardKind] Fetch the most recently used learning problem from the fit method. .. py:method:: tree_node(node: ontolearn.search.OENode) -> ontolearn.search.TreeNode[ontolearn.search.OENode] Get the TreeNode of the given node. :param node: The node. :returns: TreeNode of the given node. .. py:method:: show_search_tree(heading_step: str, top_n: int = 10) -> None Show search tree. .. py:method:: update_min_max_horiz_exp(node: ontolearn.search.OENode) .. py:method:: clean() Clear all states of the concept learner. .. py:class:: OCEL(knowledge_base: ontolearn.abstracts.AbstractKnowledgeBase, reasoner: Optional[owlapy.abstracts.AbstractOWLReasoner] = None, refinement_operator: Optional[ontolearn.abstracts.BaseRefinement[ontolearn.search.OENode]] = None, quality_func: Optional[ontolearn.abstracts.AbstractScorer] = None, heuristic_func: Optional[ontolearn.abstracts.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) Bases: :py:obj:`ontolearn.learners.celoe.CELOE` A limited version of CELOE. .. attribute:: best_descriptions Best hypotheses ordered. :type: EvaluatedDescriptionSet[OENode, QualityOrderedNode] .. attribute:: best_only If False pick only nodes with quality < 1.0, else pick without quality restrictions. :type: bool .. attribute:: calculate_min_max Calculate minimum and maximum horizontal expansion? Statistical purpose only. :type: bool .. attribute:: heuristic_func Function to guide the search heuristic. :type: AbstractHeuristic .. attribute:: heuristic_queue A sorted set that compares the nodes based on Heuristic. :type: SortedSet[OENode] .. attribute:: iter_bound Limit to stop the algorithm after n refinement steps are done. :type: int .. attribute:: kb The knowledge base that the concept learner is using. :type: AbstractKnowledgeBase .. attribute:: max_child_length Limit the length of concepts generated by the refinement operator. :type: int .. attribute:: max_he Maximal value of horizontal expansion. :type: int .. attribute:: max_num_of_concepts_tested :type: int .. attribute:: max_runtime Limit to stop the algorithm after n seconds. :type: int .. attribute:: min_he Minimal value of horizontal expansion. :type: int .. attribute:: name Name of the model = 'ocel_python'. :type: str .. attribute:: _number_of_tested_concepts Yes, you got it. This stores the number of tested concepts. :type: int .. attribute:: operator Operator used to generate refinements. :type: BaseRefinement .. attribute:: quality_func :type: AbstractScorer .. attribute:: reasoner The reasoner that this model is using. :type: AbstractOWLReasoner .. attribute:: search_tree Dict to store the TreeNode for a class expression. :type: Dict[OWLClassExpression, TreeNode[OENode]] .. attribute:: start_class The starting class expression for the refinement operation. :type: OWLClassExpression .. attribute:: start_time The time when :meth:`fit` starts the execution. Used to calculate the total time :meth:`fit` takes to execute. :type: float .. attribute:: terminate_on_goal Whether to stop the algorithm if a perfect solution is found. :type: bool .. py:attribute:: __slots__ :value: () .. py:attribute:: name :value: 'ocel_python' .. py:method:: make_node(c: owlapy.class_expression.OWLClassExpression, parent_node: Optional[ontolearn.search.OENode] = None, is_root: bool = False) -> ontolearn.search.OENode Create a node for OCEL. :param c: The class expression of this node. :param parent_node: Parent node. :param is_root: Is this the root node? :returns: The node. :rtype: OENode