AID 5th Semester Deep Learning Laboratory - AD3511 - Lab Manual
AID 5th Semester Deep Learning Laboratory - AD3511 - Lab Manual
AID 5th Semester Deep Learning Laboratory - AD3511 - Lab Manual
4th Semester
2nd Semester
Deep Learning -
AD3501
Embedded Systems
Data and Information Human Values and
and IoT - CS3691
5th Semester
7th Semester
8th Semester
Open Elective-1
Distributed Computing Open Elective 2
- CS3551 Project Work /
Elective-3
Open Elective 3 Intership
Big Data Analytics - Elective-4
CCS334 Open Elective 4
Elective-5
Elective 1 Management Elective
Elective-6
Elective 2
All Computer Engg Subjects - [ B.E., M.E., ] (Click on Subjects to enter)
Programming in C Computer Networks Operating Systems
Programming and Data Programming and Data Problem Solving and Python
Structures I Structure II Programming
Database Management Systems Computer Architecture Analog and Digital
Communication
Design and Analysis of Microprocessors and Object Oriented Analysis
Algorithms Microcontrollers and Design
Software Engineering Discrete Mathematics Internet Programming
Theory of Computation Computer Graphics Distributed Systems
Mobile Computing Compiler Design Digital Signal Processing
Artificial Intelligence Software Testing Grid and Cloud Computing
Data Ware Housing and Data Cryptography and Resource Management
Mining Network Security Techniques
Service Oriented Architecture Embedded and Real Time Multi - Core Architectures
Systems and Programming
Probability and Queueing Theory Physics for Information Transforms and Partial
Science Differential Equations
Technical English Engineering Physics Engineering Chemistry
Engineering Graphics Total Quality Professional Ethics in
Management Engineering
Basic Electrical and Electronics Problem Solving and Environmental Science and
and Measurement Engineering Python Programming Engineering
lOMoARcPSD|45333583
www.BrainKart.com
AIM:
To implement a python program for Breadth First Search (BFS).
Breadth-First Search
⮚ It must be ensured that each vertex of the graph is visited exactly once to
avoid getting into an infinite loop with cyclic graphs or to prevent visiting
a given node multiple times when it can be reached through more than
one path.
which follows the first-in-first-out (FIFO) method – i.e., the node that
was inserted first will be visited first, and so on.
ALGORITHM:
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM:
graph={
'5':['3','7'],
'3':['2','4'],
'7':['8'],
'2':[],
'4':['8'],
'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)
print ("Following is the Breadth-First Search")
bfs(visited,graph,'5')
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
Following is the Breadth-First Search
537248
RESULT:
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Thus the program for breadth-first search was implemented and executed
successfully.
AIM:
To implement a python code for Depth First Search (DFS)
ALGORITHM:
Step: 1 Pick any node. If it is unvisited, mark it as visited and recur on all
its adjacent nodes.
Step: 2 Repeat until all the nodes are visited, or the node to be searched is
found.
Step: 4 The dfs function is called and is passed the visited set,
the graph in the form of a dictionary, and A, which is the starting node.
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set()
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
RESULT:
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Thus the program for depth-first search was implemented and executed
successfully.
Ex.No:2a
IMPLEMENTATION OF A* SEARCH ALGORITHM
Date :
AIM:
To implement a path finding using A* search algorithm.
A* SEARCH :
⮚ A* search finds the shortest path through a search space to the goal state
using the heuristic function.
⮚ This technique finds minimal cost solutions and is directed to a goal state
called A* search.
⮚ The A* algorithm also finds the lowest-cost path between the start and
goal state, where changing from one state to another requires some cost.
STEPS FOR SOLVING A* SEARCH
⮚ Given the graph, find the cost-effective path from A to G. That is A is the
source node and G is the goal node.
A → B = g(B) + h(B) = 2 + 6 = 8
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
A → E = g(E) + h(E) = 3 + 7 = 10
⮚ Since the cost for A → B is less, we move forward with this path and compute the f(x) for the
children nodes of B.
A → B → C = (2 + 1) + 99= 102
A → B → G = (2 + 9 ) + 0 = 11
⮚ Here the path A → B → G has the least cost but it is s琀椀ll more than the cost of A → E, thus
we explore this path further.
A → E → D = (3 + 6) + 1 = 10
⮚ Comparing the cost of A → E → D with all the paths we got so far and as this cost is least of
all we move forward with this path.
A → E → D → G = (3 + 6 + 1) +0 = 10
⮚ Now comparing all the paths that lead us to the goal, we conclude that A
→E→D→G is the most cost-effective path to get from A to G.
ALGORITHM:
// A* Search Algorithm
Step 1: Place the starting node into OPEN and find its f (n) value.
Step 2: Remove the node from OPEN, having the smallest f (n) value. If it is a
goal node then stop and return success.
Step 3: Else remove the node from OPEN, find all its successors.
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Step 4: Find the f (n) value of all successors; place them into OPEN and place
the removed node into CLOSE.
Step 5: Go to Step-2.
Step 6: Exit.
PROGRAM:
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):
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
#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
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
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
#for simplicity we ll consider heuristic distances given
#and this function returns heuristic distance for all nodes
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 5,
'D': 7,
'E': 3,
11
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
'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:
Path found: ['A', 'F', 'G', 'I', 'J']
12
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Thus the program for A* search algorithm for path was implemented and
executed successfully.
Ex.No:2b
IMPLEMENTATION OF MEMORY BOUNDED A*
Date : ALGORITHM
AIM:
To implement memory bounded A* search for path finding problem.
Memory bounded A* Search:
13
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM:
14
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
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
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
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
16
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
'A': 11,
'B': 6,
'C': 5,
'D': 7,
'E': 3,
'F': 6,
'G': 5,
'H': 3,
'I': 1,
'J': 0
}
return H_dist[n]
17
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Output:
Path found: ['A', 'F', 'G', 'I', 'J']
Output:
18
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Thus the program for memory bounded A* search was implemented and
executed successfully.
Ex.No:3
IMPLEMENT NAIVE BAYES MODEL
Date :
AIM:
To implement a program for Naïve Bayes model
NAÏVE BAYES CLASSIFIER ALGORITHM
⮚ Naive Bayes is among one of the very simple and powerful algorithms for
classification based on Bayes Theorem with an assumption of
independence among the predictors.
⮚ The Naive Bayes classifier assumes that the presence of a feature in a
class is not related to any other feature.
⮚ Naive Bayes is a classification algorithm for binary and multi-class
classification problems.
Bayes Theorem
Based on prior knowledge of conditions that may be related to an event,
Bayes theorem describes the probability of the event
conditional probability can be found this way
Assume we have a Hypothesis(H) and evidence(E),
According to Bayes theorem, the relationship between the probability of
Hypothesis before getting the evidence represented as P(H) and the
probability of the hypothesis after getting the evidence represented
as P(H|E) is:
o P(H|E) = P(E|H)*P(H)/P(E)
19
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM:
import pandas as pd
msg=pd.read_csv('naivetext.csv',names=['message','label'])
print('The dimensions of the dataset',msg.shape)
msg['labelnum']=msg.label.map({'pos':1,'neg':0})
X=msg.message
y=msg.labelnum
print(X)
print(y)
20
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
21
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
metrics.precision_score(ytest,predicted))
print('\n The value of Recall' ,
metrics.recall_score(ytest,predicted))
Output:
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
13 0
14 1
15 0
16 1
17 0
Name: labelnum, dtype: int64
The total number of Training Data: (13,)
The total number of Test Data: (5,)
The words or Tokens in the text documents
['about', 'am', 'amazing', 'an', 'and', 'awesome', 'beers', 'best', 'can', 'deal', 'do',
'enemy', 'feel',
'fun', 'good', 'great', 'have', 'he', 'holiday', 'house', 'is', 'like', 'love', 'my', 'not', 'of',
'place',
'restaurant', 'sandwich', 'sick', 'sworn', 'these', 'this', 'tired', 'to', 'today',
'tomorrow', 'very',
'view', 'we', 'went', 'what', 'will', 'with', 'work']
Accuracy of the classifier is 0.8
Confusion matrix
[[2 1]
[0 2]]
The value of Precision 0.6666666666666666
23
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Thus the program for naïve Bayes model was implemented and executed
successfully.
Ex.No:4
Implement Bayesian networks
Date :
AIM:
ALGORITHM:
Data set:heart.csv
PROGRAM:
24
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
import numpy as np
import pandas as pd
import csv
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
print(heartDisease.head())
print(heartDisease.dtypes)
model=BayesianModel([('age','heartdisease'),('sex','heartdisease'),
('exang','heartdisease'),('cp','heartdisease'),('heartdisease','restecg'),
('heartdisease','chol')])
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)
25
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
HeartDiseasetest_infer = VariableElimination(model)
q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evi
dence={'restecg':1})
print(q1)
q2=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'cp':2})
print(q2)
26
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
27
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
28
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
29
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Ex.No:5a
Implement Regression models (Linear Regression)
Date :
AIM:
DEFINITION:
Let us consider a dataset where we have a value of response y for every feature
x:
30
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Now, the task is to find a line that fits best in the above scatter plot so
that we can predict the response for any new feature values. This line is
called a regression line.
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
# putting labels
plt.xlabel('x')
31
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
plt.ylabel('y')
def main():
# observations / data
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
# estimating coefficients
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0], b[1]))
if __name__ == "__main__":
main()
OUTPUT:
RESULT:
Thus the python program to implement linear regression model was
implemented and executed successfully.
32
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Ex.No:5b
Implement Regression models (Logistic Regression)
Date :
AIM:
PROGRAM:
from sklearn.datasets import make_classification
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
# Generate and dataset for Logistic Regression
x, y = make_classification(
n_samples=100,
n_features=1,
n_classes=2,
33
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
n_clusters_per_class=1,
flip_y=0.03,
n_informative=1,
n_redundant=0,
n_repeated=0
)
print(x,y)
OUTPUT:
[[ 0.68072366]
[-0.806672 ]
[-0.25986635]
[-0.96951576]
[-1.55870949]
[-0.71107565]
[ 0.05858082]
[-2.06472972]
[-0.61592043]
[ 1.25423915]
[ 0.81852686]
[-1.65141186]
[-0.5894455 ]
[ 1.02745431]
[-0.32508896]
[-0.53886171]
[ 1.14821234]
[ 0.87538478]
[ 0.95887802]
[ 1.30514551]
[-1.02478688]
[ 0.16563384]
[ 0.77626036]
[-1.00622251]
[-0.55976575]
[ 1.33550038]
[ 1.60327317]
[ 1.82115858]
[-0.68603388]
34
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
[ 1.8733355 ]
[-0.52494619]
[-2.03314002]
[ 0.47001797]
[ 1.55400671]
[-1.34062378]
[-0.38624537]
[-1.06339387]
[-1.41465045]
[ 0.58850401]
[ 0.80925135]
[-0.82066568]
[-0.01262654]
[-0.75104194]
[-1.09609801]
[-0.30652093]
[-0.6945338 ]
[-0.90156651]
[-0.96587756]
[ 0.53851931]
[ 0.16533166]
[-1.04609567]
[-1.15065139]
[-0.76739642]
[ 0.83776929]
[ 2.20562241]
[-0.80368921]
[-0.86160904]
[ 0.86032131]
[-0.65752318]
[ 1.81228279]
[-0.81507664]
[ 0.93532773]
[ 1.76874632]
[ 0.32893072]
[ 1.02960085]
[-1.84150254]
[ 0.16156709]
[-1.05944665]
[ 0.28788136]
[-1.05549933]
[ 1.37528673]
[ 1.66369265]
[ 1.71761177]
35
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
[ 1.96597594]
[-0.65315492]
[-0.29598263]
[-1.15345006]
[-1.03851861]
[ 1.69109822]
[ 1.92402678]
[-0.89593983]
[-0.58208549]
[-1.18750595]
[-1.06231671]
[-0.79230653]
[ 1.42147278]
[ 1.2887393 ]
[ 1.93706073]
[-1.03110736]
[-1.20543711]
[ 0.79446549]
[ 1.29599432]
[ 0.49396915]
[ 0.63241066]
[ 0.72416825]
[-1.76099355]
[-0.61639759]
[-0.43854548]
[ 1.43886371]
[-0.77167438]] [1 0 1 0 0 0 1 0 1 1 1 0 0 1 1 0 1 1
1 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0
0 1 1 0 1 1 0 1 0 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1
1 1 0 0 0 1 0 1 1 1 1
0 1 0 0 1 1 0 0 0 0 0 1 1 1 0 0 1 1 1 1 1 0 0 0 1 0]
36
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
log_reg=LogisticRegression()
log_reg.fit(x_train, y_train)
y_pred=log_reg.predict(x_test)
confusion_matrix(y_test, y_pred)
OUTPUT:
array([[12, 0],
[ 2, 11]], dtype=int64)
37
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Thus the python program to implement logistic regression model was
implemented and executed successfully.
Ex.No:6a
Implement Decision Tree
Date :
AIM:
ALGORITHM
38
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM:
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
def importdata():
balance_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-
learning-'+'databases/balance-scale/balance-scale.data',sep= ',', header = None)
# Printing the dataset shape
print ("Dataset Length: ", len(balance_data))
print ("Dataset Shape: ", balance_data.shape)
39
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
return balance_data
def splitdataset(balance_data):
# Performing training
clf_gini.fit(X_train, y_train)
return clf_gini
40
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
41
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
Dataset Length: 625
Dataset Shape: (625, 5)
Dataset: 0 1 2 3 4
0 B 1 1 1 1
1 R 1 1 1 2
2 R 1 1 1 3
3 R 1 1 1 4
4 R 1 1 1 5
Results Using Gini Index:
Predicted values:
['R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L'
'L' 'R' 'L' 'R' 'L'
'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L'
'L' 'R' 'L' 'L' 'L'
'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R'
'L' 'R' 'R' 'L' 'R'
42
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'L' 'L'
'R' 'R' 'L' 'L' 'R'
'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L'
'R' 'R' 'L' 'R' 'L'
'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'R'
'R' 'R' 'R' 'R' 'R'
'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L'
'R' 'L' 'L' 'L' 'L'
'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L'
'R' 'L' 'R' 'L' 'R'
'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L'
'R' 'R' 'R' 'R' 'R'
'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L'
'L' 'L' 'L' 'R' 'R'
'L' 'R' 'R' 'L' 'L' 'R' 'R' 'R']
Confusion Matrix: [[ 0 6 7]
[ 0 67 18]
[ 0 19 71]]
Accuracy : 73.40425531914893
Report : precision recall f1-score
support
43
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'L'
'R' 'R' 'R' 'R' 'R'
'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L'
'R' 'R' 'R' 'L' 'L'
'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L'
'R' 'L' 'R' 'L' 'R'
'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L'
'R' 'R' 'R' 'R' 'R'
'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L'
'L' 'L' 'L' 'L' 'R'
'R' 'R' 'L' 'L' 'L' 'R' 'R' 'R']
Confusion Matrix: [[ 0 6 7]
[ 0 63 22]
[ 0 20 70]]
Accuracy : 70.74468085106383
Report : precision recall f1-score
support
44
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Thus the python program to implement decision tree was implemented
and executed successfully.
Ex.No:6b
Implement Random Forest
Date :
AIM:
ALGORITHM:
45
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM:
import pandas as pd
from sklearn.datasets import load_digits
digits = load_digits()
dir(digits)
%matplotlib inline
import matplotlib.pyplot as plt
plt.gray()
for i in range(4):
plt.matshow(digits.images[i])
46
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
df = pd.DataFrame(digits.data)
df.head()
df['target'] = digits.target
df[0:12]
X = df.drop('target',axis='columns')
y = df.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=20)
model.fit(X_train, y_train)
model.score(X_test, y_test)
47
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
y_predicted = model.predict(X_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_predicted)
cm
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sn
plt.figure(figsize=(10,7))
sn.heatmap(cm, annot=True)
plt.xlabel('Predicted')
plt.ylabel('Truth')
RESULT:
Ex.No:7
Implement SVM Model
Date :
AIM:
48
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
ALGORITHM
⮚ Find the sepal length and sepal width from the given dataset
⮚ Find the petal length and petal width from the trained dataset
PROGRAM
import pandas as pd
iris = load_iris()
dir(iris)
iris.feature_names
49
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
df=pd.DataFrame(iris.data, columns=iris.feature_names)
df.head()
df['target']=iris.target
df.head()
iris.target_names
df[df.target==2].head
df['flower_name']=df.target.apply(lambda x:iris.target_names[x])
50
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
df.head()
%matplotlib inline
df0=df[df.target==0]
df1=df[df.target==1]
df2=df[df.target==2]
df2.head()
51
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
x = df.drop(['target','flower_name'], axis='columns')
x.head()
52
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
y=df.target
len(x_train)
len(x_test)
model = SVC(kernel='linear')
model.fit(x_train, y_train)
model.score(x_test, y_test)
RESULT:
53
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Ex.No:8
Implement Ensembling Techniques(Bagging)
Date :
AIM:
ALGORITHM
⮚ Display the first five rows from the dataframe using head() function.
function.
PROGRAM
import pandas as pd
df = pd.read_csv("pima-indians-diabetes.csv")
df.head()
54
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
df.isnull().sum()
df.describe()
df.diabetes.value_counts()
X = df.drop("diabetes",axis="columns")
y = df.diabetes
55
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled[:3]
X_train.shape
X_test.shape
y_train.value_counts()
201/375
y_test.value_counts()
56
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
67/125
scores
scores.mean()
bag_model = BaggingClassifier(
base_estimator=DecisionTreeClassifier(),
n_estimators=100,
max_samples=0.8,
oob_score=True,
random_state=0
bag_model.fit(X_train, y_train)
57
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
bag_model.oob_score_
bag_model.score(X_test, y_test)
bag_model = BaggingClassifier(
base_estimator=DecisionTreeClassifier(),
n_estimators=100,
max_samples=0.8,
oob_score=True,
random_state=0
scores
scores.mean()
58
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Ex.No: 9
Implement Clustering Algorithms(KMeans)
Date :
AIM:
ALGORITHM:
⮚ Display the first five rows of the dataset using head function
⮚ Apply Kmeans to the given dataset and find the septal length, septal
PROGRAM
import pandas as pd
%matplotlib inline
59
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
iris = load_iris()
df = pd.DataFrame(iris.data,columns=iris.feature_names)
df.head()
df['flower'] = iris.target
df.head()
df.head(3)
60
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
km = KMeans(n_clusters=3)
yp = km.fit_predict(df)
yp
df['cluster'] = yp
df.head(2)
df.cluster.unique()
df1 = df[df.cluster==0]
df2 = df[df.cluster==1]
df3 = df[df.cluster==2]
61
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
sse = []
k_rng = range(1,10)
for k in k_rng:
km = KMeans(n_clusters=k)
km.fit(df)
sse.append(km.inertia_)
plt.xlabel('K')
plt.plot(k_rng,sse)
62
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Ex.No: 10
Implement EM for Bayesian networks
Date :
AIM:
ALGORITHM:
o Use the current parameter estimates and the observed data (and
possibly incomplete data) to estimate the hidden or missing variables
using probabilistic inference (like the forward-backward algorithm for
hidden Markov models or sum-product algorithm for general Bayesian
networks). Compute the expected values of the hidden variables given
the current parameter estimates.
● M-step (Maximization):
63
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Program:
import numpy as np
np.random.seed(42)
true_prob_A = 0.6
sample_size = 1000
data_B = np.zeros(sample_size)
for i in range(sample_size):
# E-step: Expectation
64
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
return None
# M-step: Maximization
# Estimate probability of A
prob_A = np.mean(data_A)
data_B_given_A = data_B[data_A == a]
# EM iterations
# Initialize parameters
estimated_prob_A = 0.5
# Perform EM iterations
num_iterations = 10
for i in range(num_iterations):
65
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
estimated_prob_A, estimated_prob_B_given_A =
maximization_step(data_A, data_B, hidden_vars)
print(estimated_prob_B_given_A)
OUTPUT:
[[0.7719715 0.2280285]
[0.2970639 0.7029361]]
66
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
RESULT:
Ex.No: 11
Build simple Neural Network
Date :
AIM:
ALGORITHM
⮚ Train the input values and obtain the output from the given dataset.
⮚ Test the given dataset from the output obtained from the given dataset
⮚ Obtain the forward and Backward pass from the trained dataset
PROGRAM
# importing dependancies
import numpy as np
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
def activation(x):
return 1 / (1 + np.exp(-x))
for i in range(15000):
# forward pass
output = activation(dot_product)
# backward pass.
# OR of 1, 0 is 1
print(test_output)
68
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
RESULT:
AIM:
ALGORITHM
⮚ Load data from from the test file from the path 'C:/python/pima-indians-
diabetes.csv', delimiter=','
69
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
PROGRAM
X = dataset[:,0:8]
y = dataset[:,8]
model = Sequential()
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
OUTPUT:
70
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
_, accuracy = model.evaluate(X, y)
OUTPUT:
predictions = model.predict(X)
# round predictions
71
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
X = dataset[:,0:8]
y = dataset[:,8]
model = Sequential()
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',optimizer='adam',
metrics=['accuracy'])
for i in range(5):
72
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
OUTPUT:
RESULT:
Thus the python program to build deep learning neural network model
was implemented and executed successfully.
Content Beyond Syllabus
Solving XOR problem using DNN
Aim:
XOR logical function truth table for 2-bit binary variables, i.e, the input
vector and the corresponding output is,
X1 X2 Y
0 0 0
73
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
X1 X2 Y
0 1 1
1 0 1
1 1 0
Procedure:
1. Import the required Python libraries
2.Define Activation Function : Sigmoid Function
3.Initialize neural network parameters (weights, bias)
4. define model hyperparameters (number of iterations, learning rate)
5.Forward Propagation
6.Backward Propagation
7.Update weight and bias parameters
8.Train the learning model
9.Plot Loss value vs Epoch
10.Test the model performance
Program:
#import Python Libraries
import numpy as np
from matplotlib import pyplot as plt
# Sigmoid Function
def sigmoid(z):
return 1 / (1 + np.exp(-z))
74
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures)
W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers)
b1 = np.zeros((neuronsInHiddenLayers, 1))
b2 = np.zeros((outputFeatures, 1))
# Forward Propagation
def forwardPropagation(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)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
# Backward Propagation
def backwardPropagation(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)
75
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
return gradients
for i in range(epoch):
losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters)
gradients = backwardPropagation(X, Y, cache)
parameters = updateParameters(parameters, gradients, learningRate)
# Testing
X = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # XOR input
cost, _, A2 = forwardPropagation(X, Y, parameters)
prediction = (A2 > 0.5) * 1.0
# print(A2)
print(prediction)
76
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Output:
[[ 1. 0. 0. 1.]]
Result:
Thus the program for solving the XOR problem using DNN was
implemented and executed successfully.
Character recognition using CNN
Aim:
To write a python program to implement Character recognition using
CNN.
Procedure:
1.Data Collection and Preprocessing
2.Model Architecture
3.Compile the Model
4.Model Training
77
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
78
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
79
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
plt.legend()
plt.tight_layout()
plt.show()
# Example prediction
example_index = 0
example_image = X_test[example_index]
example_label = np.argmax(y_test[example_index])
predicted_label = np.argmax(model.predict(np.expand_dims(example_image,
axis=0)))
plt.imshow(example_image.squeeze(), cmap='gray')
plt.title(f"True Label: {example_label}, Predicted Label: {predicted_label}")
plt.axis('off')
plt.show()
Epoch 1/10
469/469 [==============================] - 69s 142ms/step - loss: 0.2773 -
accuracy: 0.9156 - val_loss: 0.0606 - val_accuracy: 0.9801
Epoch 2/10
469/469 [==============================] - 71s 151ms/step - loss: 0.0928 -
accuracy: 0.9729 - val_loss: 0.0420 - val_accuracy: 0.9853
Epoch 3/10
469/469 [==============================] - 78s 166ms/step - loss: 0.0666 -
accuracy: 0.9804 - val_loss: 0.0384 - val_accuracy: 0.9878
Epoch 4/10
469/469 [==============================] - 58s 123ms/step - loss: 0.0550 -
accuracy: 0.9832 - val_loss: 0.0295 - val_accuracy: 0.9902
Epoch 5/10
80
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
81
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
lOMoARcPSD|45333583
www.BrainKart.com
Result:
Thus a python program to implement character recognition using CNN
was implemented and executed successfully.
82
https://play.google.com/store/apps/details?id=info.therithal.brainkart.annauniversitynotes
Click on Subject/Paper under Semester to enter.
Professional English Discrete Mathematics Environmental Sciences
Professional English - - II - HS3252 - MA3354 and Sustainability -
I - HS3152 GE3451
Digital Principles and
Statistics and Probability and
Computer Organization
Matrices and Calculus Numerical Methods - Statistics - MA3391
- CS3351
- MA3151 MA3251
3rd Semester
1st Semester
4th Semester
2nd Semester
Deep Learning -
AD3501
Embedded Systems
Data and Information Human Values and
and IoT - CS3691
5th Semester
7th Semester
8th Semester
Open Elective-1
Distributed Computing Open Elective 2
- CS3551 Project Work /
Elective-3
Open Elective 3 Intership
Big Data Analytics - Elective-4
CCS334 Open Elective 4
Elective-5
Elective 1 Management Elective
Elective-6
Elective 2
All Computer Engg Subjects - [ B.E., M.E., ] (Click on Subjects to enter)
Programming in C Computer Networks Operating Systems
Programming and Data Programming and Data Problem Solving and Python
Structures I Structure II Programming
Database Management Systems Computer Architecture Analog and Digital
Communication
Design and Analysis of Microprocessors and Object Oriented Analysis
Algorithms Microcontrollers and Design
Software Engineering Discrete Mathematics Internet Programming
Theory of Computation Computer Graphics Distributed Systems
Mobile Computing Compiler Design Digital Signal Processing
Artificial Intelligence Software Testing Grid and Cloud Computing
Data Ware Housing and Data Cryptography and Resource Management
Mining Network Security Techniques
Service Oriented Architecture Embedded and Real Time Multi - Core Architectures
Systems and Programming
Probability and Queueing Theory Physics for Information Transforms and Partial
Science Differential Equations
Technical English Engineering Physics Engineering Chemistry
Engineering Graphics Total Quality Professional Ethics in
Management Engineering
Basic Electrical and Electronics Problem Solving and Environmental Science and
and Measurement Engineering Python Programming Engineering