[go: up one dir, main page]

0% found this document useful (0 votes)
5 views2 pages

BFS: DFS:: Analysis of Breadth First and Depth First Search in Terms of Time and Space

The document discusses the implementation and comparison of various algorithms including Breadth-First Search (BFS), Depth-First Search (DFS), Greedy Search, A* Search, Decision Tree Classifier, Naive Bayesian Classifier, Hierarchical Clustering, and K-Means Clustering. Each algorithm is demonstrated with code snippets and includes analysis of execution time and memory usage. Additionally, it showcases how to visualize the clustering results and predictions from classifiers.

Uploaded by

j.karuthapandian
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)
5 views2 pages

BFS: DFS:: Analysis of Breadth First and Depth First Search in Terms of Time and Space

The document discusses the implementation and comparison of various algorithms including Breadth-First Search (BFS), Depth-First Search (DFS), Greedy Search, A* Search, Decision Tree Classifier, Naive Bayesian Classifier, Hierarchical Clustering, and K-Means Clustering. Each algorithm is demonstrated with code snippets and includes analysis of execution time and memory usage. Additionally, it showcases how to visualize the clustering results and predictions from classifiers.

Uploaded by

j.karuthapandian
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/ 2

Bfs: Dfs: Analysis of Breadth First and Depth First Search in Terms of Time and Space end_ me = me.

Analysis of Breadth First and Depth First Search in Terms of Time and Space end_ me = me. me()
graph = { graph = { from collec ons import defaultdict import me execu on_ me = end_ me - start_ me
'5' : ['3','7'], '5' : ['3','7'], import sys class memory_usage = sys.getsizeof(graph)
'3' : ['2', '4'], '3' : ['2', '4'], Graph: return execu on_ me, memory_usage
'7' : ['8'], '7' : ['8'], def init (self): if name == " main ":
'2' : [], '2' : [], self.graph = defaultdict(list) g = Graph() g.add_edge(0, 1)
'4' : ['8'], '4' : ['8'], def add_edge(self, u, v): g.add_edge(0, 2)
'8' : [] '8' : [] self.graph[u].append(v) g.add_edge(1, 2)
} } def bfs(self, start): g.add_edge(2, 0)
visited = [] visited = set() visited = set() g.add_edge(2, 3)
queue = [] def dfs(visited, graph, node): queue = [start] g.add_edge(3, 3)
def bfs(visited, graph, node): if node not in visited: print (node) visited.add(node) visited.add(start) start_node = 2
visited.apped(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) while queue: bfs_ me, bfs_memory = analyze_algorithm(g.bfs, g.graph, start_node)
queue.append(node) print ("Following is the Depth-First Search") vertex = queue.pop(0) dfs_ me, dfs_memory = analyze_algorithm(g.dfs, g.graph, start_node)
while queue: dfs(visited, graph, '5') for neighbor in self.graph[vertex]: print("BFS Execu on Time:", bfs_ me)
m = queue.pop(0) if neighbor not in visited: print("BFS Memory Usage:", bfs_memory)
print (m, end = " ") queue.append(neighbor) visited.add(neighbor) print("DFS Execu on Time:", dfs_ me)
for neighbour in graph[m]: def dfs_u l(self, vertex, visited): visited.add(vertex) print("DFS Memory Usage:", dfs_memory)
if neighbour not in visited: for neighbor in self.graph[vertex]: if neighbor not in visited:
visited.append(neighbour) self.dfs_u l(neighbor, visited) def dfs(self, start):
queue.append(neighbour) visited = set() self.dfs_u l(start, visited)
print ("Following is the Breadth-First Search") def analyze_algorithm(algorithm, graph, start_node):
bfs(visited, graph, '5') start_ me = me. me()
algorithm(graph, start_node)

Implement and Compare Greedy and A* Algorithm path = [] closed_set.add(current) ]


while current: for neighbor in get_neighbors(current, grid): start = Node(0, 0) goal = Node(3, 4) print("Grid:") print_grid(grid)
import heapq class Node:
path.append((current.x, current.y)) if neighbor in closed_set: con nue print("\nGreedy Search Path:")
def init (self, x, y): self.x = x
current = current.parent tenta ve_g = current.g + 1 greedy_path = greedy_search(start, goal, grid) print_grid(grid, greedy_path)
self.y = y
return path[::-1] if neighbor not in open_list or tenta ve_g < neighbor.g: print("\nA* Search Path:")
self.g = 0
for neighbor in get_neighbors(current, grid): neighbor.parent = current astar_path = astar_search(start, goal, grid)
self.h = 0
if neighbor not in open_list: neighbor.g = tenta ve_g print_grid(grid, astar_path)
self.parent = None
neighbor.parent = current neighbor.h = manha an_distance(neighbor, goal)
def lt (self, other):
open_list.append(neighbor) if neighbor not in open_list:
return (self.g + self.h) < (other.g + other.h)
open_list.sort(key=lambda x: manha an_distance(x, goal)) heapq.heappush(open_list, neighbor) return None
def manha an_distance(node1, node2):
return None def print_grid(grid, path=None):
return
def astar_search(start, goal, grid): for i in range(len(grid)):
abs(node1.x - node2.x) + abs(node1.y - node2.y)
open_list = [] for j in range(len(grid[0])):
def get_neighbors(node, grid):
closed_set = set() if path and (i, j) in path:
neighbors = []
heapq.heappush(open_list, start) print("P", end=" ")
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
while open_list: elif grid[i][j] == 1:
nx, ny = node.x + dx, node.y + dy
current = print("#", end=" ")
if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] != 1:
heapq.heappop(open_list) else:
neighbors.append(Node (nx, ny))
if current == goal: print(".", end=" ") print()
return neighbors
path = [] grid = [
def greedy_search(start, goal, grid):
while current: [0, 0, 0, 0, 0],
open_list = [start]
path.append((current.x, current.y)) [0, 0, 1, 0, 0],
while open_list:
current = current.parent [0, 0, 1, 0, 0],
current = open_list.pop(0)
return path[::-1] [0, 0, 0, 0, 0],
if current == goal:
Write a program to demonstrate the working of the decision treebased Write a program to implement the naive Bayesian classifier Implementing hierarchical clustering algorithm Implementing k-Means algorithm to cluster a set of data
algorithm
from sklearn.feature_extrac on.text import numpy as np import numpy as np
import pandas as pd
import CountVectorizer import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt
from sklearn.naive_bayes from sklearn.datasets class KMeans:
from sklearn import tree
import Mul nomialNB import make_blobs def _init_(self, n_clusters=3, max_iters=100):
df = pd.read_excel("na on.xlsx")
train_sentences = [ from sklearn.cluster self.n_clusters = n_clusters
d = {'UK': 0, 'USA': 1, 'N': 2}
"I love this movie", import Agglomera veClustering self.max_iters = max_iters
df['Na onality'] = df['Na onality'].map(d)
"This movie is great", "Wonderful movie", from scipy.cluster.hierarchy def fit(self, X):
d = {'YES': 1, 'NO': 0}
"I hate this movie", import dendrogram, linkage self.centroids = X[np.random.choice(X.shape[0], self.n_clusters,
df['Go'] = df['Go'].map(d) replace=False)]
"This movie is terrible" X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
features = ['Age', 'Experience', 'Rank', 'Na onality'] linked = linkage(X, method='ward') for _ in range(self.max_iters):
]
X = df[features] plt.figure(figsize=(10, 7)) labels = self._assign_clusters(X)
train_labels = [1, 1,1, 0, 0]
y = df['Go'] dendrogram(linked, orienta on='top', distance_sort='descending', new_centroids = self._update_centroids(X, labels)
vectorizer = CountVectorizer()
dtree = DecisionTreeClassifier() show_leaf_counts=True) plt. tle('Hierarchical Clustering Dendrogram')
X_train = vectorizer.fit_transform(train_sentences) nb_classifier = if np.allclose(new_centroids, self.centroids):
dtree = dtree.fit(X, y) Mul nomialNB() nb_classifier.fit(X_train, train_labels) plt.xlabel('Sample Index') plt.ylabel('Distance')
break
plt.figure(figsize=(12, 8)) user_input = input("Enter a sentence: ") plt.show()
self.centroids = new_centroids return labels
tree.plot_tree(dtree, feature_names=features, class_names=['NO', 'YES'], X_user = vectorizer.transform([user_input]) cluster = Agglomera veClustering(n_clusters=4, affinity='euclidean',
def _assign_clusters(self, X):
filled=True) plt.subplots_adjust(le =0.05, right=0.95, top=0.95, bo om=0.05) linkage='ward')
predic on = nb_classifier.predict(X_user)[0] distances = np.sqrt(((X - self.centroids[:,
plt.show() cluster.fit_predict(X)
sen ment = "posi ve" if predic on == 1 else "nega ve" print(f"Predicted np.newaxis])**2).sum(axis=2))
sen ment for '{user_input}': {sen ment}") plt.figure(figsize=(10, 7))
return np.argmin(distances, axis=0)
plt.sca er(X[:,0], X[:,1], c=cluster.labels_, cmap='viridis')
def _update_centroids(self, X, labels):
plt. tle('Hierarchical Clustering')
new_centroids = np.zeros_like(self.centroids)
plt.xlabel('Feature 1')
for i in range(self.n_clusters):
plt.ylabel('Feature 2')
new_centroids[i] = X[labels == i].mean(axis=0)
plt.show()

return new_centroids
np.random.seed(0)
X, _ = np.random.randn(100, 2), None kmeans = KMeans(n_clusters=3)
labels = kmeans.fit(X)
plt.figure(figsize=(8, 6))
plt.sca er(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.sca er(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='x', c='red',
s=100, label='Centroids')
plt. tle('K-means Clustering') plt.xlabel('Feature 1')
plt.ylabel('Feature 2') plt.legend()
plt.show()

You might also like