aiml program 1-9
aiml program 1-9
class Graph:
def __init__(self):
self.graph = {}
Add edges to the graph
def add_edge(self, u, v):
if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)
Recursive function to perform DFS
def dfs(self, node, visited):
visited.add(node)
print(node, end=' ')
Recur for all adjacent nodes
for neighbor in self.graph[node]:
if neighbor not in visited:
self.dfs(neighbor, visited)
if __name__ == '__main__':
# Create a sample graph
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
# Perform DFS starting from node 2
visited = set()
print("Depth First Traversal (starting from node 2):")
g.dfs(2, visited)
Program:
class Graph:
def __init__(self, graph_dict={}):
self.graph_dict = graph_dict
def add_edge(self, vertex, edge):
if vertex not in self.graph_dict:
self.graph_dict[vertex] = [edge]
else:
self.graph_dict[vertex].append(edge)
def bfs(self, start_vertex):
visited = set() # Initialize a set to keep track of visited nodes
queue = [start_vertex] # Initialize a queue with the starting vertex
while queue:
vertex = queue.pop(0) # Dequeue a vertex from the queue
if vertex not in visited:
visited.add(vertex)
print(vertex)
for neighbor in self.graph_dict.get(vertex, []):
if neighbor not in visited:
queue.append(neighbor)
graph = Graph({
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
})
graph.bfs('A')
Program:
def depth_limited_search(node, goal_node, depth_limit):
visited = set()
stack = [(node, 0)]
while stack:
curr_node, depth = stack.pop()
visited.add(curr_node)
if curr_node == goal_node:
return curr_node
if depth >= depth_limit:
continue
for child in curr_node.children:
if child not in visited:
stack.append((child, depth+1))
return "failure"
class Node:
def __init__(self, value):
self.value = value
self.children = []
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n1.children = [n2, n3]
n2.children = [n4, n5]
goal_node = n5
result = depth_limited_search(n1, goal_node, 2)
if result == "failure":
print("Goal node not found within depth limit.")
else:
print("Goal node found!")
print(result.value)
Program:
import heapq
# Example graph with nodes and edges
graph = {
(0, 0): {(0, 1): 1, (1, 0): 1},
(0, 1): {(0, 0): 1, (0, 2): 1},
(0, 2): {(0, 1): 1, (1, 2): 1},
(1, 0): {(0, 0): 1, (2, 0): 1},
(1, 2): {(0, 2): 1, (2, 2): 1},
(2, 0): {(1, 0): 1, (2, 1): 1},
(2, 1): {(2, 0): 1, (2, 2): 1},
(2, 2): {(1, 2): 1, (2, 1): 1}
}
# Heuristic function (Euclidean distance)
def heuristic(node, goal):
x1, y1 = node
x2, y2 = goal
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# Cost function (distance between nodes)
def distance(node1, node2):
x1, y1 = node1
x2, y2 = node2
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# Neighbors function (returns adjacent nodes)
def neighbors(node):
return list(graph[node].keys())
# A* algorithm
def astar(start, goal):
open_list = [(heuristic(start, goal), start)]
closed_list = set()
g_scores = {start: 0}
parent_nodes = {start: None}
while open_list:
_, curr = heapq.heappop(open_list)
if curr == goal:
path = []
while curr:
path.append(curr)
curr = parent_nodes[curr]
return path[::-1]
closed_list.add(curr)
for neighbor in neighbors(curr):
if neighbor in closed_list:
continue
g_score = g_scores[curr] + distance(curr, neighbor)
if neighbor not in [n[1] for n in open_list]:
parent_nodes[neighbor] = curr
g_scores[neighbor] = g_score
f_score = g_score + heuristic(neighbor, goal)
heapq.heappush(open_list, (f_score, neighbor))
else:
for _, node in open_list:
if node == neighbor and g_score < g_scores[neighbor]:
parent_nodes[neighbor] = curr
g_scores[neighbor] = g_score
f_score = g_score + heuristic(neighbor, goal)
open_list.remove((heuristic(node, goal) + g_scores[node], node))
heapq.heappush(open_list, (f_score, neighbor))
return None
# Example usage
start = (0, 0)
goal = (2, 2)
path = astar(start, goal)
print(path)
Program:
def Cost(H, condition, weight = 1):
cost = {}
if 'AND' in condition:
AND_nodes = condition['AND']
Path_A = ' AND '.join(AND_nodes)
PathA = sum(H[node]+weight for node in AND_nodes)
cost[Path_A] = PathA
if 'OR' in condition:
OR_nodes = condition['OR']
Path_B =' OR '.join(OR_nodes)
PathB = min(H[node]+weight for node in OR_nodes)
cost[Path_B] = PathB
return cost
# Update the cost
def update_cost(H, Conditions, weight=1):
Main_nodes = list(Conditions.keys())
Main_nodes.reverse()
least_cost= {}
for key in Main_nodes:
condition = Conditions[key]
print(key,':', Conditions[key],'>>>', Cost(H, condition, weight))
c = Cost(H, condition, weight)
H[key] = min(c.values())
least_cost[key] = Cost(H, condition, weight)
return least_cost
# Print the shortest path
def shortest_path(Start,Updated_cost, H):
Path = Start
#update
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_cost)
# FIND MINIMIMUM PATH KEY
Next = key[Index].split()
# ADD TO PATH FOR OR PATH
if len(Next) == 1:
Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost, H)
# ADD TO PATH FOR AND PATH
else:
Path +='<--('+key[Index]+') '
Start = Next[0]
Path += '[' +shortest_path(Start, Updated_cost, H) + ' + '
Start = Next[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'
return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}
Conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
# weight
weight = 1
# Updated cost
print('Updated Cost :')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))
Program:
def uniform_cost_search(goal, start):
global graph,cost
answer = []
queue = []
for i in range(len(goal)):
answer.append(10**8)
queue.append([0, start])
visited = {}
count = 0
while (len(queue) > 0):
queue = sorted(queue)
p = queue[-1]
del queue[-1]
p[0] *= -1
if (p[1] in goal):
index = goal.index(p[1])
if (answer[index] == 10**8):
count += 1
if (answer[index] > p[0]):
answer[index] = p[0]
del queue[-1]
queue = sorted(queue)
if (count == len(goal)):
return answer
if (p[1] not in visited):
for i in range(len(graph[p[1]])):
queue.append( [(p[0] + cost[(p[1], graph[p[1]][i])])* -1,
graph[p[1]][i]])
visited[p[1]] = 1
return answer
if __name__ == '__main__':
graph,cost = [[] for i in range(8)],{}
graph[0].append(1)
graph[0].append(3)
graph[3].append(1)
graph[3].append(6)
graph[3].append(4)
graph[1].append(6)
graph[4].append(2)
graph[4].append(5)
graph[2].append(1)
graph[5].append(2)
graph[5].append(6)
graph[6].append(4)
cost[(0, 1)] = 2
cost[(0, 3)] = 5
cost[(1, 6)] = 1
cost[(3, 1)] = 5
cost[(3, 6)] = 6
cost[(3, 4)] = 2
cost[(2, 1)] = 4
cost[(4, 2)] = 4
cost[(4, 5)] = 3
cost[(5, 2)] = 6
cost[(5, 6)] = 3
cost[(6, 4)] = 7
goal = []
goal.append(6)
answer = uniform_cost_search(goal, 0)
print("Minimum cost from 0 to 6 is = ",answer[0])
Program:
class AdjacentNode:
def __init__(self,vertex):
self.vertex = vertex
self.next = None
class BidirectionalSearch:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [None] * self.vertices
self.src_queue = list()
self.dest_queue = list()
self.src_visited = [False] * self.vertices
self.dest_visited = [False] * self.vertices
self.src_parent = [None] * self.vertices
self.dest_parent = [None] * self.vertices
def add_edge(self, src, dest):
node = AdjacentNode(dest)
node.next = self.graph[src]
self.graph[src] = node
node = AdjacentNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def bfs(self, direction = 'forward'):
if direction == 'forward':
current = self.src_queue.pop(0)
connected_node = self.graph[current]
while connected_node:
vertex = connected_node.vertex
if not self.src_visited[vertex]:
self.src_queue.append(vertex)
self.src_visited[vertex] = True
self.src_parent[vertex] = current
connected_node = connected_node.next
else:
current = self.dest_queue.pop(0)
connected_node = self.graph[current]
while connected_node:
vertex = connected_node.vertex
if not self.dest_visited[vertex]:
self.dest_queue.append(vertex)
self.dest_visited[vertex] = True
self.dest_parent[vertex] = current
connected_node = connected_node.next
def is_intersecting(self):
for i in range(self.vertices):
if (self.src_visited[i] and
self.dest_visited[i]):
return i
return -1
def print_path(self, intersecting_node,
src, dest):
path = list()
path.append(intersecting_node)
i = intersecting_node
while i != src:
path.append(self.src_parent[i])
i = self.src_parent[i]
path = path[::-1]
i = intersecting_node
while i != dest:
path.append(self.dest_parent[i])
i = self.dest_parent[i]
print("*****Path*****")
path = list(map(str, path))
print(' '.join(path))
def bidirectional_search(self, src, dest):
self.src_queue.append(src)
self.src_visited[src] = True
self.src_parent[src] = -1
self.dest_queue.append(dest)
self.dest_visited[dest] = True
self.dest_parent[dest] = -1
while self.src_queue and self.dest_queue:
self.bfs(direction = 'forward')
self.bfs(direction = 'backward')
intersecting_node = self.is_intersecting()
if intersecting_node != -1:
print(f"Path exists between {src} and {dest}")
print(f"Intersection at : {intersecting_node}")
self.print_path(intersecting_node,
src, dest)
exit(0)
return -1
if __name__ == '__main__':
n = 15
src = 0
dest = 14
graph = BidirectionalSearch(n)
graph.add_edge(0, 4)
graph.add_edge(1, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 5)
graph.add_edge(4, 6)
graph.add_edge(5, 6)
graph.add_edge(6, 7)
graph.add_edge(7, 8)
graph.add_edge(8, 9)
graph.add_edge(8, 10)
graph.add_edge(9, 11)
graph.add_edge(9, 12)
graph.add_edge(10, 13)
graph.add_edge(10, 14)
out = graph.bidirectional_search(src, dest)
if out == -1:
print(f"Path does not exist between {src} and {dest}")
Program:-
#importing the libraries
import numpy as np
import matplotlib.pyplot
import pandas as pd
dataset=pd.read_csv('Data.csv')
X=dataset.iloc[:,:-1].values
Y=dataset.iloc[:,3].values
#taking care of the missing data
from sklearn.impute import SimpleImputer
imputer=SimpleImputer(missing_values=np.nan, strategy='mean')
imputer=imputer.fit(X[:,1:3])#the upperbound is excluded
X[:,1:3]=imputer.transform(X[:,1:3])
print(X)
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(),
[0])],remainder='passthrough')
X=np.array(columnTransformer.fit_transform(X),dtype=np.str)
Program:-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X_train,y_train)
y_pred=regressor.predict(X_test)
plt.scatter(X_train,y_train,color='red')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title('Salary vs Experience (Training Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
plt.scatter(X_test,y_test,color='red')
plt.plot(X_train,regressor.predict(X_train),color='blue')
plt.title('Salary vs Experience (Test Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')