0% found this document useful (0 votes)
12 views22 pages

Ai Document

Uploaded by

SaMPaTH CM 19&[
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views22 pages

Ai Document

Uploaded by

SaMPaTH CM 19&[
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

WEEK-1

AIM: Write a program using python to


A) Generate a Calendar for the given month and year?
DESCRIPTION: This program generates a calendar for a specific month and year provided
by the user. It uses Python's built-in calendar module, which provides useful functions to
work with dates and calendars. The program creates a text-based calendar and displays it in a
formatted manner.
Steps:
1. Input from User: Enter year and month for which they want to generate the
calendar.
2. Calendar Generation: Used for generating the calendar for the specified month and
year.
3. Output: Prints the calendar in a readable format, showing the days of the month
organized in weeks.
PROGRAM:
# Import the 'calendar' module
import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))
OUTPUT:

B) Implement a Simple Calculator program

DESCRIPTION: This program implements a simple calculator that can perform basic
arithmetic operations: addition, subtraction, multiplication, and division. The user selects an
operation and provides two numbers, and the program computes and displays the result.

print("------------------------ + - * / % SIMPLE CALCULATOR + - * / % --------------------


\n1 TO BEGIN\t2 TO CONTINUE\t3 TO EXIT")
result=0
while(True):
Choice=int(input())
if(Choice==1):
A=int(input('Enter Operand 1: '))
B=int(input('Enter Operand 2: '))
op=input('Enter opertor : ')
if(op=='+'):

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


ope=A+B
elif(op=='-'):
ope=A-B
elif(op=='*'):
ope=A*B
elif(op=='/'):
ope+=A/B
elif(op=='%'):
ope=A%B
else:
print("Invalid try again")
print(A,op,B,"=", ope)
result+=ope
elif(Choice==2):
C=int(input("Enter operand: "))
op=input('Enter opertor: ')
if(op=='+'):
oper=result+C
elif(op=='-'):
oper=result-C
elif(op=='*'):
oper=result*C
elif(op=='/'):
oper=result/C
elif(op=='%'):
oper=result%C
else:
print("Invalid try again")
print(result,op,C,"=", oper)
result=oper
else:
print("Final result :",result)
break
OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK-2

AIM: Design of Intelligent systems. (Suggested exercise: to control the VACUUM Cleaner
moves)

DESCRIPTION: This program simulates the behavior of an intelligent vacuum cleaner


agent operating in a two-room environment (Location A and Location B). The vacuum
cleaner can move between the rooms and clean them if they are dirty. The program calculates
the cost of actions (moving and cleaning) and outputs the final state of the rooms along with
the total cost.

1. Initialization The program initializes the goal state where both rooms are clean ({'A':
'0', 'B': '0'}).
2. User Input The initial location of the vacuum cleaner. The status of the current
location (clean or dirty).The status of the other room (clean or dirty).
3. Agent Behavior If the current location is dirty, the vacuum cleans it and incurs a cost.
If the other room is dirty, the vacuum moves to that room, cleans it, and incurs
additional costs for moving and cleaning.
4. Output The initial state of the rooms. The actions taken by the vacuum cleaner.The
final state of the rooms. The total cost of actions (performance measurement).
PROGRAM:
def vacuum_world():
goal_state = {'A': '0', 'B': '0'}
cost = 0
location_input = input("Enter Location of Vacuum (A/B): ").upper() # Location of the vacuum
status_input = input(f"Enter status of {location_input} (0 for CLEAN, 1 for DIRTY): ") # Status of
the current location
status_input_complement = input(f"Enter status of the other room (0 for CLEAN, 1 for DIRTY):
") # Status of the other room

print("\nInitial Location Condition: " + str(goal_state))

if location_input == 'A':
print("\nVacuum is placed in Location A.")
if status_input == '1':
print("Location A is Dirty.")
goal_state['A'] = '0' # Clean Location A
cost += 1 # Cost for cleaning
print(f"Cost for CLEANING A: {cost}")
print("Location A has been Cleaned.")

if status_input_complement == '1':
print("Location B is Dirty.")
print("Moving RIGHT to Location B.")
cost += 1 # Cost for moving right
print(f"COST for moving RIGHT: {cost}")

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


goal_state['B'] = '0' # Clean Location B
cost += 1 # Cost for cleaning
print(f"COST for SUCK: {cost}")
print("Location B has been Cleaned.")
else:
print("No action. Location B is already clean.")

elif status_input == '0':


print("Location A is already clean.")

if status_input_complement == '1':
print("Location B is Dirty.")
print("Moving RIGHT to Location B.")
cost += 1 # Cost for moving right
print(f"COST for moving RIGHT: {cost}")
goal_state['B'] = '0' # Clean Location B
cost += 1 # Cost for cleaning
print(f"COST for SUCK: {cost}")
print("Location B has been Cleaned.")
else:
print("No action. Location B is already clean.")

elif location_input == 'B':


print("\nVacuum is placed in Location B.")

if status_input == '1':
print("Location B is Dirty.")
goal_state['B'] = '0' # Clean Location B
cost += 1 # Cost for cleaning
print(f"COST for CLEANING B: {cost}")
print("Location B has been Cleaned.")

if status_input_complement == '1':
print("Location A is Dirty.")
print("Moving LEFT to Location A.")
cost += 1 # Cost for moving left
print(f"COST for moving LEFT: {cost}")
goal_state['A'] = '0' # Clean Location A
cost += 1 # Cost for cleaning
print(f"COST for SUCK: {cost}")
print("Location A has been Cleaned.")
else:
print("No action. Location A is already clean.")
elif status_input == '0':
print("Location B is already clean.")

if status_input_complement == '1':

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


print("Location A is Dirty.")
print("Moving LEFT to Location A.")
cost += 1 # Cost for moving left
print(f"COST for moving LEFT: {cost}")
goal_state['A'] = '0' # Clean Location A
cost += 1 # Cost for cleaning
print(f"COST for SUCK: {cost}")
print("Location A has been Cleaned.")
else:
print("No action. Location A is already clean.")

else:
print("Invalid location entered. Please enter 'A' or 'B'.")
return

print("\nGOAL STATE: " + str(goal_state))


print("Performance Measurement (Total Cost): " + str(cost))

vacuum_world()

OUTPUT

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK-3

AIM: Implement the production system and derive a solution for the real world Al problem.
(Suggested exercise: Write a program to solve the following problem: You have two jugs, a 4-
gallon and a 3-gallon. Neither of the jugs has markings on them. There is a pump that can be
used to fill the jugs with water. How can you get exactly two gallons of water in the 4-gallon
jug?).

DESCRIPTION:

A production system is a framework used in artificial intelligence to solve problems by


applying a set of rules (productions) to states. For the water jug problem, the production
system consists of:

1. States: Represented by the current amounts of water in the two jugs, e.g., (j1, j2).

2. Initial State: Both jugs are empty, (0, 0).


3. Goal State: One of the jugs contains exactly 2 gallons, e.g., (2, 0) or (2, 3).

4. Rules (Productions): Define the actions that can be performed on the jugs:

o Fill a jug to its maximum capacity.

o Empty a jug completely.

o Pour water from one jug to the other until the source jug is empty or the
destination jug is full.

PROGRAM:

def waterJugProblem(jug1Cap, jug2Cap, targetAmount):


j1, j2 = 0, 0
actions = [("fill", 1), ("fill", 2), ("empty", 1), ("empty", 2), ("pour", 1, 2), ("pour", 2, 1)]
visited = set()
queue = [(j1, j2, [])]

while queue:
j1, j2, seq = queue.pop(0)
if (j1, j2) not in visited:
visited.add((j1, j2))
if j1 == targetAmount or j2 == targetAmount:
return seq
for action in actions:
if action[0] == "fill":
next_state = (jug1Cap, j2) if action[1] == 1 else (j1, jug2Cap)
elif action[0] == "empty":
next_state = (0, j2) if action[1] == 1 else (j1, 0)
else:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


if action[1] == 1:
amount = min(j1, jug2Cap - j2)
next_state = (j1 - amount, j2 + amount)
else:
amount = min(j2, jug1Cap - j1)
next_state = (j1 + amount, j2 - amount)
if next_state not in visited:
next_seq = seq + [action]
queue.append((next_state[0], next_state[1], next_seq))
return None

result = waterJugProblem(4, 3, 2)
print(result)

OUTPUT :

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK-4

AIM: Implement A* algorithm. (Suggested exercise: to find the shortest path).

DESCRIPTION: The A* (A-star) algorithm is a powerful and versatile search method used
in computer science to find the most efficient path between nodes in a graph. Widely used in
a variety of applications ranging from pathfinding in video games to network routing and AI,
A* remains a foundational technique in the field of algorithms and artificial intelligence.

Working of A* Algorithm

The core of the A* algorithm is based on cost functions and heuristics. It uses two main
parameters:

1. g(n): The actual cost from the starting node to any node n.

2. h(n): The heuristic estimated cost from node n to the goal. This is where A* integrates
knowledge beyond the graph to guide the search.

The sum, f(n)=g(n)+h(n)f(n)=g(n)+h(n), represents the total estimated cost of the cheapest
solution through nnn. The A* algorithm functions by maintaining a priority queue (or open
set) of all possible paths along the graph, prioritizing them based on their fff values. The steps
of the algorithm are as follows:
1. Initialization: Start by adding the initial node to the open set with its f(n).

2. Loop: While the open set is not empty, the node with the lowest f(n) value is removed
from the queue.
3. Goal Check: If this node is the goal, the algorithm terminates and returns the
discovered path.
4. Node Expansion: Otherwise, expand the node (find all its neighbors), calculating g,
h, and f values for each neighbor. Add each neighbor to the open set if it's not already
present, or if a better path to this neighbor is found.

5. Repeat: The loop repeats until the goal is reached or if there are no more nodes in the
open set, indicating no available path.

PROGRAM:

from heapq import heappush, heappop

def a_star_search(graph, start, goal, heuristic):


open_list = []
heappush(open_list, (0, start, [start]))
g_cost = {start: 0}

while open_list:
f_cost, current, path = heappop(open_list)

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


if current == goal:
return path, g_cost[current]

for neighbor, weight in graph[current]:


tentative_g_cost = g_cost[current] + weight

if neighbor not in g_cost or tentative_g_cost < g_cost[neighbor]:


g_cost[neighbor] = tentative_g_cost
f_cost = tentative_g_cost + heuristic[neighbor]
heappush(open_list, (f_cost, neighbor, path + [neighbor]))

return None, float("inf")

if __name__ == "__main__":
graph = {
"A": [("B", 1), ("C", 3)],
"B": [("D", 1), ("E", 5)],
"C": [("E", 2)],
"D": [("F", 4)],
"E": [("F", 1)],
"F": [],
}
heuristic = {"A": 6, "B": 4, "C": 4, "D": 2, "E": 1, "F": 0}

start_node = "A"
goal_node = "F"

path, cost = a_star_search(graph, start_node, goal_node, heuristic)

if path:
print(f"Path found: {path} with cost: {cost}")
else:
print("No path found.")

OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK 5

AIM: Implement the Constraint Specific Problem. (Suggested exercise: a crossword puzzle).

DESCRIPTION: A Constraint Satisfaction Problem is a mathematical problem where the


solution must meet a number of constraints. In a CSP, the objective is to assign values to
variables such that all the constraints are satisfied. CSPs are used extensively in artificial
intelligence for decision-making problems where resources must be managed or arranged
within strict guidelines.

Components of Constraint Satisfaction Problems

CSPs are composed of three key elements:

1. Variables: The things that need to be determined are variables. Variables in a CSP are
the objects that must have values assigned to them in order to satisfy a particular set
of constraints. Boolean, integer, and categorical variables are just a few examples of
the various types of variables, for instance, could stand in for the many puzzle cells
that need to be filled with numbers in a sudoku puzzle.

2. Domains: The range of potential values that a variable can have is represented by
domains. Depending on the issue, a domain may be finite or limitless. For instance, in
Sudoku, the set of numbers from 1 to 9 can serve as the domain of a variable
representing a problem cell.

3. Constraints: The guidelines that control how variables relate to one another are
known as constraints. Constraints in a CSP define the ranges of possible values for
variables. Unary constraints, binary constraints, and higher-order constraints are only
a few examples of the various sorts of constraints. For instance, in a sudoku problem,
the restrictions might be that each row, column, and 3×3 box can only have one
instance of each number from 1 to 9.

PROGRAM:

ways = 0

def print_matrix(matrix):
for row in matrix:
print(" ".join(row))
print()

def check_horizontal(x, y, matrix, word):


n = len(word)
for i in range(n):
if matrix[x][y + i] not in ("+", word[i]):
matrix[0] = "@"

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


return matrix
matrix[x] = matrix[x][: y + i] + word[i] + matrix[x][y + i + 1 :]
return matrix

def check_vertical(x, y, matrix, word):


n = len(word)
for i in range(n):
if matrix[x + i][y] not in ("+", word[i]):
matrix[0] = "@"
return matrix
matrix[x + i] = matrix[x + i][:y] + word[i] + matrix[x + i][y + 1 :]
return matrix

def solve_puzzle(words, matrix, index, n):


global ways
if index < len(words):
current_word = words[index]
max_len = n - len(current_word)

for i in range(n):
for j in range(max_len + 1):
temp = check_vertical(j, i, matrix.copy(), current_word)
if temp[0] != "@":
solve_puzzle(words, temp, index + 1, n)

for i in range(n):
for j in range(max_len + 1):
temp = check_horizontal(i, j, matrix.copy(), current_word)
if temp[0] != "@":
solve_puzzle(words, temp, index + 1, n)
else:
print(f"{ways + 1} way to solve the puzzle")
print_matrix(matrix)
print()
ways += 1

if __name__ == "__main__":
n1 = 10
matrix = [
"##########",
"##########",
"######+###",
"#+####++##",

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


"#+####+###",
"#+####+###",
"#+####+###",
"#+#++++++#",
"##########",
"#+++++++##",
]

words = ["VISHAL","MAHESH", "SAMPATH","VARUN"]


ways = 0
solve_puzzle(words, matrix, 0, n1)
print(f"Number of ways to fill the grid is {ways}")

OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK-6

AIM: Implement the alpha-beta pruning. (Suggested exercise: for a tic toc game).

DESCRIPTION: Alpha-Beta pruning is not actually a new algorithm, but rather an


optimization technique for the minimax algorithm. It reduces the computation time by a huge
factor. This allows us to search much faster and even go into deeper levels in the game tree. It
cuts off branches in the game tree which need not be searched because there already exists a
better move available. It is called Alpha-Beta pruning because it passes 2 extra parameters in
the minimax function, namely alpha and beta.

Let’s define the parameters alpha and beta.

Alpha is the best value that the maximizer currently can guarantee at that level or above.
Beta is the best value that the minimizer currently can guarantee at that level or below.
EXAMPLE:

1) Initial Setup:
a) The algorithm starts at node A (the root, a maximizer).
b) Initial values: alpha = -INFINITY (for maximizer), beta = +INFINITY (for
minimizer).
2) Exploring Node B:
a) A calls B (a minimizer).
b) B calls D (a maximizer).
i) D evaluates its left child (leaf node) with value 3.
(1) alpha at D becomes max(-INF, 3) = 3.
(2) Since beta > alpha, D continues to evaluate its right child.
ii) D evaluates its right child (leaf node) with value 5.
(1) alpha at D becomes max(3, 5) = 5.
iii) D returns 5 to B.
c) B updates beta = min(+INF, 5) = 5.
d) B calls E to check for a better (lower) value.
i) E evaluates its left child (leaf node) with value 6.
(1) alpha at E becomes max(-INF, 6) = 6.
(2) Since beta (5) <= alpha (6), E prunes its right subtree and returns 6 to B.
e) B updates beta = min(5, 6) = 5.
f) B returns 5 to A.
3) Exploring Node C:
a) A calls C (a minimizer) to check for a better (higher) value.
b) C calls F (a maximizer).
i) F evaluates its left child (leaf node) with value 1.
(1) alpha at F remains max(5, 1) = 5.
ii) F evaluates its right child (leaf node) with value 2.
(1) alpha at F remains max(5, 2) = 5.

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


F returns 2 to C.
iii)
c) C updates beta = min(+INF, 2) = 2.
d) Since beta (2) <= alpha (5), C prunes its right subtree (G) and returns 2 to A.
4) Final Decision at A:
a) A updates alpha = max(5, 2) = 5.
b) The optimal value for the maximizer (A) is 5.

PROGRAM:

MAX, MIN = 1000, -1000

# Returns optimal value for current player


#(Initially called for root and maximizer)
def minimax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):

# Terminating condition. i.e


# leaf node is reached
if depth == 3:
return values[nodeIndex]

if maximizingPlayer:

best = MIn
# Recur for left and right children
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i, False, values, alpha, beta)


best = max(best, val)
alpha = max(alpha, best)
# Alpha Beta Pruning
if beta <= alpha:
break

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


return best
else:
best = MAX

# Recur for left and


# right children
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)

# Alpha Beta Pruning


if beta <= alpha:
break
return best
# Driver Code
if __name__ == "__main__":

values = [3, 5, 6, 9, 1, 2, 0, -1]


print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK 7

AIM: Design a planning system using STRIPS. (Suggested exercise: an elevator problem to
move a passenger from the 1st floor to the 4th floor in a building).

DESCRIPTION: In AI, planning involves generating a sequence of actions to achieve a


specific goal. One of the most influential approaches to automated planning is the Stanford
Research Institute Problem Solver, commonly known as STRIPS. Developed in the late
1960s at Stanford Research Institute (now SRI International) by Richard Fikes and Nils
Nilsson, STRIPS has laid the groundwork for many of the concepts used in modern AI
planning systems.

STRIPS is a formal language used for expressing planning problems and was originally
designed to control the actions of a robot in a manipulable environment. It is primarily
concerned with the automatic generation of plans, which are sequences of actions that
transition a system from its initial state to a desired goal state.

Key Components of STRIPS:

 States: Defined by a set of logical propositions.

 Goals: Specified as a set of conditions that describe the desired outcome.

 Actions: Each action in STRIPS is characterized by three components:

o Preconditions: Conditions that must be true for the action to be executed.


o Add Effects: Conditions that become true as a result of executing the action.

o Delete Effects: Conditions that become false as a result of executing the


action.

Planning with STRIPS:

1. Define the Initial State: Where the system starts.

2. Set the Goal State: What the system should achieve.

3. Develop Actions: Defined by their preconditions and effects.

4. Search for Solutions: Using a strategy like backward chaining from the goal state to
the initial state, identifying actions that satisfy the goal conditions

PROGRAM:

import random
import time

class Building:
def __init__(self, floors, customers):

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


self.number_of_floors = floors
self.customer_list = []
for customerID in range(1, customers + 1):
new_customer = Customer(customerID, self.number_of_floors)
self.customer_list.append(new_customer)
self.customer_list.sort(key=lambda x: x.current_floor)
self.elevator = Elevator(floors, self.customer_list)
self.run()

def run(self):
print("++++++++++++++++++++++++++ ELEVATOR IS NOW STARTING
+++++++++++++++")
print(f"There are {len(self.customer_list)} customers in the building")
self.output()

def output(self):
for customer in self.customer_list:
print(f"Customer {customer.customerID} is on floor {customer.current_floor} and
wants to go to {customer.destination_floor}")

# Elevator moving up
while self.elevator.current_floor < self.elevator.number_of_floors:
self.elevator.current_floor += 1
print("ELEVATOR MOVING UP")
print(f"{len(self.customer_list)} Customers in lift.")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(f"FLOOR {self.elevator.current_floor}")

for customer in self.customer_list:


if (self.elevator.current_floor == customer.current_floor) and
customer.customer_direction == 1:
customer.in_elevator = True
print(f"Customer {customer.customerID} has entered the lift")
if (self.elevator.current_floor == customer.destination_floor) and
customer.in_elevator and customer.customer_direction == 1:
customer.in_elevator = False
self.customer_list.remove(customer)
print(f"Customer {customer.customerID} has reached their destination")

while self.elevator.current_floor <= self.number_of_floors and


self.elevator.current_floor > 1:
self.elevator.current_floor -= 1
print(f"{len(self.customer_list)} Customers in lift.")

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


print("ELEVATOR MOVING DOWN")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(f"FLOOR {self.elevator.current_floor}")

for customer in self.customer_list:


if customer.in_elevator:
customer.current_floor = self.elevator.current_floor
if (self.elevator.current_floor == customer.destination_floor) and
customer.in_elevator and customer.customer_direction == -1:
customer.in_elevator = False
self.customer_list.remove(customer)
print(f"Customer {customer.customerID} has reached their destination")

print(f"There are {len(self.customer_list)} customers trapped in the elevator")


print(f"There are {len(self.elevator.register_list)} people left on the register")
print("Elevator run is done!!!")

print("CUSTOMERS STUCK IN LIFT ARE BELOW")


for stuck_customer in self.customer_list:
print(f"Cust. ID: {stuck_customer.customerID}, Dest. Floor:
{stuck_customer.destination_floor}, Curr. Floor: {stuck_customer.current_floor}, In
Elevator: {stuck_customer.in_elevator}, Direction:
{stuck_customer.customer_direction}")

class Elevator:
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
self.current_floor = 0

def move(self):
pass
def register_customer(self, customers):
for customer in customers:
self.register_list.append(customer)

def cancel_customer(self, customers):


pass

class Customer:
def __init__(self, customerID, floors):
self.customerID = customerID

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


self.current_floor = random.randint(1, floors)
self.destination_floor = random.randint(1, floors)
while self.destination_floor == self.current_floor:
self.destination_floor = random.randint(1, floors)
self.customer_direction = 1 if self.current_floor < self.destination_floor else -1
self.in_elevator = False
self.finished = False
def main():
try:
floors = int(input("Enter the number of floors: "))
customers = int(input("Enter number of customers: "))
building = Building(floors, customers)
except ValueError:
print("YOU DIDN'T ENTER A NUMBER. START AGAIN.")
main()

if __name__ == "__main__":
main()

OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


WEEK 8

AIM: Implement a single neural network and test for different logic gates.

DESCRIPTION:

Layers in Neural Network Architecture

1. Input Layer: This is where the network receives its input data. Each input neuron in
the layer corresponds to a feature in the input data.

2. Hidden Layers: These layers perform most of the computational heavy lifting. A
neural network can have one or multiple hidden layers. Each layer consists of units
(neurons) that transform the inputs into something that the output layer can use.

3. Output Layer: The final layer produces the output of the model. The format of these
outputs varies depending on the specific task (e.g., classification, regression).

PROGRAM:

import numpy as np
from matplotlib import pyplot as plt

# Sigmoid Function
def sigmoid(z):
return 1 / (1 + np.exp(-z))

# Initialization of the neural network parameters


def initialize_parameters(input_features, neurons_in_hidden_layers, output_features):
W1 = np.random.randn(neurons_in_hidden_layers, input_features)
W2 = np.random.randn(output_features, neurons_in_hidden_layers)
b1 = np.zeros((neurons_in_hidden_layers, 1))
b2 = np.zeros((output_features, 1))
parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2}
return parameters

# Forward Propagation
def forward_propagation(X, Y, parameters):
m = X.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
b1 = parameters["b1"]
b2 = parameters["b2"]

Z1 = np.dot(W1, X) + b1
A1 = sigmoid(Z1)

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)

cache = (Z1, A1, W1, b1, Z2, A2, W2, b2)


logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))
cost = -np.sum(logprobs) / m

return cost, cache, A2

# Backward Propagation
def backward_propagation(X, Y, cache):
m = X.shape[1]
Z1, A1, W1, b1, Z2, A2, W2, b2 = cache

dZ2 = A2 - Y
dW2 = np.dot(dZ2, A1.T) / m
db2 = np.sum(dZ2, axis=1, keepdims=True) / m

dA1 = np.dot(W2.T, dZ2)


dZ1 = np.multiply(dA1, A1 * (1 - A1))
dW1 = np.dot(dZ1, X.T) / m
db1 = np.sum(dZ1, axis=1, keepdims=True) / m

gradients = {"dZ2": dZ2, "dW2": dW2, "db2": db2, "dZ1": dZ1, "dW1": dW1, "db1":
db1}
return gradients

# Updating the weights based on the negative gradients


def update_parameters(parameters, gradients, learning_rate):
parameters["W1"] = parameters["W1"] - learning_rate * gradients["dW1"]
parameters["W2"] = parameters["W2"] - learning_rate * gradients["dW2"]
parameters["b1"] = parameters["b1"] - learning_rate * gradients["db1"]
parameters["b2"] = parameters["b2"] - learning_rate * gradients["db2"]
return parameters

# Model to learn the AND truth table


X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # AND input
Y = np.array([[0, 0, 0, 1]]) # AND output

# Define model parameters


neurons_in_hidden_layers = 2 # Number of hidden layer neurons
input_features = X.shape[0] # Number of input features
output_features = Y.shape[0] # Number of output features

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL


parameters = initialize_parameters(input_features, neurons_in_hidden_layers,
output_features)

epoch = 100000
learning_rate = 0.01
losses = np.zeros((epoch, 1))

# Training the model


for i in range(epoch):
losses[i, 0], cache, A2 = forward_propagation(X, Y, parameters)
gradients = backward_propagation(X, Y, cache)
parameters = update_parameters(parameters, gradients, learning_rate)

# Plotting the loss


plt.figure()
plt.plot(losses)
plt.xlabel("EPOCHS")
plt.ylabel("Loss value")
plt.show()

# Testing the model


X_test = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # Test input
cost, _, A2 = forward_propagation(X_test, Y, parameters)
prediction = (A2 > 0.5) * 1.0
print("Predictions:", prediction)

OUTPUT:

323103383L02 CSD-DATA SCIENCE K. SAMPATH VISHAL

You might also like