0% found this document useful (0 votes)
4 views23 pages

Final

The document contains multiple Python programs demonstrating various search algorithms such as Breadth-First Search, Depth-First Search, Greedy Best-First Search, A* Search, and AO* Search, along with supervised machine learning examples using datasets like Iris and car prices. Each program includes the necessary code and comments explaining the functionality and output. Additionally, it covers applications in predicting weather and classifying emails as spam or not spam.

Uploaded by

Bhuvan P.r
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)
4 views23 pages

Final

The document contains multiple Python programs demonstrating various search algorithms such as Breadth-First Search, Depth-First Search, Greedy Best-First Search, A* Search, and AO* Search, along with supervised machine learning examples using datasets like Iris and car prices. Each program includes the necessary code and comments explaining the functionality and output. Additionally, it covers applications in predicting weather and classifying emails as spam or not spam.

Uploaded by

Bhuvan P.r
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/ 23

1. Python Program on problem solving by searching: Breadth-First Search.

graph = {
'5' : ['3','7'], '3' : ['2', '4'], '7' : ['8'],
'2' : [], '4' : ['8'], '8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Output:
2. Python Program on problem solving by searching: Depth-First Search.
graph = {
'A' : ['B','C','D'], 'B' : ['E', 'F'], 'C' : [], 'D' : ['G','H'], 'E' : [], 'F' : [],
'G' : ['I','J'], 'I' : [], 'J' : ['K'], 'K' : [], 'H' : []
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, 'A')

Output:
3. Python Program on problem solving by searching: Greedy best-first
Search.
import heapq
graph = {
'A': [('B'), ('C')], 'B': [('D'), ('E')], 'C': [('F')], 'D': [('G'), ('I')], 'E': [('H')],
'F': [], 'G': [], 'H': [], 'I': []
}
heuristic = {
'A':10, 'B':8, 'C':7, 'D':6, 'E':4, 'F':5, 'G':3, 'H':2, 'I':0
}
def best_first_search(graph,start,goal,heuristic):
frontier = [(heuristic[start], start)]# priority queue of(priority, node)
came_from = {}
came_from[start] = None
while frontier:
_, current = heapq.heappop(frontier)# node with lowest heuristic value
if current == goal:
break
for neighbor in graph[current]:
if neighbor not in came_from:
priority = heuristic[neighbor]
heapq.heappush(frontier, (priority, neighbor))
came_from[neighbor] = current
return came_from

start_node ='A'
goal_node ='I'
came_from = best_first_search(graph, start_node, goal_node, heuristic)

print("Path from", start_node,"to", goal_node,":")


node = goal_node
path = [node]
while node != start_node:
node = came_from[node]
path.append(node)
path.reverse()
print(path)

Output:
4. Python Program on problem solving by searching: A* Search.

def aStarAlgo(start_node, stop_node):


open_set = set(start_node)
closed_set = set()
g = {} #store distance from starting node
parents = {} # parents contains an adjacency map of all nodes
#distance of starting node from itself is zero
g[start_node] = 0
#start_node is root node i.e it has no parent nodes
#so start_node is set to its own parent node
parents[start_node] = start_node
while len(open_set) > 0:
n = None
#node with lowest f() is found
for v in open_set:
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
if n == stop_node or Graph_nodes[n] == None:
pass
else:
for (m, weight) in get_neighbors(n):
#nodes 'm' not in first and last set are added to first
#n is set its parent
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
#for each node m,compare its distance from start i.e g(m) to the
#from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
#if m in closed set,remove and add to open
if m in closed_set:
closed_set.remove(m)
open_set.add(m)

if n == None:
print('Path does not exist!')
return None

# if the current node is the stop_node


# then we begin reconstructin the path from it to the start_node
if n == stop_node:
path = [ ]
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path
# remove n from the open_list, and add it to closed_list
# because all of his neighbors were inspected
open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None

#define fuction to return neighbor and its distance


#from the passed node
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None

def heuristic(n):
H_dist = {
'A': 11, 'B': 6,'C': 5,'D': 7, 'E': 3, 'F': 6, 'G': 5, 'H': 3, 'I': 1, 'J': 0
}
return H_dist[n]

#Describe your graph here


Graph_nodes = {
'A': [('B', 6), ('F', 3)],
'B': [('A', 6), ('C', 3), ('D', 2)],
'C': [('B', 3), ('D', 1), ('E', 5)],
'D': [('B', 2), ('C', 1), ('E', 8)],
'E': [('C', 5), ('D', 8), ('I', 5), ('J', 5)],
'F': [('A', 3), ('G', 1), ('H', 7)],
'G': [('F', 1), ('I', 3)],
'H': [('F', 7), ('I', 2)],
'I': [('E', 5), ('G', 3), ('H', 2), ('J', 3)],
}

aStarAlgo('A', 'J')

Output:
5. Python Program on problem solving by searching: AO* Search.

class Graph:
def __init__(self, graph, heuristicNodeList, startNode): #instantiate graph object
with graph topology, heuristic values, start node
self.graph = graph
self.H=heuristicNodeList
self.start=startNode
self.parent={}
self.status={}
self.solutionGraph={}

def applyAOStar(self): # starts a recursive AO* algorithm


self.aoStar(self.start, False)
def getNeighbors(self, v): # gets the Neighbors of a given node
return self.graph.get(v,'')
def getStatus(self,v): # return the status of a given node
return self.status.get(v,0)
def setStatus(self,v, val): # set the status of a given node
self.status[v]=val
def getHeuristicNodeValue(self, n):
return self.H.get(n,0) # always return the heuristic value of a given node
def setHeuristicNodeValue(self, n, value):
self.H[n]=value # set the revised heuristic value of a given node
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE
START NODE:",self.start)
print("------------------------------------------------------------")
print(self.solutionGraph)
print("------------------------------------------------------------")
def computeMinimumCostChildNodes(self, v): # Computes the Minimum Cost
of child nodes of a given node v
minimumCost=0
costToChildNodeListDict={}
costToChildNodeListDict[minimumCost]=[]
flag=True
for nodeInfoTupleList in self.getNeighbors(v): # iterate over all the set of child
node/s
cost=0
nodeList=[]
for c, weight in nodeInfoTupleList:
cost=cost+self.getHeuristicNodeValue(c)+weight
nodeList.append(c)
if flag==True: # initialize Minimum Cost with the cost of first set of child
node/s
minimumCost=cost
costToChildNodeListDict[minimumCost]=nodeList # set the Minimum
Cost child node/s
flag=False
else: # checking the Minimum Cost nodes with the current Minimum Cost
if minimumCost>cost:
minimumCost=cost
costToChildNodeListDict[minimumCost]=nodeList # set the Minimum
Cost child node/s
return minimumCost, costToChildNodeListDict[minimumCost] # return
Minimum Cost and Minimum Cost child node/s

def aoStar(self, v, backTracking): # AO* algorithm for a start node and


backTracking status flag
print("HEURISTIC VALUES :", self.H)
print("SOLUTION GRAPH :", self.solutionGraph)
print("PROCESSING NODE :", v)
print("---------------------------------------------------------------------------------------
--")
if self.getStatus(v) >= 0: # if status node v >= 0, compute Minimum Cost
nodes of v
minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)
print(minimumCost, childNodeList)
self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v,len(childNodeList))
solved=True # check the Minimum Cost nodes of v are solved
for childNode in childNodeList:
self.parent[childNode]=v
if self.getStatus(childNode)!=-1:
solved=solved & False
if solved==True: # if the Minimum Cost nodes of v are solved, set the
current node status as solved(-1)
self.setStatus(v,-1)
self.solutionGraph[v]=childNodeList # update the solution graph with the
solved nodes which may be a part of solution
if v!=self.start: # check the current node is the start node for backtracking
the current node value
self.aoStar(self.parent[v], True) # backtracking the current node value
with backtracking status set to true
if backTracking==False: # check the current call is not for backtracking
for childNode in childNodeList: # for each Minimum Cost child node
self.setStatus(childNode,0) # set the status of child node to 0(needs
exploration)
self.aoStar(childNode, False) # Minimum Cost child node is further
explored with backtracking status as false

print ("Graph - 1")


h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
graph1 = {
'A': [[('B', 1), ('C', 1)], [('D', 1)]],
'B': [[('G', 1)], [('H', 1)]],
'C': [[('J', 1)]],
'D': [[('E', 1), ('F', 1)]],
'G': [[('I', 1)]]
}

G1= Graph(graph1, h1, 'A')


G1.applyAOStar()
G1.printSolution()
Output:
6a. Python program to demonstrate the supervised machine learning.

from sklearn import datasets


import pandas as pd
import matplotlib.pyplot as plt

# Loading IRIS dataset from scikit-learn object into iris variable.


iris = datasets.load_iris()

# Prints the type/type object of iris


print(type(iris))
# <class 'sklearn.datasets.base.Bunch'>

# prints the dictionary keys of iris data


print(iris.keys())

# prints the type/type object of given attributes


print(type(iris.data), type(iris.target))

# prints the no of rows and columns in the dataset


print(iris.data.shape)

# prints the target set of the data


print(iris.target_names)

# Load iris training dataset


X = iris.data

# Load iris target set


Y = iris.target

# Convert datasets' type into dataframe


df = pd.DataFrame(X, columns=iris.feature_names)

# Print the first five tuples of dataframe.


print(df.head())
Output:
6b. Python program to demonstrate the supervised machine learning.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [3, 5, 7, 8, 9],
'target': [4, 7, 10, 12, 14]
}
df = pd.DataFrame(data)

X = df[['feature1', 'feature2']]
y = df['target']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)

print("Mean Squared Error:", mse)


print("Predictions:", y_pred)
Output:
7. Python program to predict the price of the car using decision tree.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
# Example dataset
data = {
'year': [2010, 2011, 2012, 2013, 2014],
'mileage': [50000, 40000, 30000, 20000, 10000],
'price': [15000, 14000, 13000, 12000, 11000]
}
df = pd.DataFrame(data)
X = df[['year', 'mileage']]
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
model = DecisionTreeRegressor()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
print("Predictions:", y_pred)

Output:
8. Python program of weather prediction model that predicts whether or not
there’ll be rain on a particular day.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'temperature': [30, 25, 27, 35, 20],
'humidity': [70, 65, 80, 90, 60],
'rain': [1, 1, 1, 0, 0] # 1 for rain, 0 for no rain
}
df = pd.DataFrame(data)
X = df[['temperature', 'humidity']]
y = df['rain']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_pred = [1 if p >= 0.5 else 0 for p in y_pred]
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)

Output:
10. Python program to classify the emails as spam or not spam.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score

# Example dataset
data = {
'email': ['buy now', 'limited offer', 'meeting at 3', 'project deadline', 'win a
prize'],
'label': [1, 1, 0, 0, 1] # 1 for spam, 0 for not spam
}
df = pd.DataFrame(data)

X = df['email']
y = df['label']

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)

model = MultinomialNB()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Output:
11. Python program that demonstrate how to classify flower using a Support
vector machine classifier.

from sklearn import datasets


from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score

# Load the iris dataset


iris = datasets.load_iris()
X = iris.data # Features: sepal length, sepal width, petal length, petal width
y = iris.target # Labels: 0-setosa, 1-versicolor, 2-virginica

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Standardize the features (important for SVM)


scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Create an SVM classifier with a linear kernel


svm_classifier = SVC(kernel='linear')
# Train the classifier
svm_classifier.fit(X_train, y_train)

# Predict the labels of the test set


y_pred = svm_classifier.predict(X_test)
# Evaluate the classifier
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
Output:
12. Python program to demonstrate how to use basic artificial neural network
to classify students based on their height and weight.

import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Sample data: [height (cm), weight (kg)]
X = np.array([
[150, 45], [160, 55], [170, 65], [180, 75], [190, 85],
[160, 50], [170, 60], [180, 70], [190, 80], [200, 90]
])
# Labels: 0 for class 0 (shorter/lighter), 1 for class 1 (taller/heavier)
y = np.array([0, 0, 0, 1, 1, 0, 0, 1, 1, 1])
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Create the MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(5,), max_iter=1000,
random_state=42)
# Train the classifier
clf.fit(X_train, y_train)
# Make predictions
y_pred = clf.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
# Print the results
print("Testing inputs (X_test):")
print(X_test)
print("Actual labels (y_test):")
print(y_test)
print("Predicted labels (y_pred):")
print(y_pred)
print("Accuracy:", accuracy)
Output:
13. Python program using speech recognition library to perform speech
recognition.

import speech_recognition as sr
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()

# Reading Microphone as source


# listening the speech and store in audio_text variable
with sr.Microphone() as source:
print("Talk")
audio_text = r.listen(source)
print("Time over, thanks")

# recoginze_() method will throw a request


# error if the API is unreachable,
# hence using exception handling
try:
# using google speech recognition
print("Text: "+r.recognize_google(audio_text))
except:
print("Sorry, I did not get that")

Output
Hi Siri.

You might also like