Ai Tu Cse
Ai Tu Cse
By
Dr B Nandini,
Associate Professor, Dept of CSE, Telangana
University
• There are three kinds of Intelligence:
– One kind understand things for itself,
– The other appreciates what others can understand,
– The third understands neither for itself nor through
others.
• The first kind is excellent, the second good, and
the third kind useless.
Niccolo Machiavelli (1469-1527)
----
This algorithm is more involved and takes longer but it is more efficient in
storage which compensates for its longer time. It depends on the programmer’s
skill.
• Data Structure:
1) Use vector, called board, as Solution 1
2) However, elements of the vector:
2: Empty
3: X
5: O
3) Turn of move: indexed by integer 1,2,3, etc
Make2:
a) Return a location on a game-board.
IF (board[5] = 2) RETURN 5;
//the center cell.
ELSE RETURN any cell that is not at the
board’s corner; // (cell: 2,4,6,8)
b) Let P represent for X or O
c) can_win(P) : P has filled already at least two
cells on a straight line (horizontal, vertical,
or diagonal)
d) cannot_win(P) = NOT(can_win(P))
2. Posswin(P):
IF (cannot_win(P))
RETURN 0;
ELSE
RETURN index to the empty cell on the line of
can_win(P)
Let odd numbers are turns of X
Let even numbers are turns of O
3. Go(n): make a move
Algorithm
1. Turn = 1: (X moves)
• Go(1) //make a move at the left-top cell
2. Turn = 2: (O moves)
IF board[5] is empty THEN Go(5)
ELSE Go(1)
3. Turn = 3: (X moves)
IF board[9] is empty THEN Go(9)
ELSE Go(3).
4. Turn = 4: (O moves)
IF Posswin (X) <> 0 THEN Go (Posswin (X)) //Prevent the opponent to win
ELSE Go (Make2)
5. Turn = 5: (X moves)
IF Posswin(X) <> 0 THEN Go(Posswin(X)) //Win for X.
ELSE IF Posswin(O) <> THEN Go(Posswin(O)) //Prevent the opponent to win
ELSE IF board[7] is empty THEN Go(7)
ELSE Go(3).
Comments:
1. Not efficient in time, as it has to check
several conditions before making each move.
2. Easier to understand the program’s strategy.
3. Hard to generalize.
Program 2’
• This is similar to program 2 but only change in board
representation. 8 3 4
1 5 9
6 7 2
• def print_board(board):
• """
• Prints the Tic Tac Toe board in a formatted way.
• """
• for i in range(3):
• print(' | '.join(board[i * 3:(i * 3) + 3]))
• if i < 2:
• print('-' * 9)
• def is_board_full(board):
• """
• Checks if all the squares on the board are filled.
• """
• return all(x != ' ' for x in board)
• def main():
• """
• Main function to run the Tic Tac Toe game.
• """
• board = create_board()
• current_player = 'X'
• while True:
• print_board(board)
•
• # Get player input
• position = int(input(f"Player {current_player}, enter your move (1-9): ")) - 1
•
• # Validate move
• if not is_valid_move(board, position):
• print("Invalid move. Please try again.")
• continue
• # Make move
• make_move(board, current_player, position)
• # Switch player
• current_player = 'O' if current_player == 'X' else 'X'
• if __name__ == "__main__":
• main()
Example-2: Question Answering
• Let us consider Question Answering systems
that accept input in English and provide
answers also in English.
• This problem is harder than the previous one
as it is more difficult to specify the problem
properly.
• Another area of difficulty concerns deciding
whether the answer obtained is correct, or
not, and further what is meant by ‘correct’.
For example, consider the following situation:
• Text
– Rani went shopping for a new Coat. She found a
red one she really liked. When she got home, she
found that it went perfectly with her favourite
dress.
• Question
1. What did Rani go shopping for?
2. What did Rani find that she liked?
3. Did Rani buy anything?
Method 1
• Data Structures
– A set of templates that match common questions and
produce patterns used to match against inputs.
Templates and patterns are used so that a template
that matches a given question is associated with the
corresponding pattern to find the answer in the input
text.
– For example, the template who did x y generates x y z
if a match occurs and z is the answer to the question.
The given text and the question are both stored as
strings.
Algorithm: Answering a question requires the
following four steps to be followed:
• Compare the template against the questions
and store all successful matches to produce a
set of text patterns.
• Pass these text patterns through a substitution
process to change the person or voice and
produce an expanded set of text patterns.
• Apply each of these patterns to the text;
• collect all the answers and then print the
answers.
Example:
In question 1 we use the template WHAT DID X Y
which generates Rani go shopping for z and after
substitution we get Rani goes shopping for z and
Rani went shopping for z giving z [equivalence] a
new coat.
In question 2 we need a very large number of
templates and also a scheme to allow the insertion
of ‘find’ before ‘that she liked’; the insertion of
‘really’ in the text; and the substitution of ‘she’ for
‘Rani’ gives the answer ‘a red one’.
Question 3 cannot be answered.
• Comments :
– This is a very primitive approach basically not
matching the criteria we set for intelligence and
worse than that, used in the game. Surprisingly
this type of technique was actually used in ELIZA.
Method 2
Data Structures:
A structure called English consists of a dictionary, grammar and
some semantics about the vocabulary we are likely to come across.
This data structure provides the knowledge to convert English text
into a storable internal form and also to convert the response back into
English.
The structured representation of the text is a processed form and
defines the context of the input text by making explicit all references
such as pronouns.
There are three types of such knowledge representation systems:
production rules of the form ‘if x then y’,
slot and filler systems
and statements in mathematical logic.
The system used here will be the slot and filler system.
Take, for example sentence: ‘She found a red one she
really liked’.
Comments
This approach is more meaningful than the
previous one and so is more effective. The extra power
given must be paid for by additional search time in the
knowledge bases.
A warning must be given here: that is – to generate
unambiguous English knowledge base is a complex task.
The problems of handling pronouns are difficult.
For example:
• Rani walked up to the salesperson: she asked
where the toy department was.
• Rani walked up to the salesperson: she asked
her if she needed any help.
– Whereas in the original text the linkage of ‘she’ to
‘Rani’ is easy, linkage of ‘she’ in each of the above
sentences to Rani and to the salesperson requires
additional knowledge about the context via the
people in a shop.
Method 3
• Data Structures :
• World model contains knowledge about objects,
actions and situations that are described in the input
text.
• This structure is used to create integrated text from
input text.
• The diagram shows how the system’s knowledge of
shopping might be represented and stored.
• This information is known as a script and in this case
is a shopping script.
Algorithm
• Convert the question to a structured form using
both the knowledge contained in Method 2 and the
World model, generating even more possible
structures, since even more knowledge is being
used. Sometimes filters are introduced to prune the
possible answers.
• To answer a question, the scheme followed is:
Convert the question to a structured form as before
but use the world model to resolve any ambiguities
that may occur. The structured form is matched
against the text and the requested segments of the
question are returned.
• Example
– Both questions 1 and 2 generate answers, as in
the previous program.
– Question 3 can now be answered. The shopping
script is instantiated and from the last sentence
the path through step 14 is the one used to form
the representation. ‘M’ is bound to the red coat-
got home. ‘Rani buys a red coat’ comes from step
10 and the integrated text generates that she
bought a red coat.
• Comments
• This program is more powerful than both the previous
programs because it has more knowledge.
• Thus, like the last game program it is exploiting AI
techniques.
• However, we are not yet in a position to handle any English
question. The major omission is that of a general reasoning
mechanism known as inference to be used when the
required answer is not explicitly given in the input text.
• But this approach can handle, with some modifications,
questions of the following form with the answer—Saturday
morning Rani went shopping. Her brother tried to call her
but she did not answer.
– Question: Why couldn’t Rani’s brother reach her?
– Answer: Because she was not in.
• This answer is derived because we have
supplied an additional fact that a person
cannot be in two places at once. This patch is
not sufficiently general so as to work in all
cases and does not provide the type of
solution we are really looking for.
• Question answering (QA) is a fundamental and challenging problem in the field of Artificial Intelligence (AI),
specifically within Natural Language Processing (NLP). It aims to develop systems that can automatically
answer questions posed by humans in natural language.
Here are some key aspects of the question answering problem:
• Ambiguity and complexity of natural language: Language can be ambiguous, with multiple meanings for
words and phrases depending on context. Understanding the nuances of language is challenging for AI
systems.
• Open ended and challenging questions: Not all questions have clear-cut answers, and some may require
reasoning, common sense, or knowledge of the real world that is difficult to encode in a computer
program.
• Keeping knowledge bases and information sources up-to-date: As the world and information constantly
change, ensuring the knowledge base and information sources used by QA systems are accurate and up-to-
date is crucial.
• Returns:
• A potential answer extracted from the text (string), or "No answer found" if no match is found.
• """
• # Process the question and text using spaCy
• doc_question = nlp(question)
• doc_text = nlp(text)
• # Extract named entities from the question
• question_entities = [ent.text for ent in doc_question.ents]
• # Look for entities and keywords in the text that match the question
• for entity in question_entities:
• if entity.lower() in text.lower():
• # Simplistic answer extraction based on keyword matching
• return f"A possible answer based on keyword matching: {entity}"
• return "No answer found"
• # Example usage
• question = "What is the capital of France?"
• text = "France is a European country. Paris is its capital city."
• answer = answer_question(question, text)
• print(answer)
• #output
• = RESTART: C:/Users/NANDINI/AppData/Local/Programs/Python/Python311/Scripts/nlp.py
• A possible answer based on keyword matching: France
Example:
You are using a search engine and want to know the capital of France. You type the question:
"What is the capital of France?" into the search bar.
• The question answering system performs the following steps:
• Understanding the question: The system identifies the question type (factual question) and
recognizes the named entity "France" as a country.
• Finding relevant information: The system searches its database of information, which may
include text documents and knowledge bases. It retrieves relevant information related to
"France" and its capital city.
• Generating the answer: The system extracts the answer "Paris" from the retrieved
information and presents it to you in a concise and informative way: "The capital of France is
Paris."
• Additional Information:
• This example showcases a retrieval-based approach to question answering. However, other
approaches exist, including generative models that might directly generate an answer like:
"Bonjour! I can tell you that the capital of France is the beautiful city of Paris."
• Furthermore, question answering systems are constantly evolving, and researchers are
exploring ways to improve their capabilities in various aspects, such as:
• Handling more complex and open-ended questions.
• Understanding the context of the question and providing relevant answers based on the
context.
• Generating answers that are not only factually accurate but also grammatically correct and
engaging.
Example:
• Scenario:
• You're reading an online news article about the latest advancements in electric vehicle technology. You
come across a sentence mentioning "lithium-ion batteries" and are curious about their specific
advantages and disadvantages. Instead of searching the web yourself, you decide to ask the built-in AI
assistant within the news platform: "What are the advantages and disadvantages of lithium-ion
batteries?"
• The question answering system performs the following steps:
• Understanding the context: The system analyzes the surrounding text and recognizes the mention of
"lithium-ion batteries" within the context of the news article about electric vehicles. This helps the
system understand the user's intent and focus on information related to the specific context.
• Finding relevant information: The system leverages its knowledge base and potentially searches the
surrounding article for relevant information about lithium-ion batteries. It retrieves information that
discusses both the advantages (e.g., high energy density, long lifespan) and disadvantages (e.g., cost,
safety concerns).
• Generating the answer: The system summarizes the retrieved information, focusing on the advantages
and disadvantages relevant to the context of electric vehicles. It presents the answer in a concise and
informative way, potentially even referencing specific details from the surrounding article.
• Example Answer:
• "Lithium-ion batteries offer several advantages for electric vehicles, including high energy density,
allowing for longer range on a single charge, and longer lifespans compared to other battery
technologies. However, they also come with disadvantages, such as higher cost compared to some
alternatives and potential safety concerns related to thermal runaway in rare cases."
• This example demonstrates a hybrid approach, combining context understanding with information
retrieval and summarization to provide a focused and informative answer tailored to the user's specific
question within the context of the surrounding information.
Conclusion:
• In the above 2 problems, the final program
exemplifies what we mean by an AI
Technique. Here come across 3 main AI
Techniques:
– Search
– Use of Knowledge
– Abstraction
The Level of the Model(Approaches to AI)
• Acting humanly: The Turing test approach ..
• Thinking humanly: The cognitive modelling
approach ..
• Thinking rationally: The ``laws of thought''
approach ..
• Acting rationally: The rational agent
approach..
Acting humanly: The Turing test approach
Cont..
To pass the Turing Test a machine will need the capabilities of
-natural language processing to enable it to communicate
successfully in English;
- knowledge representation to store what it knows or hears;
- automated reasoning to use the stored information to
answer questions and to draw new conclusions;
- machine learning to adapt to new circumstances and to
detect and extrapolate patterns.
Total Turing Test: Also tests the subject’s perceptual abilities
through video and passing physical objects; additional
capabilities of
- Computer vision
- Robotics
Cont..
• Importance: This approach focuses on
creating AI systems that interact with humans
in a natural and understandable way.
• This can improve user experience, trust, and
acceptance of AI.
• Examples include chatbots that use natural
language or robots that move and behave in
ways that are familiar to humans.
"Thinking Humanly: The Cognitive Modeling
Approach":
• the idea of creating computer programs that
think like humans.
• determining how humans think.
• need to get inside the actual workings of
human minds.
• There are three ways to do this: introspection,
psychological experiments, and brain
imaging.
Cont..
• through introspection—trying to catch our
own thoughts as they go by;
• through psychological experiments—
observing a person in action;
• and through brain imaging—observing the
brain in action.
Building Cognitive Models:
• Understanding the Mind Through Computation-
Cognitive models are computational
representations of mental processes. They attempt
to capture how humans think, learn, and make
decisions.
• The interdisciplinary field of cognitive science brings
together computer models from AI and
experimental techniques from psychology to
construct precise and testable theories of the
human mind.
Building these models involves:
1. Defining the Scope:
– What cognitive process are you modeling? (e.g., memory, decision-making, language
comprehension)
– What level of detail is needed? (e.g., individual neurons, brain regions, psychological constructs)
2. Gathering Data:
– Behavioral data (e.g., reaction times, accuracy rates)
– Physiological data (e.g., brain scans, eye movements)
– Introspective data (e.g., verbal reports, self-reflection)
3. Choosing a Computational Framework:
– Symbolic AI (e.g., rules, logic)
– Connectionist AI (e.g., artificial neural networks)
– Bayesian networks (e.g., probabilistic reasoning)
4. Developing the Model:
– Implementing the chosen framework
– Training the model on the gathered data
– Refining the model based on evaluation
5. Testing and Evaluation:
– Comparing model predictions to human behavior
– Analyzing strengths and weaknesses of the model
– Iterating on the model based on the evaluation
Cont..
• Importance: This approach aims to replicate
human-like cognitive abilities, such as
learning, reasoning, and problem-solving.
• This can lead to more adaptable and
intelligent AI systems.
• Examples include self-driving cars that make
decisions like human drivers or AI systems that
diagnose diseases like doctors.
Thinking Rationally: The "Laws of Thought" Approach
• Formal rules and reasoning: Can logical rules be used to draw valid
conclusions? Philosophers like Aristotle and Leibniz explored this
question, laying the groundwork for symbolic reasoning in AI.
• Mind and matter: Is the mind a physical system governed by the laws of
physics, or something separate from it? This debate between dualism
(Descartes) and materialism has implications for understanding how
intelligence arises.
• Source of knowledge: Where does knowledge come from? Empiricism
(Locke, Hume) emphasizes sensory experience, while rationalism
(Leibniz) highlights the role of reason. AI research draws on both
perspectives.
• Knowledge and action: How does knowledge lead to action? Aristotle's
work on goal-directed reasoning and decision-making has influenced
research in planning and decision-making for AI systems.
Mathematics : This delves into the mathematical foundations of
Artificial Intelligence (AI), focusing on three key areas :
• Early computers: The first digital computers were developed during World
War II, with the Colossus and ENIAC being influential early models. These
machines laid the foundation for modern computers.
• Moore's Law: For several decades, computer performance roughly doubled
every two years, following a trend known as Moore's Law. This rapid
progress was fueled by miniaturization of transistors and other components.
• Challenges and future directions: As miniaturization reaches its
limits, future performance gains are expected to come from other
innovations like parallel processing and specialized hardware.
• Software's role: the importance of software, including operating
systems, programming languages, and tools, in enabling AI development.
• AI's contributions to computer science: how research in AI has also led to
advancements in mainstream computer science, such as time-
sharing, interactive interfaces, and new programming concepts.
Control theory and cybernetics:
• Early examples of self-control: The idea of machines regulating their own behavior dates
back centuries, as seen in inventions like the water clock and the steam engine governor.
• Birth of control theory: The 19th century saw the development of the mathematical
foundation for stable feedback systems, paving the way for more advanced control
mechanisms.
• Norbert Wiener and cybernetics: Wiener's work bridged the gap between engineering and
biology, suggesting parallels between machine control and animal behavior. His book
"Cybernetics" popularized the notion of intelligent machines.
• Homeostasis and adaptation: W. Ross Ashby and others explored the concept of
"homeostasis," where systems maintain stability through feedback loops, as a potential
principle for achieving intelligence.
• Modern control theory: Today, control theory aims to design systems that optimize specific
objectives over time, reflecting a common goal with AI.
• Divergence of AI and control theory: Despite their shared history, the two fields diverged
due to differences in their mathematical tools and the types of problems they addressed.
Control theory focused on continuous variables and well-defined systems, while AI explored
broader challenges like language, vision, and planning.
Linguistics: an interesting look at the relationship between linguistics and artificial
intelligence (AI), particularly regarding language and thought. Here are some key points: