Code

Shivam Dubey
0
##practical-1 bfs(non ai persepective) graph = { '5': ['3', '7'], '3': ['2'], '7': ['8'], '2': [], '8': [] } visited = [] queue = [] def bfs(visited, graph, node): visited.append(node) queue.append(node) while queue: m = queue.pop(0) print(m, end="-->") for neighbour in graph[m]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) bfs(visited, graph, '5') ## practical 2 bfs with romanian from queue import Queue from RMP import dict_gn def bfs(start, goal): visited = set([start]) parent = {start: None} q = Queue() q.put(start) while not q.empty(): current = q.get() if current == goal: path = [] while current: path.append(current) current = parent[current] return path[::-1] for neighbor in dict_gn[current]: if neighbor not in visited: visited.add(neighbor) parent[neighbor] = current q.put(neighbor) return None start_city = "Arad" goal_city = "Bucharest" path = bfs(start_city, goal_city) if path: print("Path found: " + "->".join(path)) else: print(f"Couldn't find the path to: {goal_city}") ## practical 3 IDDFS from RMP import dict_gn start = 'Arad' goal = 'Bucharest' def dls(city, limit, path): path.append(city) if city == goal: return True if limit == 0: path.pop() return False for neighbor in dict_gn[city]: if neighbor not in path: if dls(neighbor, limit - 1, path): return True path.pop() return False def iddfs(start, goal, max_depth): for depth in range(max_depth + 1): print("searching with limit", depth) path = [] if dls(start, depth, path): print("Path found:") print("IDDFS Traversal from", start, "to", goal, "is:") print(" " +" -->" .join(path)) return else: print("Path not found") print("result:", " ".join(path)) print("------") iddfs(start, goal, 9) ## practical 4 A* import queue as q from RMP import dict_gn, dict_hn start = 'Arad' goal = 'Bucharest' result = [] def get_gn(path_list): return sum(dict_gn[path_list[i]][path_list[i + 1]] for i in range(len(path_list) - 1)) def get_fn(path_list): return get_gn(path_list) + dict_hn[path_list[-1]] def expand(city_q): global result if city_q.empty(): return for _, path_list, this_city in list(city_q.queue): if this_city == goal: result = path_list return _, path_list, this_city = city_q.get() for city in dict_gn[this_city]: city_q.put((get_fn(path_list + [city]), path_list + [city], city)) expand(city_q) # Main city_q = q.PriorityQueue() city_q.put((get_fn([start]), [start], start)) expand(city_q) total_cost = get_gn(result) print(f"The A* path with total is : {' -> '.join(result)} :: {total_cost}") ##practical 5 neural network import numpy as np class NeuralNetwork: def __init__(self): np.random.seed(1) self.synaptic_weights = 2 * np.random.random((3, 1)) - 1 def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(self, x): return x * (1 - x) def train(self, training_inputs, training_outputs, training_iterations): for iteration in range(training_iterations): output = self.think(training_inputs) error = training_outputs - output adjustment = np.dot(training_inputs.T, error * self.sigmoid_derivative(output)) self.synaptic_weights += adjustment def think(self, inputs): inputs = inputs.astype(float) output = self.sigmoid(np.dot(inputs, self.synaptic_weights)) return output if __name__ == "__main__": neural_network = NeuralNetwork() print("Random starting synaptic weights:") print(neural_network.synaptic_weights) training_inputs = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_outputs = np.array([[0, 1, 1, 0]]).T neural_network.train(training_inputs, training_outputs, 10000) print("Synaptic weights after training:") print(neural_network.synaptic_weights) print("Enter 3 binary inputs (0 or 1):") user_input_1 = int(input("User input 1: ")) user_input_2 = int(input("User input 2: ")) user_input_3 = int(input("User input 3: ")) new_situation = np.array([user_input_1, user_input_2, user_input_3]) output = neural_network.think(new_situation) print("Considering new situation", new_situation, "-> Output:") print(output) ## practical 6 adaboost import pandas as pd from sklearn import model_selection from sklearn.ensemble import AdaBoostClassifier # Dataset URL url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv" # Read dataset df = pd.read_csv(url) array = df.values # Features & labels X = array[:, 0:8] Y = array[:, 8] # Model setup seed = 7 trees = 30 # 30 weak learners model = AdaBoostClassifier(n_estimators=trees, random_state=seed, algorithm="SAMME") # Cross-validation result = model_selection.cross_val_score(model, X, Y, cv=10) print("Accuracy: %.2f%%" % (result.mean()*100)) ## practical 7 Recursive Breadth First Search import queue as Q from RMP import dict_gn from RMP import dict_hn start = 'Arad' goal = 'Bucharest' result = '' def get_fn(citystr): cities = citystr.split(",") hn = gn = 0 for ctr in range(0, len(cities)-1): gn = gn + dict_gn[cities[ctr]][cities[ctr+1]] hn = dict_hn[cities[len(cities)-1]] return (hn + gn) def printout(cityq): for i in range(0, cityq.qsize()): print(cityq.queue[i]) def expand(cityq): global result tot, citystr, thiscity = cityq.get() nextot = 999 if not cityq.empty(): nextot, nextcitystr, nextcity = cityq.queue[0] if thiscity == goal and nextot > tot: result = citystr + "::" + str(tot) return print("Expanding city------------------------------ ", thiscity) print("Second best f(n)---------------------------- ", nextot) tempq = Q.PriorityQueue() for cty in dict_gn[thiscity]: tempq.put((get_fn(citystr+","+cty), citystr +","+cty, cty)) for ctr in range(1, 3): ctrtot, ctrcitystr, ctrthiscity = tempq.get() if ctrtot < nextot: cityq.put((ctrtot, ctrcitystr, ctrthiscity)) else: cityq.put((ctrtot, ctrcitystr, ctrthiscity)) break printout(cityq) expand(cityq) def main(): cityq = Q.PriorityQueue() thiscity = start cityq.put((get_fn(start), start, thiscity)) expand(cityq) main() ## RMP file dict_gn = { 'Arad': {'Zerind': 75, 'Sibiu': 140, 'Timisoara': 118}, 'Zerind': {'Arad': 75, 'Oradea': 71}, 'Oradea': {'Zerind': 71, 'Sibiu': 151}, 'Sibiu': {'Arad': 140, 'Oradea': 151, 'Fagaras': 99, 'Rimnicu Vilcea': 80}, 'Timisoara': {'Arad': 118, 'Lugoj': 111}, 'Lugoj': {'Timisoara': 111, 'Mehadia': 70}, 'Mehadia': {'Lugoj': 70, 'Drobeta': 75}, 'Drobeta': {'Mehadia': 75, 'Craiova': 120}, 'Craiova': {'Drobeta': 120, 'Rimnicu Vilcea': 146, 'Pitesti': 138}, 'Rimnicu Vilcea': {'Sibiu': 80, 'Craiova': 146, 'Pitesti': 97}, 'Fagaras': {'Sibiu': 99, 'Bucharest': 211}, 'Pitesti': {'Rimnicu Vilcea': 97, 'Craiova': 138, 'Bucharest': 101}, 'Bucharest': {'Fagaras': 211, 'Pitesti': 101, 'Giurgiu': 90, 'Urziceni': 85}, 'Giurgiu': {'Bucharest': 90}, 'Urziceni': {'Bucharest': 85, 'Hirsova': 98, 'Vaslui': 142}, 'Hirsova': {'Urziceni': 98, 'Eforie': 86}, 'Eforie': {'Hirsova': 86}, 'Vaslui': {'Urziceni': 142, 'Iasi': 92}, 'Iasi': {'Vaslui': 92, 'Neamt': 87}, 'Neamt': {'Iasi': 87} } dict_hn = { 'Arad': 366, 'Bucharest': 0, 'Craiova': 160, 'Drobeta': 242, 'Eforie': 161, 'Fagaras': 176, 'Giurgiu': 77, 'Hirsova': 151, 'Iasi': 226, 'Lugoj': 244, 'Mehadia': 241, 'Neamt': 234, 'Oradea': 380, 'Pitesti': 100, 'Rimnicu Vilcea': 193, 'Sibiu': 253, 'Timisoara': 329, 'Urziceni': 80, 'Vaslui': 199, 'Zerind': 374 }

Post a Comment

0Comments
Post a Comment (0)
Xf
Vghjj