Experiment No: 4: Artificial Intelligence (3170716)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Artificial Intelligence (3170716) 210170107518

Experiment No: 4

Convert the given Prolog predicates into Semantic Net.

cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).

Date:

Competency and Practical Skills:Understanding of basics of semantic Net.

Relevant CO: CO2

Objectives:To Learn Basic symbols of Semantic Net.

Equipment/Instruments: Personal Computer, open-source software for programming

Theory:

Semantic Nets provide a powerful tool for representing and organizing knowledge in artificial
intelligence.

Semantic Nets use symbols to represent concepts and relationships between them. Here are the
common symbols used in Semantic Nets:

• Nodes or Concepts: Nodes represent concepts or objects in the Semantic Net. They are
usually represented by rectangles, circles or ovals. The name of the concept is usually
written inside the node.
• Arcs or Relations: Arcs represent the relationships between concepts in the Semantic Net.
They are usually represented by arrows or lines connecting two nodes. The label of the arc
describes the relationship between the two nodes.
• Attributes: Attributes are used to describe the properties or characteristics of a node or
concept. They are usually written inside the node as smaller labels.
• Values: Values represent the specific values of attributes associated with a particular node
or concept. They are usually written next to the attribute label in the node.
• Unary Relations: Unary relations are used to represent a relationship between a concept and
an attribute. They are usually represented by an arrow pointing from the attribute to the
concept.
• Cardinality: Cardinality is used to indicate the number of objects that are related to a
particular concept. It is usually represented by a small number in a circle or next to the arc.
• Inheritance: Inheritance is used to represent the relationship between a general concept and
a more specific concept. It is usually represented by an arrow pointing from the specific
concept to the more general concept.
Artificial Intelligence (3170716) 210170107518

This representation consists of mainly two types of relations:


IS-A relation (Inheritance)
Kind-of-relation

Safety and necessary Precautions:

When creating a semantic net, it is important to avoid ambiguity by using clear and
concise notations. Ambiguity can lead to confusion and misinterpretation of the net.

Procedure:
1. Create a node for each object or concept.
2. Create an arc between each object and its attribute or property.
3. Add appropriate labels to each node and arc to indicate the relationship between objects.

Observation/Program:

Conclusion:

The Prolog program and its associated semantic network depict a series of relationships and facts.
It classifies Tom and Cat1 as cats, each being mammals and animals. Tom is further defined as
having ginger fur and being owned by John. Cat1 is shown to sit on Mat1, while Tom has caught
Bird1, establishing a predator-prey relationship. The program introduces a rule that entities liking
cream are considered cats, allowing for a simple form of inference. Overall, this Prolog program
provides a structured representation of entities, their attributes, ownership, and actions,
demonstrating the utility of Prolog in encoding and reasoning about relationships in a logical
manner.

Quiz:

1. What is the advantage of using Semantic Nets for knowledge representation?


 The advantage of using Semantic Nets for knowledge representation is their ability to
represent and relate concepts using nodes and edges, making it easier to express complex
Artificial Intelligence (3170716) 210170107518
relationships and infer information.

2. What is the IS-A relation in a Semantic Net?


 The IS-A relation in a Semantic Net represents a hierarchical relationship where one concept
or class is a subtype or instance of another, indicating a "is-a" or "kind-of" relationship
between them.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students:

1. https://rashandeepsingh.medium.com/what-is-semantic-net-give-example-1757afa43ea6
2. https://lucid.app/documents#/documents?folder_id=recent

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 5

Construct the Conceptual Dependency for the given statements.


1) John gives Mary a book
2) John gave Mary the book yesterday.

Date:

Competency and Practical Skills: Understanding of basics of Knowledge Representation.

Relevant CO: CO2

Objectives: To identify the agents involved


To identify the action performed
To identify the object of the action

Equipment/Instruments: Personal Computer, open-source software

Theory:

Conceptual Dependency originally developed to represent knowledge acquired from natural


language input.
The goals of this theory are:

• To help in the drawing of inference from sentences.


• To be independent of the words used in the original input.
• That is to say: For any 2 (or more) sentences that are identical in meaning there
should be only one representation of that meaning.

It has been used by many programs that portend to understand English (MARGIE, SAM,
PAM). CD developed by Schank et al. as were the previous examples.

CD provides:

• a structure into which nodes representing information can be placed


• a specific set of primitives
• at a given level of granularity.

Sentences are represented as a series of diagrams depicting actions using both abstract and
real physical situations.

• The agent and the objects are represented


• The actions are built up from a set of primitive acts which can be modified by
tense.

Examples of Primitive Acts are:

ATRANS
-- Transfer of an abstract relationship. e.g. give.
PTRANS
-- Transfer of the physical location of an object. e.g. go.
PROPEL
Artificial Intelligence (3170716) 210170107518
-- Application of a physical force to an object. e.g. push.
MTRANS
-- Transfer of mental information. e.g. tell.
MBUILD
-- Construct new information from old. e.g. decide.
SPEAK
-- Utter a sound. e.g. say.
ATTEND
-- Focus a sense on a stimulus. e.g. listen, watch.
MOVE
-- Movement of a body part by owner. e.g. punch, kick.
GRASP
-- Actor grasping an object. e.g. clutch.
INGEST
-- Actor ingesting an object. e.g. eat.
EXPEL
-- Actor getting rid of an object from body. e.g. ????.

Six primitive conceptual categories provide building blocks which are the set of allowable
dependencies in the concepts in a sentence:

PP
-- Real world objects.
ACT
-- Real world actions.
PA
-- Attributes of objects.
AA
-- Attributes of actions.
T
-- Times.
LOC
-- Locations.

• Arrows indicate the direction of dependency. Letters above indicate certain


relationships:

o
-- object.
R
-- recipient-donor.
I
-- instrument e.g. eat with a spoon.
D
-- destination e.g. going home.

• Double arrows ( ) indicate two-way links between the actor (PP) and action
(ACT).
• The actions are built from the set of primitive acts (see above).
o These can be modified by tense etc.

The use of tense and mood in describing events is extremely important and
schank introduced the following modifiers:
Artificial Intelligence (3170716) 210170107518
p
-- past
f
-- future
t
-- transition

-- start transition

-- finished transition
k
-- continuing
?
-- interrogative
/
-- negative
delta
-- timeless
c
-- conditional
the absence of any modifier implies the present tense.

Advantages of CD:

• Using these primitives involves fewer inference rules.


• Many inference rules are already represented in CD structure.
• The holes in the initial structure help to focus on the points still to be established.

Disadvantages of CD:

• Knowledge must be decomposed into fairly low level primitives.


• Impossible or difficult to find correct set of primitives.
• A lot of inference may still be required.
• Representations can be complex even for relatively simple actions.

Safety and necessary Precautions:

• Primitive actions are the basic actions that can be performed or described without reference
to other actions or concepts

Procedure:

1. Identify the main concepts and their relationships.


2. Use Proper Primitives to draw Conceptual Diagrams.
Artificial Intelligence (3170716) 210170107518
Observation/Program:

John gives marry a book

John gives marry a book yesterday

Conclusion:

In analyzing the two sentences, it's evident that Conceptual Dependency (CD) offers a structured
and formal method for representing the meaning of natural language statements. In the first
sentence, "John gives Mary a book," the CD model efficiently captures the key components of the
action: the agent, John; the action, give; and the object, a book, which has both recipient, Mary, and
thematic elements. In the second sentence, "John gave Mary the book yesterday," CD extends its
utility by incorporating temporal information, making it possible to represent events in the context
of time. CD proves to be a valuable tool for breaking down and visualizing the intricate relationships
and dependencies within sentences, enhancing our understanding of the underlying semantics and
facilitating natural language processing tasks.

Quiz:

1. What is the purpose of a Conceptual Dependency diagram?


 The purpose of a Conceptual Dependency diagram is to represent the meaning of a sentence
or statement in a structured way, showing the semantic relationships between concepts and
actions.

2. How can Conceptual Dependency be used in natural language processing?


 Conceptual Dependency can be used in natural language processing to understand and
analyze the meaning of sentences, enabling the development of more sophisticated
language understanding and generation systems.

3. Can a Conceptual Dependency primitive be further decomposed?


 Yes, Conceptual Dependency primitives can be further decomposed into more detailed
Artificial Intelligence (3170716) 210170107518
conceptual elements, allowing for a more granular representation of meaning.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students:

1. https://people.cs.pitt.edu/~wiebe/courses/CS3730/Spring2013/cd.pdf
2. https://users.cs.cf.ac.uk/Dave.Marshall/AI2/node69.html

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 6

Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.

Date:

Competency and Practical Skills:


Basic knowledge of Python programming language, Familiarity with the rules of tic-tac-toe game,
including the board layout and winning conditions.
Understanding of the Minimax algorithm, which is a decision-making algorithm.

Relevant CO: CO3

Objectives: To illustrate how to recursively apply the Minimax algorithm to build a game tree
and determine the optimal move for the computer player.

Equipment/Instruments: Personal Computer, Python3, Jupytor Notebook

Theory:
• The Minimax Algorithm is a popular decision-making algorithm used in game
theory, which allows a player to determine the best possible move to make, given
that the opponent will also make the best possible move.
• Here's a general implementation of the Minimax algorithm:
• Define the game state: The game state should be defined in terms of the current
state of the board or game, including the position of all pieces, scores, and any other
relevant information.
• Define the game tree: The game tree represents all the possible moves that can be
made from the current game state, and the resulting game states that will arise from
each move. The game tree can be constructed recursively, with the root node
representing the current game state, and the child nodes representing the possible
moves that can be made from that state.
• Assign scores to each game state: At the bottom of the game tree, assign a score to
each game state based on the outcome of the game from that state. For example, if
the game is won by the player who reached that state, assign a positive score, and
if the game is lost, assign a negative score.
• Determine the best move: Starting from the root node, alternate between selecting
the move that maximizes the score for the player and selecting the move that
minimizes the score for the opponent until you reach a leaf node. The score of that
leaf node will then be propagated back up the tree to the root node, and the best
move will be the one that leads to the highest score.

Safety and necessary Precautions:

Handle edge cases such as invalid moves, repeated moves, and game-ending conditions to avoid
program crashes or incorrect results.

Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
Artificial Intelligence (3170716) 210170107518
3. Create a function to get the best move for the current player.

Observation/Program:

PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '

def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)

def is_winner(board, player):


for i in range(3):
if all(board[i][j] == player for j in range(3)) or \
all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or \
all(board[i][2 - i] == player for i in range(3)):
return True
return False

def is_draw(board):
return all(board[i][j] != EMPTY for i in range(3) for j in range(3))

def available_moves(board):
return [(i, j) for i in range(3) for j in range(3) if board[i][j] == EMPTY]

def minimax(board, depth, is_maximizing):


if is_winner(board, PLAYER_X):
return 1
if is_winner(board, PLAYER_O):
return -1
if is_draw(board):
return 0

if is_maximizing:
max_eval = -float('inf')
for move in available_moves(board):
i, j = move
board[i][j] = PLAYER_X
eval = minimax(board, depth + 1, False)
board[i][j] = EMPTY
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float('inf')
Artificial Intelligence (3170716) 210170107518
for move in available_moves(board):
i, j = move
board[i][j] = PLAYER_O
eval = minimax(board, depth + 1, True)
board[i][j] = EMPTY
min_eval = min(min_eval, eval)
return min_eval

def find_best_move(board):
best_eval = -float('inf')
best_move = None

for move in available_moves(board):


i, j = move
board[i][j] = PLAYER_X
eval = minimax(board, 0, False)
board[i][j] = EMPTY
if eval > best_eval:
best_eval = eval
best_move = move

return best_move

if __name__ == "__main__":
board = [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]

print("Welcome to Tic-Tac-Toe!")
print_board(board)

while True:
player_move = input("Enter your move (row and column, e.g., '0 0'): ").split()
i, j = int(player_move[0]), int(player_move[1])

if board[i][j] != EMPTY:
print("Invalid move. Try again.")
continue

board[i][j] = PLAYER_O
print_board(board)

if is_winner(board, PLAYER_O):
print("You win! Congratulations!")
break

if is_draw(board):
print("It's a draw!")
break

computer_move = find_best_move(board)
Artificial Intelligence (3170716) 210170107518
i, j = computer_move
board[i][j] = PLAYER_X
print("Computer's move:")
print_board(board)

if is_winner(board, PLAYER_X):
print("Computer wins!")
break

if is_draw(board):
print("It's a draw!")
break

Conclusion:
Artificial Intelligence (3170716) 210170107518

The Minimax algorithm is a fundamental technique for decision-making in two-player games like
tic-tac-toe. The code provided effectively implements the Minimax algorithm, constructing a game
tree and evaluating game states with an evaluation function. It handles edge cases and ensures that
the game proceeds smoothly. This algorithm, when applied to a game, allows the AI player to make
optimal moves by considering all possible future outcomes, making it a powerful tool for game AI
development.

Quiz:

1. How can you optimize the Minimax algorithm to improve its performance in Tic Tac
Toe?
 To optimize the Minimax algorithm in Tic Tac Toe, you can use alpha-beta pruning to
reduce the number of evaluated game states and improve performance.

2. Can the Minimax algorithm be used for games other than Tic Tac Toe? If so, what are
some examples?
 Yes, the Minimax algorithm can be used for a wide range of two-player, deterministic
games, including chess, checkers, and Connect Four, not just Tic Tac Toe.
Artificial Intelligence (3170716) 210170107518
Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students:

1. https://www.shiksha.com/online-courses/articles/tic-tac-game-python/
2. https://www.shiksha.com/online-courses/articles/tic-tac-game-python/
3. https://geekflare.com/tic-tac-toe-python-code/

Rubric wise marks obtained:

Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 7

Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.

Date:

Competency and Practical Skills: Understanding of Bayesian Networks.


Familiarity with the Monty Hall problem, which is a classic probability puzzle that involves three
doors and a prize.
Knowledge of probability theory, including conditional probability and Bayes' theorem.
Familiarity with a programming language

Relevant CO: CO4

Objectives: To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.

Equipment/Instruments: Personal Computer, Programming Language

Theory:
Bayesian Networks is a probabilistic graphical model used for representing and reasoning about
uncertain knowledge. It consists of a directed acyclic graph (DAG) where nodes represent random
variables and edges represent dependencies between them. Each node has a conditional probability
distribution (CPD) that describes the probability of that node given its parents. Bayesian Networks
can be used for a wide range of tasks including prediction, classification, diagnosis, and decision-
making.
The algorithm for constructing a Bayesian Network involves the following steps:
• Identify the random variables: The first step is to identify the random variables that are
relevant to the problem. These variables can be discrete or continuous, and can represent
events, states, or properties.
• Define the dependencies: The next step is to define the dependencies between the variables.
This is done by specifying the causal relationships between the variables, and determining
which variables are parents and which are children.
• Assign probabilities: The next step is to assign probabilities to the variables. This involves
specifying the prior probabilities for each variable, as well as the conditional probabilities
for each node given its parents.
• Construct the graph: The final step is to construct the DAG by connecting the nodes
according to their dependencies, and specifying the CPDs for each node.

The Monty Hall problem

It is a famous probability puzzle based on a game show scenario. The problem is named after Monty
Hall, the host of the game show "Let's Make a Deal".
The scenario goes as follows:
• There are three doors, behind one of which is a prize, and behind the other two are goats.
The player chooses one door, and then the host, who knows what is behind each door, opens
one of the other two doors to reveal a goat. The player is then given the option to switch
their choice to the other unopened door or stick with their original choice.
• The question is: should the player switch their choice, or stick with their original choice?
• The answer is that the player should always switch their choice.
• To understand why this is the case, consider the following:
• When the player initially chooses a door, there is a 1/3 chance that they have chosen the
door with the prize, and a 2/3 chance that they have chosen a door with a goat. When the
Artificial Intelligence (3170716) 210170107518
host then opens one of the other doors to reveal a goat, the probability that the player's initial
choice was correct remains at 1/3. However, the probability that the prize is behind the other
unopened door is now 2/3.
• Therefore, when given the option to switch, the player should always switch because the
probability of winning the prize increases from 1/3 to 2/3. This may seem counterintuitive,
as it goes against our initial intuition that the probability of winning should be equally
distributed among the three doors. However, this is a classic example of how probabilities
can be counterintuitive, and why it is important to understand the underlying mathematics.

• Safety and necessary Precautions:

Ensure that the algorithm produces accurate results, it is important to validate the input data
to ensure that it is consistent and complete.

Procedure:

1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.

Observation/Program:

from IPython.display import Image


Image("./examples_Monty_Hall_Problem_3_0.png")

from pgmpy.models import BayesianNetwork


from pgmpy.factors.discrete import TabularCPD

# Defining the network structure


model = BayesianNetwork([("C", "H"), ("P", "H")])

# Defining the CPDs:


cpd_c = TabularCPD("C", 3, [[0.33], [0.33], [0.33]])
cpd_p = TabularCPD("P", 3, [[0.33], [0.33], [0.33]])
cpd_h = TabularCPD(
"H",
3,
[
[0, 0, 0, 0, 0.5, 1, 0, 1, 0.5],
[0.5, 0, 1, 0, 0, 0, 1, 0, 0.5],
[0.5, 1, 0, 1, 0.5, 0, 0, 0, 0],
],
evidence=["C", "P"],
evidence_card=[3, 3],
)

model.add_cpds(cpd_c, cpd_p, cpd_h)


model.check_model()
from pgmpy.inference import VariableElimination
infer = VariableElimination(model)
posterior_p = infer.query(["P"], evidence={"C": 0, "H": 2})
print(posterior_p)
Artificial Intelligence (3170716) 210170107518

Conclusion:

Here , we have used an pgmpy module for implementation of Bayesian network with probabilistic
distribution the module contains all the work necessary to implement monty hall problem .

The work was as below . first of all we define the Options for contestant and their probabllity
distribution contestent{1,2,3} Prizes {1,2,3} Host {1,2,3} .

After that train the model and then query it based on the options chosen by contestant and host .
And then model return the output probability for each option and based on that we have to decide
either contastent has to switch or not .
Artificial Intelligence (3170716) 210170107518

We have query it by saying that contestant has chosen door 0 and host has chosen door 2 but the
probability distribution says that door 1 has high probability of the desire prize so contestant has to
Switch the door and accept the offer.

Quiz:

1. What is inference in a Bayesian Network?


 Inference in a Bayesian Network refers to the process of making probabilistic predictions or
answering questions about uncertain variables based on available evidence and the
network's structure and probability distributions.

2. What are some applications of Bayesian Networks?


 Some applications of Bayesian Networks include medical diagnosis, fraud detection,
natural language processing, image recognition, and risk assessment in various fields such
as finance and engineering.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students:

1. https://ipython.readthedocs.io/en/stable/install/kernel_install.html
2. https://en.wikipedia.org/wiki/Monty_Hall_problem

Rubric wise marks obtained:


Problem Logic Completeness
Knowledge
Recognition Building and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 8

Demonstrate Connectionist Model using Tool.

Date:

Competency and Practical Skills:

Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.

Relevant CO: CO4

Objectives:Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.

Equipment/Instruments: Personal Computer, Connectionist Models Tool

Theory:

Connectionist Models

• In contrast to the symbolist architectures in which the mind is assumed to be a physical


symbol-processing system, connectionist systems are networks of large numbers of
interconnected “units.” Each unit can have associated with it a certain amount of
activation. Connections to other units are given explicit weights (including negative
weights).
• Activation spreads from one unit to another as a function of the weighted links. For
example, the function of a typical link might be to multiply the input activation by its
weight and then apply a threshold function. A typical unit would sum all of its input
activations, then divide this among all its links. The weights on the links are adjustable
with experience.
• Some of the links may represent sensory inputs from the outside world; some may
represent output to effectors to the outside world. Units in connectionist models are
usually taken to be below the level of a symbol. For example, different units may
represent visual features of a letter such as verticalness or roundedness.

Neural networks are by far the most commonly used connectionist model today.

• Though there are a large variety of neural network models, they almost always follow two
basic principles regarding the mind:
• Any mental state can be described as an (N)-dimensional vector of numeric activation values
over neural units in a network.
• Memory is created by modifying the strength of the connections between neural units. The
connection strengths, or "weights", are generally represented as an N×N matrix.
Artificial Intelligence (3170716) 210170107518

Some Examples of popular tools:

• TensorFlow: An open-source platform developed by Google for building and training


machine learning models, including neural networks. It provides a high-level API that
makes it easy to build complex models with multiple layers and customizable activation
functions.
• PyTorch: An open-source machine learning library developed by Facebook that provides a
dynamic computational graph for building neural networks. It is highly optimized for GPU
acceleration and provides a Pythonic interface for building and training models.
• Keras: A high-level neural networks API developed in Python that can run on top of
TensorFlow, CNTK, or Theano. It provides a simple and intuitive interface for designing
and training neural networks, and supports both convolutional and recurrent networks.
• Caffe: A deep learning framework developed by Berkeley AI Research (BAIR) that is
optimized for speed and memory efficiency. It provides a C++ API for building and training
neural networks and supports a variety of pre-trained models for image recognition and other
tasks.
• FastAI: A Python library that provides tools for building and training deep learning models,
including neural networks, with a focus on ease of use and fast prototyping.

Safety and necessary Precautions:

Different tools are designed for different tasks, and it's crucial to use a tool that is
appropriate for the task at hand.

Procedure:

• Choose a connectionist modeling tool


• Define the problem
• Design the architecture of the
• Implement the model
• Test the model
• Deploy the model

Observation/Program:

from sklearn import tree,datasets


from sklearn.model_selection import train_test_split
Artificial Intelligence (3170716) 210170107518
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd

Load The Data


data = pd.read_csv('./CHESS_DATA.csv')

alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']


x_columns = list()
for i in range(1, 9):
for j in range(1, 9):
x_columns.append(f'{alphabet[j-1]}{i}')

Preprocessing
from sklearn.preprocessing import LabelEncoder
input_encoder = LabelEncoder()
output_encoder = LabelEncoder()
for col in x_columns:
data[col] = output_encoder.fit_transform(data[col])
X = data[x_columns]

Set Y as an output class


Y = np.array(data['MOVE_FROM'])
Y = output_encoder.fit_transform(y)

Model training using Decision Tree Classifier


model=tree.DecisionTreeClassifier(max_depth=30,min_samples_split=3)
(x_train,x_test,y_train,y_test)=train_test_split(X,Y,test_size=0.3)
model=model.fit(x_train,y_train)

Predicting the output


y_predicted=model.predict(x_test)

Counting score
score = accuracy_score(y_test, y_predicted)

Visualizing using Confusion matri


Artificial Intelligence (3170716) 210170107518
import matplotlib.pyplot as plt
import seaborn as sns
cf_matrix = confusion_matrix(y_test, y_predicted)
sns.heatmap(cf_matrix)
plt.show()

Model training using neural network


from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, BatchNormalization
model = Sequential()
model.add(Dense(64, input_shape=(64,), activation='relu'))
model.add(BatchNormalization())
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(64, activation='softmax'))

Compile the neural network


model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

Fit the neural network


history = model.fit(x_train, y_train, epochs = 10, validation_data=(x_test,y_test))

in neural network we have 6 layers first layer take all the input features and last layer predict the all
the output fratures all the middle layers have 256 nodes with relu activation method . and last layer
was producing the output that’s why it has softmax activation function .

Observations:
Input Data to feed into the model 64 features
Artificial Intelligence (3170716) 210170107518

Output Classes

Accuracy Score of Decision Tree Classifier

Visualization using Confusion matrix

Accuracy Score of dense neural network


Artificial Intelligence (3170716) 210170107518

Conclusion:

So I have created an small data science project here . I have downloaded an dataset called chess
best move predictor on kaggle which is already cleaned so our work will be easy today.

I feed the data into the neural network with following properties .
Neural network has 1 input layer , 4 hidden layers and 1 output layers .

Input layer has 64 input features while all the hidden layers has 256 internal nodes .
Input layer and all hidden layer uses relu activation while output layer used softmax activation.

I have also added some visuals to compare the efficiency of the predicted output and actual output.
Loss function is sparse_categorical_crossentropy and optimizer is adam .

Quiz:

1. What is the role of the activation function in a connectionist model?


 The activation function in a connectionist model introduces non-linearity and helps the model
learn complex patterns by determining the output of a neuron or unit based on its input.

2. What is the purpose of testing a connectionist model?


 The activation function in a connectionist model introduces non-linearity and helps the model
learn complex patterns by determining the output of a neuron or unit based on its input.

3. What is back propagation in a connectionist model?


 Back propagation in a connectionist model is an algorithm used to adjust the model's weights
and biases by propagating errors backward through the network. It's a key part of training
neural networks to minimize prediction errors.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students:

1. https://aws.amazon.com/what-is/neural-
network/#:~:text=A%20neural%20network%20is%20a,that%20resembles%20the%20hum
an%20brain.
2. https://www.ibm.com/topics/neural-networks
Artificial Intelligence (3170716) 210170107518
Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 9

Implement Genetic Algorithm in any Programming Language.

Date:

Competency and Practical Skills:

Understanding of genetic algorithms, which are a class of optimization algorithms that are
inspired by the principles of natural selection and genetics.
Knowledge of a programming language

Relevant CO: CO4

Objectives: To use a computational approach that mimics the process of natural selection to solve
optimization problems

Equipment/Instruments: Programming language

Theory:

Genetic Algorithm (GA) is a popular meta heuristic optimization algorithm in the field of artificial
intelligence (AI).Genetic Algorithms are based on the theory of natural selection and work on
generating a set of random solutions and making them compete in an arena where only the fittest
survive. It is often used to solve complex optimization problems where other traditional methods
may not work well.

GA works by maintaining a population of candidate solutions (also called chromosomes) and


applies genetic operators such as selection, crossover, and mutation to create new and hopefully
better solutions. The basic idea is to mimic the natural process of evolution and survival of the fittest
in order to find the optimal solution to a problem.

The first step in using GA for an AI problem is to define the problem as an optimization problem.
This involves identifying the objective function that needs to be optimized and the constraints (if
any) that need to be satisfied.

Once the problem is defined, the next step is to create an initial population of candidate solutions.
The population is typically generated randomly or using some heuristics depending on the problem.

The fitness function is then defined, which evaluates each chromosome in the population based on
how well it satisfies the objective function and constraints.

Next, the GA applies selection, crossover, and mutation operators to create new and hopefully better
solutions. Selection involves choosing the top-performing chromosomes to be carried over to the
next generation. Crossover involves combining two chromosomes to create new offspring. Mutation
involves randomly changing some genes in a chromosome to introduce diversity into the
population.

The GA then repeats the process of selection, crossover, and mutation for a number of generations
or until a stopping criterion is met (such as reaching a maximum number of generations or finding
an optimal solution).
Artificial Intelligence (3170716) 210170107518
Safety and necessary Precautions:

It is important to define clear objectives and constraints for the optimization problem.
It is crucial to validate the fitness function.

Procedure:

1. Define the problem


2. Define the representation
3. Initialize the population.
4. Evaluate the fitness
5. Select parents.
6. Create offspring: Use genetic operators such as crossover and mutation to create offspring
from the selected parents.
7. Evaluate the offspring.
8. Select survivor
9. Check stopping criteria

Observation/Program:

Code:
import random

def proportional_selection(population, fitness_scores, num_parents):


parents = []
total_fitness = sum(fitness_scores)

for _ in range(num_parents):
spin = random.uniform(0, total_fitness)
cumulative_fitness = 0

for i, individual in enumerate(population):


cumulative_fitness += fitness_scores[i]
if cumulative_fitness >= spin:
parents.append(individual)
break

return parents

def one_point_crossover(parent1, parent2):


crossover_point = random.randint(1, len(parent1) - 1)
offspring = parent1[:crossover_point] + parent2[crossover_point:]

return offspring

def mutate(individual, mutation_rate):


mutated_individual = list(individual)

for i in range(len(mutated_individual)):
if random.random() < mutation_rate:
mutated_individual[i] = '0' if individual[i] == '1' else '1'

return ''.join(mutated_individual)
Artificial Intelligence (3170716) 210170107518
if __name__ == "__main__":
target_string = input("Enter the target string: ")
population = ["".join(random.choice("01") for _ in range(len(target_string))) for _ in range(3)]
mutation_rate = 0.1

while True:
e = input("Options: [S]election, [C]rossover, [M]utation, [E]xit: ")

if e == "s" or e == "S":
fitness_scores = [sum(1 for a, b in zip(target_string, individual) if a == b) for individual in
population]
num_parents = 2
selected_parents = proportional_selection(population, fitness_scores, num_parents)

print("Selected Parents:")
for parent in selected_parents:
print(parent)
elif e == "c" or e == "C":
if len(population) < 2:
print("Need at least 2 individuals in the population for crossover.")
continue
parent1, parent2 = random.sample(population, 2)
offspring = one_point_crossover(parent1, parent2)

print("Offspring:", offspring)
population.append(offspring)
elif e == "m" or e == "M":
mutated_population = [mutate(individual, mutation_rate) for individual in population]
print("Mutated Population:")
for mutated_individual in mutated_population:
print(mutated_individual)
population.append(mutated_individual)
elif e == "e" or e == "E":
break

Conclusion:
Artificial Intelligence (3170716) 210170107518
In conclusion, the provided code offers a foundational understanding of how GAs work, but
practical implementations should consider the problem's specific requirements and necessitate
careful design and validation of the fitness function and other algorithm parameters to achieve
meaningful results in various AI and optimization domains.

Quiz:

1. What are the genetic operators that will be used to create new individuals in each
generation? Will you use crossover, mutation, or both?
 Genetic operators typically include both crossover (recombining genetic material from two
parents) and mutation (introducing small random changes). Both are commonly used in
genetic algorithms.

2. How will you evaluate the fitness of each individual in the population? Will you evaluate
them sequentially or in parallel?
 The fitness of each individual is evaluated based on a predefined fitness function. Evaluation
can be done sequentially or in parallel, depending on available resources.

3. What is the stopping criterion for the genetic algorithm? Will you stop when a certain
fitness level is reached, after a certain number of generations, or when the algorithm
converges?
 The stopping criterion for a genetic algorithm can vary. It could be based on reaching a
certain fitness level, a fixed number of generations, or when convergence criteria are met,
depending on the specific problem and goals.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students:

1. https://www.geeksforgeeks.org/genetic-algorithms/
2. https://www.javatpoint.com/genetic-algorithm-in-machine-learning

Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 10

Write a PROLOG program based on List Operations.

• To find the length of a list.


• To sum all numbers of list.
• To find whether given element is a member of a list.
• To append the list.
• To reverse the list.
• To find the last element of a list.
• To delete the first occurrence of an element from a list.
• To delete every occurrence of an element from a list.
• To find nth element from the list.

Date:

Competency and Practical Skills:

Knowledge of basic PROLOG syntax

Relevant CO: CO5

Objectives: Understand the basic data structure for lists


Learn basic list operations

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

Theory:

The list is a simple data structure that is widely used in non-numeric programming. List consists of
any number of items, for example, red, green, blue, white, dark. It will be represented as, [red,
green, blue, white, dark]. The list of elements will be enclosed with square brackets.

A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom,
[]. In the second case, the list consists of two things as given below –

The first item, called the head of the list;

The remaining part of the list, called the tail.

Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green,
blue, white, dark]. So the tail is another list.

Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the
list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.

So the following list representations are also valid −


[a, b, c] = [x | [b, c] ]
[a, b, c] = [a, b | [c] ]
[a, b, c] = [a, b, c | [ ] ]
For these properties we can define the list as –
Artificial Intelligence (3170716) 210170107518
A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has
to be a list.

Basic Operations on Lists

Following table contains various operations on prolog lists –

Operations Definition

Membership During this operation, we can verify whether a given element is member of
Checking specified list or not?

Length Calculation With this operation, we can find the length of a list.

Concatenation Concatenation is an operation which is used to join/add two lists.

Delete Items This operation removes the specified element from a list.

Append Items Append operation adds one list into another (as an item).

Insert Items This operation inserts a given item into a list.

Safety and necessary Precautions:

The program should handle exceptions, such as input errors or invalid operations.

Procedure:

1. Define the Structure of List in Prolog.


2. Perform Different List operations.

Observation/Program:

Find the length


list_length([],0).
list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1.

list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
Artificial Intelligence (3170716) 210170107518

list_cancat([],L,L).
list_concat([X1|L1],L2,[X1|L3]):- list_concat(L1,L2,L3).

list_delete(X, [X], []).


list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).

list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).

list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).

list_delete(X, [X], []).


list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).

list_insert(X,L,R) :- list_delete(X,R,L).
Artificial Intelligence (3170716) 210170107518

Conclusion:

In this practical we have done the prolog programing in symbolic language and write the prolog
code for various list operations such as searching , appending , inserting and delete .it’s a fun
activity we have done here inspite the logic was not so hard but the preciseness in the logic should
be required in order to achieve the desired output .

Quiz:

1) What is a list in Prolog?


 In Prolog, a list is a data structure that can hold a sequence of elements. Lists are typically
represented using square brackets, and they can be either empty ([]) or contain elements.

2) Write a Prolog predicate "last/2" that returns the last element of a list.
 Here's a Prolog predicate "last/2" that returns the last element of a list:

last(X, [X]).
last(X, [_|T]) :- last(X, T).

This predicate checks if the input list has only one element, in which case that element is the
last. If the list has more than one element, it recursively removes the first element and
continues until it reaches the last element.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/

References used by the students:

1. https://www.javatpoint.com/lists-and-sequence-in-prolog
2. https://www.geeksforgeeks.org/lists-in-prolog/
3. https://www.tutorialspoint.com/prolog/prolog_lists.htm
Artificial Intelligence (3170716) 210170107518
Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

You might also like