Horje
Role of Knowledge Bases in Intelligent Systems

As AI technology advances, integrating knowledge-based intelligent systems becomes essential for maintaining competitiveness in our fast-paced world. These systems not only use extensive, dynamic knowledge to make informed decisions but also continuously learn and adapt to their environments.

In this article, we will be exploring the concept of knowledge base and its major role in intelligent systems.

What is a Knowledge Base?

A knowledge base is not merely a collection of data; it is an Artificial Intelligence-driven central hub that intelligently organizes and manages information. By consolidating data from various sources, it enables quick retrieval of relevant and accurate information, significantly improving decision-making processes.

Types of Knowledge Bases

  1. Machine Learning-Enhanced Knowledge Bases: These knowledge bases leverage machine learning to extract detailed insights from user interactions, continuously updating themselves with the most relevant information to ensure timely and accurate responses.
  2. Semantic Knowledge Bases: With the ability to understand the deeper meanings behind user inputs, these bases use semantic search to quickly link queries to the appropriate information, crucial for handling complex customer service interactions.
  3. NLP Knowledge Bases: These systems utilize Natural Language Processing (NLP) to interpret and generate human language, making them ideal for applications like customer service chatbots that need to understand and respond to user queries accurately.
  4. Predictive Knowledge Bases: By anticipating potential issues before they arise, predictive knowledge bases proactively update their content, enabling customer service agents to offer preemptive solutions, thus enhancing overall service efficiency and preventing problems.

Components and structure of the knowledge base

The typical knowledge model has three components and each of these components is a related group of knowledge structures. The knowledge components can also be called as knowledge category. The three major components are explained below:

Structure-of-knowledge-base

Structure of Knowledge Based

Domain knowledge

The Domain-knowledge is the first component of the knowledge model. This component is responsible for specifying the domain-specific knowledge and information that are relevant to a particular area or application. For example, in a medical diagnosis, the domain knowledge includes the definition of diseases, symptoms, and tests, and how they are related. It’s similar to a data model or object model in software engineering which provides a structured way to describe the important concepts in that field.

The domain-knowledge description generally contains two major elements:

  • Domain schema: The domain schema is a schematic description of the domain-specific knowledge and information needed for a particular area or topic. It uses different types to define the structure of this knowledge. This schema shows how things are organized in that area, but it doesn’t change much over time. In the context of the knowledge base, the domain schema resembles a framework or structure that helps to organize and represent information in our AI system.
  • Knowledge base: A knowledge base accommodates the instances of the types specified in the domain schema. In knowledge modeling, we often have different knowledge bases for different types of knowledge. For example, we might have one knowledge base for rules and another for other types of pieces of information.

Inference knowledge

Inference knowledge is the second component of the knowledge model. Inference knowledge refers to the reasoning steps used with the domain knowledge to make decisions. These steps are like building blocks of a reasoning system. In technical terms, they are the basic functional components. For example, in a medical diagnosis application, one inference might hypothesize a disease based on the symptoms, and another might verify it by identifying tests to confirm the disease.

  • Knowledge roles: Inference I/O role is described as functional roles. This role is known as the knowledge role. There are two types of knowledge roles one is Dynamic and static roles.
    1. Dynamic role: Dynamic roles are said to be the run-time inputs and outputs of the inferences.
    2. Static roles: It specifies the group of domain knowledge that is used to make the inference.
  • Transfer functions: The transfer function is the function that is responsible for transferring the information between the reasoning agent that was described in the knowledge model and the outside world. It is also considered as a black box that only describes their name and I/O.
  • There are four types of transfer functions, they are:
    1. Obtain: The external agent contains the information item. The reasoning agent initiates the request a piece of information from an external agent.
    2. Receive: The reasoning agent receives the piece of information from the external agent which takes the initiative and holds the information item.
    3. Present: The reasoning agent shares the information with an external agent. It takes the initiative and has the information.
    4. Provide: The system gives the information to the external agent. Here, the external agent takes the initiative and the reasoning agent has the information item.

Task knowledge

Task knowledge is the third component of the knowledge model. It describes the goals of an application and how these goals are said to be achieved through smaller tasks and steps. It also includes how these tasks are controlled or managed internally. For instance, in a medical diagnosis, the important tasks that are said to be performed might be diagnosing the illness and that can be achieved by repeating the steps like hypothesizing and verifying them within the tests. In simpler terms, Task knowledge is like breaking down big tasks into smaller ones and it also includes how the functions are controlled within the system.

There are two types of task knowledge:

  • Task: A task specifies the complex reasoning function. It is the top-level tasks that correspond to a task identified in the task model. The specification of a task tells the user what kind of inputs and outputs of the tasks are.
  • Task method: A task method is like a set of instructions for how to do specific tasks. It breaks the tasks down into smaller steps, which can be other tasks, reasoning steps, or actions like obtaining information. The part part of a task method is the control structure which tells us to do these smaller steps. It’s kind of like a simple program where the steps are the actions we take and the roles are the instructions for those actions. The control structure helps us understand how we’re solving the problem like a strategy. Sometimes, a task method might also include extra roles to help keep track of the information we need temporarily.

Role of Intelligent Systems in the Knowledge Base

  • Classification tasks: The intelligent system can be employed where there are classification tasks. It potentially helps the system to analyze the different data to understand its classification status.
  • Expert systems: Knowledge base plays a vital role in expert systems because it simulates the human expert decision-making in a specific field. The expert system is capable of providing the solution based on the information item in the knowledge base and strives the decision-making process efficiently.
  • Medical diagnosis system: As we have seen earlier, the intelligent system in the knowledge base a huge role in the medical diagnosis system. It helps the diagnosis patients to input their data or it lets the patients answer a series of questions. Based on the responses from the patients it identifies the diagnosis and provides recommendations so that the medical professionals can use this information to treat the patient.
  • Rule-based systems: Rule-based intelligent system typically relies on human-specified rules that can be used to analyze or modify the data to obtain the desired outcome.

Implementation of Knowledge-based Intelligent System

Step 1: Importing libraries

Initially we import the required library. The spacy is an open source library and can be used for advanced NLP in python. It offers variety of advantages such as processing and analyzing the large volume of text data.

import spacy

Step 2: Knowledge Base initialization

We define KnowledgeBase class that initializes the three attributes called domain_knowledge, inference_rules, and task_methods.

  • domain_knowledge: It is a dictionary to store domain-specific knowledge
  • inference_rules: It is a list to store the rules which can be further used for making inferences.
  • task_methods: It is a list to store methods for performing tasks.
class KnowledgeBase:
def __init__(self):
self.domain_knowledge = {}
self.inference_rules = []
self.task_methods = []

def load_domain_knowledge(self, knowledge):
self.domain_knowledge.update(knowledge)

def load_inference_rules(self, rules):
self.inference_rules.extend(rules)

def load_task_method(self, methods):
self.task_method.extend(methods)

Step 3: Inference Engine

We then initialize the class called InferenceEngine with a reference to the knowledge_base. The infer method processes input data against the inference rules and returns the conclusions. It iterates through each rule and applies it using the apply_rule method. This apply_rule is responsible for checking if all the conditions in a rule are met. And the check_condition verfies if a specific condition is satisfied by comparing attributes in the input data.

class InferenceEngine:
def __init__(self, knowledge_base):
self.knowledge_base = knowledge_base

def infer(self, input_data):
results = []
for rule in self.knowledge_base.inference_rules:
if self.apply_rule(rule, input_data):
results.append(rule['conclusion'])

def apply_rule(self, rule, input_data):
conditions = rule['conditions']
for condition in conditions:
if not self.check_condition(condition, input_data):
return False
return True

def check_condition(self, condition, input_data):
return input_data.get(condition['attribute']) == condition['value']

Step 4: NLP processor

The class NLP processor class initializes the spacy NLP model. The process_query processes a user query to identify the intent and entities. This method iterates through tokens in the query to find the root web (intent) and entities based on keywords and named entities.

class NLPProcessor:
def __init__(self):
self.nlp = spacy.load('en_core_web_sm')

def process_query(self, query):
doc = self.nlp(query)
intent = None
entities = {}
for token in doc:
if token.dep_ == 'ROOT':
if token.lemma_ in ['have', 'do', 'improve']:
intent = token.lemma_
else:
intent = token.text
if token.ent_type:
entities[token.ent_type_] = token.text.lower()
elif token.lemma_ in ['fever', 'battery']:
entities[token.lemma_] = token.text.lower()
return {'intent': intent, 'entities': entities}

Step 5: Knowledge Base Query

The KnowledgeBaseQuery class initializes with a reference to the knowledge_base. The query method processes the structured query to find relevant information from the knowledge base. The search_knowledge looks up the intent and entities in the knowledge base to find and return the relevant information.

class KnowledgeBaseQuery:
def __init__(self, knowledge_base):
self.knowledge_base = knowledge_base

def query(self, structured_query):
intent = structured_query['intent']
entities = structured_query['entities']
relevant_info = self.search_knowledge(intent, entities)
return relevant_info

def search_knowledge(self, intent, entities):
if intent in self.knowledge_base.domain_knowledge:
return self.knowldege_base.domain_knowledge[intent]
for entity in entities.values():
if entity in self.knowledge_base.domain_knowledge:
return self.knowledge_base.domain_knowledge[entity]
return "No relevant information found"

Step 6: Main Function

The main function initializes the knowledge base and loads domain knowledge and inference rules. The nlp_processor is responsible for processing the user input to create a structured query. Debug prints show the structured query and inference results. The inference_engine infers results based on structured query entities. The kb_query queries the knowledge base to get a response based on the structured query’s intent and entities.

def main(user_input):
kb = KnowledgeBase()
kb.load_domain_knowledge({
'diagnose': 'Medical diagnosis information',
'fever': 'Possible flu',
'battery': 'Battery optimization tips',
'battery life': 'Check battery optimization settings'
})
kb.load_inference_rules([
{'conditions': [{'attribute': 'symptom', 'value': 'fever'}],
'Conclusion': 'Possible flu'},
{'conditions': [{'attribute': 'question', 'value': 'battery life'}],
'conclusion': ' Check battery optimization settings'}
])

nlp_processor = NLPProcessor()
structured_query = nlp_processor.process_query(user_input)
print(f"Structured Query: {structured_query}")

inference_engine = InferenceEngine(kb)
inference_results = inference_engine.infer(structured_query['entities'])
print(f"Inference Results: {inference_results}")

kb_query = KnowledgeBaseQuery(kb)
response = kb_query.query(
{'intent': structured_query['intent'], 'entities': structured_query['entities']})

return response

Step 7: Example usage

user_input = "I have a fever"
response = main(user_input)
print(response)

user_input = "what can I do to improve my battery life?"
response = main(user_input)
print(response)
  • The NLP processor converts user input into structured queries with intents and entities.
  • The inference Engine checks if the structured query matches any predefined inference rules. Since no matched, the inference results were None.
  • The Knowledge Base Query then searches the knowledge base for relevant information based on the identified entities and intent, returning the corresponding information for fever and battery.

Complete code

Python
import spacy


class KnowledgeBase:
    def __init__(self):
        self.domain_knowledge = {}
        self.inference_rules = []
        self.task_methods = []

    def load_domain_knowledge(self, knowledge):
        self.domain_knowledge.update(knowledge)

    def load_inference_rules(self, rules):
        self.inference_rules.extend(rules)

    def load_task_method(self, methods):
        self.task_method.extend(methods)


class InferenceEngine:
    def __init__(self, knowledge_base):
        self.knowledge_base = knowledge_base

    def infer(self, input_data):
        results = []
        for rule in self.knowledge_base.inference_rules:
            if self.apply_rule(rule, input_data):
                results.append(rule['conclusion'])

    def apply_rule(self, rule, input_data):
        conditions = rule['conditions']
        for condition in conditions:
            if not self.check_condition(condition, input_data):
                return False
        return True

    def check_condition(self, condition, input_data):
        return input_data.get(condition['attribute']) == condition['value']


class NLPProcessor:
    def __init__(self):
        self.nlp = spacy.load('en_core_web_sm')

    def process_query(self, query):
        doc = self.nlp(query)
        intent = None
        entities = {}
        for token in doc:
            if token.dep_ == 'ROOT':
                if token.lemma_ in ['have', 'do', 'improve']:
                    intent = token.lemma_
                else:
                    intent = token.text
            if token.ent_type:
                entities[token.ent_type_] = token.text.lower()
            elif token.lemma_ in ['fever', 'battery']:
                entities[token.lemma_] = token.text.lower()
        return {'intent': intent, 'entities': entities}


class KnowledgeBaseQuery:
    def __init__(self, knowledge_base):
        self.knowledge_base = knowledge_base

    def query(self, structured_query):
        intent = structured_query['intent']
        entities = structured_query['entities']
        relevant_info = self.search_knowledge(intent, entities)
        return relevant_info

    def search_knowledge(self, intent, entities):
        if intent in self.knowledge_base.domain_knowledge:
            return self.knowldege_base.domain_knowledge[intent]
        for entity in entities.values():
            if entity in self.knowledge_base.domain_knowledge:
                return self.knowledge_base.domain_knowledge[entity]
        return "No relevant information found"


def main(user_input):
    kb = KnowledgeBase()
    kb.load_domain_knowledge({
        'diagnose': 'Medical diagnosis information',
        'fever': 'Possible flu',
        'battery': 'Battery optimization tips',
        'battery life': 'Check battery optimization settings'
    })
    kb.load_inference_rules([
        {'conditions': [{'attribute': 'symptom', 'value': 'fever'}],
            'Conclusion': 'Possible flu'},
        {'conditions': [{'attribute': 'question', 'value': 'battery life'}],
            'conclusion': ' Check battery optimization settings'}
    ])

    nlp_processor = NLPProcessor()
    structured_query = nlp_processor.process_query(user_input)
    print(f"Structured Query: {structured_query}")

    inference_engine = InferenceEngine(kb)
    inference_results = inference_engine.infer(structured_query['entities'])
    print(f"Inference Results: {inference_results}")

    kb_query = KnowledgeBaseQuery(kb)
    response = kb_query.query(
        {'intent': structured_query['intent'], 'entities': structured_query['entities']})

    return response


user_input = "I have a fever"
response = main(user_input)
print(response)

user_input = "what can I do to improve my battery life?"
response = main(user_input)
print(response)

Output:

Structured Query: {'intent': 'have', 'entities': {'fever': 'fever'}}
Inference Results: None
Possible flu
Structured Query: {'intent': 'do', 'entities': {'battery': 'battery'}}
Inference Results: None
Battery optimization tips

Conclusion

The knowledge base is one of the crucial components in the intelligent system that stores and organizes information. With the help of this information, the intelligent system can make decisions, solve problems, and even learn from experiences. By utilizing technologies like Machine learning and NLP, the knowledge enhances the efficiency and accuracy of the tasks that they were involved in.




Reffered: https://www.geeksforgeeks.org


AI ML DS

Related
E-commerce product recommendations using catboost E-commerce product recommendations using catboost
Handle streaming data in a data engineering pipeline Handle streaming data in a data engineering pipeline
What are the various methods and tools available for extracting data in ETL processes? What are the various methods and tools available for extracting data in ETL processes?
How can you deploy a big data solution? How can you deploy a big data solution?
How Good is R for Data Visualization? How Good is R for Data Visualization?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16