0% found this document useful (0 votes)
38 views81 pages

Artificial Intelligence & Machine Learning Lab Manual (R22a6684)

The document is a laboratory manual for the Artificial Intelligence and Machine Learning course for B.Tech CSE students at Mallareddy College of Engineering & Technology. It outlines the vision, mission, program educational objectives, program specific outcomes, and program outcomes for the course, along with lab objectives and outcomes. Additionally, it includes a structured index of programming tasks and examples related to AI algorithms, Python programming, and machine learning techniques.

Uploaded by

vamshinathj123
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)
38 views81 pages

Artificial Intelligence & Machine Learning Lab Manual (R22a6684)

The document is a laboratory manual for the Artificial Intelligence and Machine Learning course for B.Tech CSE students at Mallareddy College of Engineering & Technology. It outlines the vision, mission, program educational objectives, program specific outcomes, and program outcomes for the course, along with lab objectives and outcomes. Additionally, it includes a structured index of programming tasks and examples related to AI algorithms, Python programming, and machine learning techniques.

Uploaded by

vamshinathj123
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/ 81

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ARTIFICIAL INTELLIGENCE
AND
MACHINE LEARNING
[R22A6684]
LABORATORY MANUAL

B. TECH CSE
(IIIYEAR–IISEM)

R22 REGULATION
(2024-25)

Name:

Rollno: Branch:

Section:

Year: Sem:

MALLAREDDY COLLEGE OF ENGINEERING & TECHNOLOGY


(AutonomousInstitution– UGC,Govt.ofIndia)
Recognizedunder2(f)and12(B)ofUGCACT1956
(AffiliatedtoJNTUH,Hyderabad,ApprovedbyAICTE-AccreditedbyNBA&NAAC–‘A’
Grade-ISO9001:2015Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad –
500100,TelanganaState,India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Vision
To acknowledge quality education and instill high patterns of discipline making the
students technologically superior and ethically strong which involves the
improvement in the quality of life in human race.

Mission
To achieve and impart holistic technical education using the best of infrastructure,
outstanding technical and teaching expertise to establish the students into competent
and confident engineers.
 Evolving the center of excellence through creative and innovative teaching learning
practicesforpromotingacademicachievementtoproduceinternationallyacceptedcompetiti
veand world class professionals.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1–ANALYTICALSKILLS
To facilitate the graduates with the ability to visualize, gather information, articulate, analyze,
solve complex problems, and make decisions. These are essential to address the challenges of
complex and computation intensive problems increasing their productivity.
PEO2–TECHNICALSKILLS
Tofacilitatethegraduateswiththetechnicalskillsthatpreparethemforimmediateemploymentandpurs
ue certification providing a deeper understanding of the technology in advanced areas of
computer science and related fields, thus encouraging pursuing higher education and research
based on their interest.
PEO3–SOFTSKILLS
To facilitate the graduates with the soft skills that include fulfilling the mission, setting goals,
showing self confidence by communicating effectively, having a positive attitude, get
involved in team-work, being a leader, managing their career and their life.
PEO4–PROFESSIONALETHICS
To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety
codes, and adapting them to technological advancements.

PROGRAM SPECIFIC OUTCOMES (PSOs)


After the completion of the course, B.Tech Computer Science and Engineering, the graduates
will have the following Program Specific Outcomes:

1. FundamentalsandcriticalknowledgeoftheComputerSystem:-
AbletoUnderstandtheworkingprinciples of the computer System and its components, Apply
the knowledge to build, asses, and analyze the software and hardware aspects of it.

2. The comprehensive and Applicative knowledge of Software Development: Comprehensive


skills of Programming Languages, Software process models, methodologies, and able to plan,
develop, test, analyze, and manage the software and hardware intensive systems in
heterogeneous platforms individually or working in teams.

3. Applications of Computing Domain & Research: Able to use the professional, managerial,
interdisciplinary skill set, and domain specific tools in development processes, identify their
search gaps, and provide innovative solutions to them.
PROGRAM OUTCOMES (POs)
Engineering Graduates should possess the following:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals,andanengineeringspecializationtothesolutionofcomplexengineeringproblems.

2. Problem analysis: Identify, formulate, review researchliterature, and analyze complex


engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3. Design / development of solutions: Design solutions for complex


engineeringproblemsanddesignsystemcomponentsorprocessesthatmeetthespecifiedneedswit
happropriateconsideration for the public health and safety, and the
cultural, societal, and environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and team work: Function effectively as an individual, and as member or leader in
diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
ARTIFICIAL AND MACHINE
LEARNING LABORATORY

LAB OBJECTIVES:
1. To provide student with an academic environment aware of various AI Algorithms.
2. To train Students with python programming as to comprehend, analyze, design and create AI
platforms and solutions for the real life problems.
3. Learn usage of Libraries for Machine Learning in Python
4. Demonstrate Dimensionality reduction methods
5. Describe appropriate supervised/Unsupervised learning algorithms for a given problem.

LAB OUTCOMES:
Upon completion of the course, students will be able to
1. Apply various AI search algorithms (uninformed, informed, heuristic, constraint satisfaction)
2. Understand the fundamentals of knowledge representation, inference.
3. Illustrate the applications of Python Machine Learning Libraries.
4. Apply Dimensionality reduction methods for Machine Learning Tasks.
5. Design and analyze various supervised/unsupervised learning mechanisms.

Introduction about lab Minimum System requirements:


Processors: Intel Atom® processor or Intel ®Core™ i3 processor.
Disk space: 1GB.
Operating systems: Windows*7 or later, macOS, and Linux.
Python*versions:2.7.X, 3.6.X., 3.8.X

About lab:
Python is a general purpose, high-level programming language; other high Level
languages you might have heard of C++,PHP, Java and Python. Virtually all
Modern programming languages make us of an Integrated Development Environment(IDE),
which allows the creation, editing, testing, and saving of programs and modules .In Python, the
IDE is called IDLE(like many items in the language, this is a reference to the British comedy
group Monty Python, and in this case, one of its members, Eric Idle).
Many modern languages use both processes. They are first compiled into a lower level
language, called byte code, and then interpreted by a program called a virtual machine. Python uses
both processes, but because of the way programmers interact with it, it is usually considered an
interpreted language Practical aspects are the key to understanding and conceptual visualization of
theoretical aspects covered in the laboratory.
General laboratory instructions

1. Students are advised to come to the laboratory at least 5minutes before(to the starting time),
those who come after 5minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis /program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,)filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in
the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN , and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results/ output in the lab observation
notebook, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
Maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students/ Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.

9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab/ class without permission
duringworkinghourswillbetreatedseriouslyandpunishedappropriately.

10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/ she must ensure the system/ seat is kept
properly.
INDEX

Week-No List of Programs Pg Nos.


1 a) Write a program to Implement Breadth First Search. 1
b) Write a program to Implement Depth First Search.

Write a program to implement Hill Climbing Algorithm 4


2
Write a program to implement A* Algorithm 8
3
Write a program to implement Tic- Tac -Toe game. 12
4
Write a program to implement Water Jug Problem. 15
5

a) Write a python program to import and export data using 17


6 Pandas library functions.
b) Demonstrate various data pre-processing techniques for a
given dataset.
a)Implement Dimensionality reduction using Principle Component
Analysis (PCA)method. 26
7 b) Write a Python program to demonstrate various Data
Visualization Techniques

8 a) Implement Simple and Multiple Linear Regression Models. 39


b) Develop Logistic Regression Model for a given dataset
9 Develop Decision Tree Classification model for a given dataset 55
and use it to classify a new sample.
a) Implement Naïve Bayes Classification in Python 62
10
b) Build KNN Classification model for a given dataset.
Build Artificial Neural Network model with back propagation 67
on a given dataset.
11
12 Write a python program to implement K-Means clustering Algorithm. 70
Artificial Intelligence and Machine Learning Lab 2024-2025
WEEK 1
a) Write a program to Implement Breadth First Search.

Program:

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): #functionforBFS


visited.append(node)
queue.append(node)

while queue: #Creating loop to visit each node


m=queue.pop(0)
print(m, end="")

for neighbor 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') #functioncalling

Output:

DEPT OF CSE Page 1


Artificial Intelligence and Machine Learning Lab 2024-2025

b) Write a program to Implement Depth First Search.

Program:
graph={

'5':['3','7'],

'3':['2','4'],

'7': ['8'],

'2':[],

'4': ['8'],

'8':[]

}
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 istheDepth-First Search"

dfs(visited,graph,'5')

Output:

DEPT OF CSE Page 2


Artificial Intelligence and Machine Learning Lab 2024-2025

Viva Questions:
1. Differences between Informed and Uninformed Search.
2. What are the Properties of Search Algorithms.
3. What is Breadth-First-Search.

FacultySignature
DEPT OF CSE Page 3
Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK-2

Write a program to implement Hill Climbing Algorithm

Program:
Import random

Def random Solution(tsp):

cities=list(range(len(tsp)))s

olution=[]

for i in range(len(tsp)):

randomCity = cities[random.randint(0, len(cities) - 1)]

solution.append(randomCity)

cities.remove(randomCity)

return solution

def routeLength(tsp,solution):

routeLength=0

for i in range(len(solution)):

routeLength+=tsp[solution[i-1]] [solution[i]]

return routeLength

def getNeighbours(solution):

neighbours=[]

for i in range(len(solution)):

for j in range(i+1, len(solution)):

neighbour = solution.copy()

neighbour[i] = solution[j]

DEPT OF CSE Page 4


Artificial Intelligence and Machine Learning Lab 2024-2025

neighbour[j] =solution[i]

neighbours.append(neighbour)r

eturn neighbours

def getBestNeighbour(tsp, neighbours):

bestRouteLength=routeLength(tsp,neighbours[0])

bestNeighbour=neighbours[0]

for neighbour in neighbours:

current RouteLength=routeLength (tsp,neighbour)

if current RouteLength< best RouteLength:

best RouteLength = current RouteLength

best Neighbour= neighbour

return bestNeighbour,bestRouteLength

def hillClimbing(tsp):

current Solution = randomSolution(tsp)

current RouteLength=routeLength(tsp,currentSolution)

neighbours= get Neighbours(currentSolution)

bestNeighbour,best Neighbour RouteLength=getBestNeighbour(tsp,neighbours)

while best Neighbour RouteLength<current RouteLength:

current Solution = best Neighbour current

RouteLength=best Neighbour Route Length

neighbours=getNeighbours(currentSolution)

best Neighbour, best Neighbour RouteLength=getBestNeighbour(tsp,neighbours)

return current Solution,current RouteLength

DEPT OF CSE Page 5


Artificial Intelligence and Machine Learning Lab 2024-2025

def main():

tsp=[

[0,400,500,300],

[400,0,300,500],

[500,300,0,400],

[300, 500,400,0]
]

Print (hillClimbing(tsp))
if name

=="main":main()

DEPT OF CSE Page 6


Artificial Intelligence and Machine Learning Lab 2024-2025

Viva questions
1. What is hill climbing in artificial intelligence?
2. What are the different types of hill-climbing algorithms?
3. What is the problem of local maxima in hill climbing?

FacultySignature

DEPT OF CSE Page 7


Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK 3: Write a program to implement A* Algorithm


Aim:
Write a program to implement A*Algorithm

Program:
From collections import deque

Class Graph:
def init (self, adjac_lis):
self.adjac_lis=adjac_lis

def get_neighbors(self,v):
return self.adjac_lis[v]

#This is heuristic function which is having equal values for all nodes def
h (self,n):
H ={
'A':1,
'B':1,
'C':1,
'D':1
}

return H[n]

def a_star_algorithm (self, start, stop):


#In this open_lst is a list of nodes which have been visited, but who's
#neighbours haven't all been always inspected, It starts off with the start#
node
#And closed_lst is a list of nodes which have been visited#
and who's neighbors have been always inspected
open_lst=set([start])
closed_lst=set([])

#poo has present distances from start to all other nodes#


the default value is+infinity
poo={}poo[start]=0

#par contains an adjac mapping of all nodes


par={}
par[start]=start
while len(open_lst) > 0:
n=None

DEPT OF CSE Page 8


Artificial Intelligence and Machine Learning Lab 2024-2025

# it will find a node with the lowest value of f()–


for v in open_lst:
if n==None or poo[v]+self.h(v)<poo[n] +self.h (n):
n=v;

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

# if the current node is the stop # then


we start again from start
if n==stop:
reconst_path=[]
while par[n]!=n:
reconst_path.append(n)
n=par[n]
reconst_path.append(start)r

econst_path.reverse()

print('Path found: {}'.format(reconst_path))


return reconst_path

#for all the neighbors of the current node do


for (m,weight) in self.get_neighbors(n):
#if the current node is not present in both open_lst and closed_lst
#add it to open_lst and note nasit'spar
if m not in open_lst and m not in closed_lst:
open_lst.add(m)
par[m] =n
poo[m]=poo[n]+weight

#otherwise, check if it's quicker to first visit n, then m


# and if it is, update par data and poo data
#and if the node was in the closed_lst, move it to open_lstelse:
if poo[m] > poo[n] + weight:
poo[m] = poo[n] + weight
par[m]=n

if m in closed_lst:
closed_lst.remove(m)
open_lst.add(m)

DEPT OF CSE Page 9


Artificial Intelligence and Machine Learning Lab 2024-2025

#remove n from the open_lst, and add it to


closed_lst # because all of his neighbors were
inspected open_lst.remove(n)
closed_lst.add(n)

print('Path does not exist!')


return None
adjac_lis={
'A':[('B', 1),('C',3),('D',7)],
'B':[('D',5)],
'C':[('D',12)]
}
graph1 = Graph (adjac_lis)
graph1.a_star_algorithm('A','D')

Output:

DEPT OF CSE Page10


Artificial Intelligence and Machine Learning Lab 2024-2025

Viva Questions:
1. What is Best First Search?
2. Explain Heuristic Function?
3. Explain A*Search.
.

DEPT OF CSE Page11


FacultySignature
Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK 4
Write a program to implement Tic-Tac-Toe game
Aim:
Write a program to implement Tic-Tac-Toe game.
Program:
Import os
import
time

board=['','','','','','','','','','']
player =1

########win Flags##########
Win =1
Draw =-1
Running=0
Stop =
1#########################
##
Game=Runnin
gMark='X'

#This Function Draws Game


Board def DrawBoard():
print("%c|%c|%c"%(board[1],board[2],board[3]))
print(" | | ")
print("%c|%c|%c"%(board[4],board[5],board[6]))
print(" | | ")
print("%c|%c|%c"%(board[7],board[8],board[9]))
print(" ||")

#This Function Checks position is empty or not


def CheckPosition(x):
if(board[x]==''):
return True
else:
return False

#This Function Checks player has won or not


def CheckWin():
global Game
#Horizontal winning condition
if(board[1] ==board[2]and board[2] ==board[3]andboard[1]!=''):

DEPT OF CSE Page12


Game=Win
Artificial Intelligence and Machine Learning Lab 2024-2025

elif(board[4]==board[5]and board[5] ==board[6] and board[4]!=''):


Game=Win
elif(board[7]==board[8]and board[8] ==board[9]and board[7]!=''):
Game=Win
#Vertical Winning Condition
elif(board[1]==board[4]and board[4] ==board[7] and board[1]!=''):
Game=Win
elif(board[2]==board[5]and board[5] ==board[8] and board[2]!=''):
Game=Win
elif(board[3]==board[6]and board[6] ==board[9] andboard[3]!=''):
Game=Win
#Diagonal Winning Condition
elif(board[1]==board[5]and board[5] ==board[9] and board[5]!=''):
Game=Win
elif(board[3]==board[5]and board[5] ==board[7] and board[5]!=''):
Game=Win
#Match Tie or Draw Condition
elif(board[1]!=''andboard[2]!=''andboard[3]!=''andboard[4]!=''andboard[5]!=''and
board[6]!=''and board[7]!=''and board[8]!=''andboard[9]!=''):
Game=Dra
welse:
Game=Running
print("Tic-Tac-Toe Game ")
print("Player1[X]---Player2[O]\n")
print
()pri
nt()
print("PleaseWait...")
time.sleep(3)
while(Game==Running)
:
os.system('cls')
Draw Board()
if(player%2!=0):
print("Player1'schance"
)Mark='X'
else:
print("Player2'schance"
)Mark='O'
choice=int(input("Enter the position between[1-9] where you want to mark:"))
if(Check Position(choice)):
board[choice]=Markplayer+=1
CheckWin()
os.system('cls')
DrawBoard()
if(Game==Draw
):

DEPT OF CSE Page13


print("Game Draw")
Artificial Intelligence and Machine Learning Lab 2024-2025

elif(Game==Win):
player-=1

if(player%2!=0
):
print("Player1Won"
)
else:
print("Player2Won")

Output:

DEPT OF CSE Page14


FacultySignature
Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK 5
Write a program to implement Water Jug Problem

Aim:

Write a program to implement Water Jug Problem?

Program:

#This function is used to initialize the


#dictionary elements with a default
value. from collections import default
dict

#jug1andjug2containthevalue
#for max capacity in respective jugs
#and aim is the amount of water to be
measured.
jug1,jug2,aim=4,3,2

#Initialize dictionary
with #default value as
false.
visited=default dict (lambda:False)

# Recursive function which prints


the
# Intermediate steps to reach the
final
#solution and return Boolean value
# (True if solution is possible, otherwise False).
# amt1 and amt2 are the amount of water present
#in both jugs at a certain point of time.
Def waterJugSolver(amt1,amt2):

#Checks for our goal


and #returns true if
achieved.
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print (amt1,amt2)
return True

#Checks if we have already visited the


# combination or not. If not, then it proceeds
further. If visited[(amt1,amt2)]== False:

DEPT OF CSE Page15


print(amt1,amt2)
Artificial Intelligence and Machine Learning Lab 2024-2025

#Changes the Boolean value of


#the combination as it is
visited. visited[(amt1,amt2)]=
True
#Check for all the 6 possibilities and
#see if a solution is found in any one of them.

return (waterJugSolver(0,amt2)or
waterJugSolver(amt1,0)orwaterJugSolver(jug1,amt2)orwaterJugSolver(amt1,j
ug2)orwaterJugSolver(amt1 + min(amt2, (jug1-amt1)),amt2-min(amt2,(jug1-
amt1)))or waterJugSolver(amt1 - min(amt1, (jug2-amt2)),amt2+
min(amt1,(jug2-amt2))))

#Return False if the combination is


#already visited to avoid repetition
otherwise #recursion will enter an infinite
loop.
else:
return False

print("Steps:")

# Call the function and pass the


#initial amount of water present in both
jugs. waterJugSolver(0,0)

Output:

FacultySignature

DEPT OF CSE Page16


Artificial Intelligence and Machine Learning Lab 2024-2025

Week 6
Write a python program to import and export the data using pandas library
1. Manual Function
Go to Google Page and find www.kaggle.com.Select Datasets and find Titanic dataset, then
download train.csvfile and save it to desktop.
1. Read a CSV file
import pandas as pd
url='C:/Users/MRCET1/Desktop/train.csv'
dataframe=pd.read_csv(url)dataframe.head(5)

2. Write a CSVfile
Import pandas as pd
marks_data=pd.DataFrame({'ID':{0:23,1:43,2:12,3:13,4:67,5:89},'NAME':{0:'Ram',1
:'Deep',2:'Yash',3:'Arjun',4:'Aditya',5:'Divya'},'Marks':{0:89,1:92,2:45,3:78,4:56,5:76},'Grade':{0:'
b',1:'a',2:'f',3:'c',4:'e',5:'c'}})

filename='C:/Users/MRCET1/Desktop/Marksdata.
xlsx'marks_data.to_excel(filename)
print('Data frame written to Excel')

3. Read an Excel File import pandas as


pdurl='C:/Users/MRCET1/Desktop/train.csv.xls'datafra
me=pd.read_excel(url)dataframe.head(5)

4. Write an Excel file

importpandas as pd
marks_data=pd.DataFrame({'ID':{0:23,1:43,2:12,3:13,4:67,5:89},'NAME':{0:'Ram',1
:'Deep',2:'Yash',3:'Arjun',4:'Aditya',5:'Divya'},'Marks':{0:89,1:92,2:45,3:78,4:56,5:76},'Grade':{
0
:'b',1:'a',2:'f',3:'c',4:'e',5:'c'}})
filename='C:/Users/MRCET1/Desktop/Marksdata.csv'marks_data.to_csv(filename)

print('Data frame written to CSV');

DEPT OF CSE Page17


mm
Artificial Intelligence and Machine Learning Lab 2024-2025

Output:

DEPT OF CSE Page18


Artificial Intelligence and Machine Learning Lab 2024-2025

FacultySignature

DEPT OF CSE Page19


Artificial Intelligence and Machine Learning Lab 2024-2025

b) Demonstrate various data pre-processing techniques for a given dataset


1. Detecting and Handling Missing values
1. Type conversion
2. Detecting and Treating Outliers
3. Scaling
4. Dimensionality Reduction

import numpy as np import


panda sas pd
import matplotlib.pyplot as plt
import seaborn as sns
df=pd.read_csv('C:/Users/MRCET1/Desktop/train.csv')
df.head(5)

df.shape # to check dimensions of datadf.info()#

to list features of data

df.describe()#to display mean,variance, count and other details of data df.columns #to

display column names

df.dtypes #to display data types of columns

#To display the total count of null values in each column

column_names=df.columns
for column in column_names:
print(column+'-'+str(df[column].isnull().sum()))

# To display the count of passengers survived

df.Survived.value_counts()

DATAVISUALIZATION

# To draw a bar graph to visualize survival data import


matplotlib.pyplotas plt
plt=df.Survived.value_counts().plot.bar(x='Survivedornot',y='PassengerCount',rot=0)

#To see probability of survival based on Passenger Class


plt=df.Pclass.value_counts().sort_index().plot.bar(x='PClass',y='SurvivalProbability',rot=0)

#To display Class wise survival count


df[['Pclass','Survived']].groupby('Pclass').count()

df[['Pclass','Survived']].groupby('Pclass').mean().Survived.plot.bar(x='PClass',y='SurvivalProbability
',rot=0)

DEPT OF CSE Page20


mm
Artificial Intelligence and Machine Learning Lab 2024-2025

#From the results, we can say that,1stclass has high chance of surviving than the other two classes.

# To display survival count based on


Genderdf.Sex.value_counts().sort_index().plot.bar(x='Sex',y='Passenger Count',rot=0)
plt.set_xlabel('Sex')
plt.set_ylabel('Passengercount')

IDENTIFYING IRRELEVANT AND REDUNDANT

FEATURES Remove unnecessary columns


We can remove' Ticket' and 'PassengerId', as they don't contribute to target class.
Remove 'Cabin' as ith as a lot of missing values in both train and test data

df= df.drop(columns=['Ticket', 'PassengerId', 'Cabin'])


df.head()

#Map 'Sex' and 'Embarked' to numerical values. df['Sex']


=df['Sex'].map({'male':0,'female':1})
df['Embarked'] = df['Embarked'].map({'C':0, 'Q':1, 'S':2})
df.head()

#Preprocess 'Name'
#Extarct title from name of the passenger and categorize them. #Drop the
column 'Name'
df['Title'] = df.Name.str.extract(' ([A-Za-z]+)\.',expand=False)
df=df.drop(columns='Name')
df.Title.value_counts().plot.bar(x='Title',y=0,rot=0)

#Combines ome of the classes and group all the rare classes into 'Others'.
df['Title'] = df['Title'].replace(['Dr', 'Rev', 'Col', 'Major', 'Countess', 'Sir', 'Jonkheer', 'Lady',
'Capt','Don'],'Others')
df['Title'] =df['Title'].replace('Ms','Miss')
df['Title']=df['Title'].replace('Mme','Mrs)df['Title']
=df['Title'].replace('Mlle','Miss)
df.Title.value_counts().sort_index().plot.bar(x='Titl
e',y='Passengercount')

df[['Title','Survived']].groupby('Title').mean().Survived.plot.bar(x='Title',y='SurvivalProbability
')

#Map 'Title 'to numerical values


df['Title']=df['Title'].map({'Master':0,'Miss':1,'Mr':2,'Mrs':3,'Others':4})
df.head()

#Correlation between columns


corr_matrix=df.corr()
import matplotlib.pyplot as
pltplt.figure(figsize=(9,8))
sns.heatmap(data=corr_matrix,cmap='BrBG',annot=True,linewidths=0.2)

DEPT OF CSE Page21


Artificial Intelligence and Machine Learning Lab 2024-2025
#Handling missing values
df.isnull().sum()

#Impute 'Embarked' with it's majority class.

df['Embarked'].isnull().sum()

#There are two null values in the column 'Embarked'. Let's impute them using majority class. #The
majority class is'S'. Impute the unkonown values (NaN) using 'S'
df['Embarked'] = df['Embarked'].fillna(2)
df.head()

#Missingvalues-'Age'
#Let's find the columns that are useful to predict
thevalueofAge.corr_matrix=df[['Pclass','Sex','Age','SibSp','Parch','Fare']].corr()

plt.figure(figsize=(7,6))
sns.heatmap(data=corr_matrix,cmap='BrBG',annot=True,linewidths=0.2)

#Age is not correlated with 'Sex' and 'Fare'. So,we don't consider these two columns while imputing'
Sex'.
#'Pclass', 'SibSp' and 'Parch' are negatively correlated with 'Sex'.
#Let's fill Age with the median age of similar rows from 'Pclass', 'SibSp' and 'Parch'
.#If there are no similar rows, fill the age with the median age of total dataset.
NaN_indexes=df['Age'][df['Age'].isnull()].index

for i in NaN_indexes:
pred_age = df['Age'][((df.SibSp == df.iloc[i]["SibSp"]) & (df.Parch == df.iloc[i]["Parch"])
&(df.Pclass==df.iloc[i]["Pclass"]))].median()
ifnotnp.isnan(pred_age):
df['Age'].iloc[i] = pred_ageelse:
df['Age'].iloc[i] = df['Age'].median()

df.isnull().sum()

#There are no missing values in the


data.df.head(20)

DEPT OF CSE Page22


Artificial Intelligence and Machine Learning Lab 2024-2025

Output:

DEPT OF CSE Page23


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page24


Artificial Intelligence and Machine Learning Lab 2024-2025

Viva Questions
2. What is Machine learning?
3. What is the main key difference between supervised and unsupervised machine
learning?
4. What are the Different Types of Machine Learning?
5. What is numpy in python?

FacultySignature

DEPT OF CSE Page25


mm
Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK-7
a): Implement Dimensionality reduction using Principle ComponentAnalysis(PCA)method.

import numpy asnp #linear algebra


import pandas as pd #data processing, CSV fileI/O (e.g.pd.read_csv) import
seaborn as sns
import mat plotlib.pyplot as plt
%matplotlib in lines ns.set_theme(style="darkgrid")

Now, were add the data and check out how the data looks
data=pd.read_csv("C:/Users/MRCET1/Desktop/stars.csv")
data.head(5)

Now, let us check the shape of the dataset. Before proceeding with the problem
statement, understanding the data set is very important.
data.shape

The attributes of the data are


data.info()

Now, we check for missing values.


data.isnull().sum()

some analysis of the data distribution.


a= pd.DataFrame(data['Star color'].value_counts())
plt.figure(figsize=(8,6))
sns.barplot(data=a,x='Starcolor',y=a.index,palette='Spectral')
plt.title("StarColorAnalysis")

Star Spectral Class Analysis:

a= pd.DataFrame(data['Spectral Class'].value_counts())
plt.figure(figsize=(8,6))
sns.barplot(data=a,x='SpectralClass',y=a.index,palette='rainbow')plt.title("Star
SpectralClassAnalysis")
StarType Analysis
a =pd.DataFrame(data['Star type'].value_counts())

DEPT OF CSE Page26


Artificial Intelligence and Machine Learning Lab 2024-2025
plt.figure(figsize=(10,8))

plt.pie(data=a,x='Startype',labels=a.index,autopct='%1.1f%%')
plt.title("PercentageDistributionofStarType")
m

Corrlation Analysis
matrix=data.corr()
mask=np.zeros_like(matrix,dtype=float)mask[np.triu
_indices_from(mask)]=Trueplt.figure(figsize=(11,6)
)
sns.heatmap(matrix,annot=True,cmap='viridis',annot_kws={'size':10},mask=mask)plt.title("
CorrelationAnalysis")
plt.show()

from sklearn import preprocessing


#label_encoder
label_encoder=preprocessing.LabelEncoder()

Now, we apply the encoder to the dataset.

data['Color_Label']=label_encoder.fit_transform(data['Star color'])
data['Spectral_Class_Label']=label_encoder.fit_transform(data['Spec tralClass'])data.head()

print("Original Colours:")
print(data['Starcolor'].unique())print("Labels:")
print(data['Color_Label'].unique())

Now,we split the dataset into X and y.

y=data["Spectral_Class_Label"].values
X=data.drop(labels=['Spectral_Class_Label','Starcolor','SpectralClass'],axis=1).values

Applying Standard Scaler Normalization


from sklearn.preprocessing import Standard Scalersc= StandardScaler()
X=sc.fit_transform(X)
Implementation of PCA
from sklearn.decomposition import PCApca
=PCA()
X=pca.fit_transform(X)

DEPT OF CSE Page27


Artificial Intelligence and Machine Learning Lab 2024-2025

explained_variance =
pca.explained_variance_ratio_explained_variance

First, we train the Classifier model by taking the two top features. Inbuilt Random Forest Classifier is
used. mm
from sklearn. Decomposition import PCA
pca2 = PCA(n_components=2)X_2=pca2.fit_transform(X)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test =train_test_split(X_2,y,test_size=0.2,random_state=5)
From sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(max_depth=2,
random_state=0)classifier.fit(X_train,y_train)
#PredictingtheTestsetresultsy_pred =
classifier.predict(X_test)from
sklearn.metrics importaccuracy_score
print('Accuracy: '
,accuracy_score(y_test,y_pred))

Number of principal components=3.

from sklearn.decomposition import PCApca3=


PCA(n_components=3)
X_3=pca3.fit_transform(X)
X_train,X_test,y_train,y_test =train_test_split(X_3,y,test_size=0.2,random_state=5)
classifier =
RandomForestClassifier(max_depth=2,random_state=0)classifier.fit(X_train,y_train)
#PredictingtheTestsetresultsy_pred=classi
fier.predict(X_test)
print('Accuracy: ',accuracy_score(y_test,y_pred))

number of principal components=4.


from sklearn.decomposition import PCApca4=
PCA(n_components=4)
X_4=pca4.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_4, y, test_size=0.2,
random_state=5)classifier=
RandomForestClassifier(max_depth=2,random_state=0)classifier.fit(X_train,y_train)
# Predicting the Test set
resultsy_pred=classifier.predict(X_test)
print('Accuracy: ',accuracy_score(y_test,y_pred))

DEPT OF CSE Page28


mm
Artificial Intelligence and Machine Learning Lab 2024-2025

Output:

DEPT OF CSE Page29


Artificial Intelligence and Machine Learning Lab 2024-2025

Viva Questions
1. What is PCA?
2. What is Dimensionality Reduction?
3. What is CSV file?
4. Compare PCA and LDA

FacultySignature

DEPT OF CSE Page30


Artificial Intelligence and Machine Learning Lab 2024-2025

b) Write a python program to demonstrate various Data Visualization Techniques.


import pandas as pd
import matplotlib.pyplot as plt import
seaborn as sns
#Downdload dataset and read it

DEPT OF CSE Page31


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page32


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page33


mm
Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page34


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page35


Artificial
mm Intelligence and Machine Learning Lab 2024-2025

Viva Questions
1. What is meant by data visualization in machine learning?
2. What are the various types of Data Visualization Approaches?
3. List some of the Data Visualization Libraries Available in Python
4. List some of Feature Selection Techniques in supervised learning.

DEPT OF CSE Page36


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page37


Artificial Intelligence and Machine Learning Lab 2024-2025

Faculty Signature

DEPT OF CSE Page38


Artificial Intelligence and Machine Learning Lab 2024-2025
WEEK-8:
a)Implement Simple and Multiple Linear Regression Models

1. Implementation of Linear Regression


import numpy as np
import matplotlib.pyplot as plt def estimate_coef(x, y):
# number of observations/points n = np.size(x)

# mean of x and y vector m_x = np.mean(x)


m_y = np.mean(y)

# calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) - n*m_y*m_x


SS_xx = np.sum(x*x) - n*m_x*m_x

# calculating regression coefficients b_1 = SS_xy / SS_xx


b_0 = m_y - b_1*m_x return (b_0, b_1)

def plot_regression_line(x, y, b):


# plotting the actual points as scatter plot plt.scatter(x, y, color = "m", marker = "o", s = 30)

# predicted response vector y_pred = b[0] + b[1]*x


# plotting the regression line plt.plot(x, y_pred, color = "g")

# putting labels plt.xlabel('x') plt.ylabel('y') # function to show plot plt.show()


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]))

# plotting regression line plot_regression_line(x, y, b)

if name == " main ": main()

DEPT OF CSE Page39


Artificial Intelligence and Machine Learning Lab 2024-2025
2. Multiple linear regression
import numpy as np
import matplotlib.pyplot as plt

def estimate_coef(x, y):


# number of observations/points n = np.size(x)
# mean of x and y vector m_x = np.mean(x)
m_y = np.mean(y)

# calculating cross-deviation and deviation about x SS_xy = np.sum(y*x) - n*m_y*m_x


SS_xx = np.sum(x*x) - n*m_x*m_x

# calculating regression coefficients b_1 = SS_xy / SS_xx


b_0 = m_y - b_1*m_x return (b_0, b_1)
def plot_regression_line(x, y, b):
# plotting the actual points as scatter plot plt.scatter(x, y, color = "m",marker = "o", s = 30)

# predicted response vector y_pred = b[0] + b[1]*x

# plotting the regression line plt.plot(x, y_pred, color = "g")

# putting labels plt.xlabel('x') plt.ylabel('y')

# function to show plot plt.show()

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]))

# plotting regression line plot_regression_line(x, y, b)


if name == " main ":
main()

DEPT OF CSE Page40


Artificial Intelligence and Machine Learning Lab 2024-2025

Output:

DEPT OF CSE Page41


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page42


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page43


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page44


Artificial Intelligence and Machine Learning Lab 2024-2025

Faculty Signature

DEPT OF CSE Page45


Artificial Intelligence and Machine Learning Lab 2024-2025
b):DevelopLogisticRegression Modelforagiven dataset.
import matplotlib.pyplot as plt
importnumpyasnp
fromsklearn.linear_modelimportLogisticRegression
fromsklearn.metricsimportclassification_report,confusion_matrix

x=np.arange(10).reshape(-1,1)
y=np.array([0,0, 0, 0, 1, 1,1, 1, 1, 1])
xy

model = LogisticRegression(solver='liblinear',

random_state=0)model.fit(x,y)

LogisticRegression(C=1.0,class_weight=None,dual=False,fit_intercept=True,intercept_scaling=1,
l1_ratio=None,max_iter=100,
multi_class='warn',n_jobs=None,penalty='l2',random_
state=0,solver='liblinear',tol=0.0001,verbose=0,warm_
start=False)

model=LogisticRegression(solver='liblinear',random_state=0).fit(x,y)model.classes
_model.intercept_model.coef_
model.predict_proba(x)#model.predict(x)

DEPT OF CSE Page46


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions
1. What ismeantbylinearregression?

2. Listsomeofthesupervisedlearningalgorithms

3. List thetypesoflinearregressionanddefineeach

DEPT OF CSE Page47


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page48


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page49


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page50


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page51


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page52


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page53


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions

1. Whatismeantbylogisticregression?
2. Listthetypesoflogisticregressionandexplain each
3. Listtheclassificationmodelinmachinelearning
4. WhataretheStepsinvolvedin LogisticRegression

Faculty Signature

DEPT OF CSE Page54


Artificial Intelligence and Machine Learning Lab 2024-2025
WEEK-9:DevelopDecisionTreeClassificationmodelforagivendatasetanduseittoclassifyanew
sample.
1.Implementation ofDecision treeclassification
# Importing the
requiredpackagesimportnumpyasnp
importpandasaspd
fromsklearn.metricsimportconfusion_matrix
from sklearn.model_selection
importtrain_test_splitfromsklearn.treeimport
DecisionTreeClassifier
fromsklearn.metricsimportaccuracy_score
fromsklearn.metricsimportclassification_report

# Function importing
Datasetdefimportdata():
balance_data =
pd.read_csv('https://archive.ics.uci.edu/ml/machine-
learning-'+'databases/balance-scale/balance-scale.data',
sep=',',header=None)

#Printingthedataswetshape
print ("Dataset Length: ",
len(balance_data))print("DatasetShape:",balance_dat
a.shape)

# Printing the dataset


obseravtionsprint("Dataset:",balance_data.
head())
returnbalance_data
# Function to split the dataset
defsplitdataset(balance_data):
# Separating the targetvariable

DEPT OF CSE Page55


Artificial Intelligence and Machine Learning Lab 2024-2025
X = balance_data.values[:,1:5]
Y=balance_data.values[:,0]

#Splitting thedataset intotrainandtest


X_train,X_test,y_train,y_test=train_test_split(X,Y,test_size
=0.3,random_state=100)
returnX,Y,X_train,X_test,y_train,y_test

#Functionto performtraining withginiIndex.


def train_using_gini(X_train, X_test, y_train):#
Creatingtheclassifierobject
clf_gini=DecisionTreeClassifier(criterion="gini",
random_state = 100,max_depth=3,
min_samples_leaf=5)#Performingtraining
clf_gini.fit(X_train,y_train)returnclf_
gini
# Decision tree with
entropyclf_entropy=DecisionTreeClassifier(
criterion = "entropy", random_state =
100,max_depth=3,min_samples_leaf=5)

#Performingtrainingclf_entropy.fit(X_trai
n,y_train)returnclf_entropy

# Function to make
predictionsdefprediction(X_test,clf_object)
:

# Predicton on test with giniIndexy_pred =


clf_object.predict(X_test)print("Predictedval
ues:")print(y_pred)
returny_pred

# Function to calculate
accuracydefcal_accuracy(y_test,y_pred):

print("Confusion Matrix:
",confusion_matrix(y_test,y_pred))

DEPT OF CSE Page56


Artificial Intelligence and Machine Learning Lab 2024-2025
print ("Accuracy :
",accuracy_score(y_test,y_pred)*100)

print("Report : ", classification_report(y_test,


y_pred))#Drivercode
defmain():

#BuildingPhasedata=importdata()
X, Y, X_train, X_test, y_train, y_test =
splitdataset(data)clf_gini=train_using_gini(X_train,X_test,y_train
)

clf_entropy=tarin_using_entropy(X_train,X_test,y_train)#Operationa

lPhase
print("ResultsUsingGiniIndex:")

#Predictionusinggini
y_pred_gini=prediction(X_test,clf_gini)cal_accura
cy(y_test,y_pred_gini)

print("ResultsUsingEntropy:")#Predictio
nusingentropy
y_pred_entropy = prediction(X_test,
clf_entropy)cal_accuracy(y_test,y_pred_entropy)

#Calling mainfunction
if name=="main":main()

DEPT OF CSE Page57


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page58


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page59


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions
1. WhatisDecisionTrees-ID3in machinelearning?
2. Whatismeantbyinformationgain?
3. Whatarethemajorissuesindecisiontreelearning?
4. Howdoesdecisiontreehelpindecisionmaking?

Faculty Signature

DEPT OF CSE Page60


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page61


Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK-10 a):ImplementationofNaïveBayesclassifieralgorithm
#Importingthedataset
dataset=pd.read_csv(&#39;titanic.csv&#39;)
X=dataset.iloc[:,[2,3]].valuesy=dataset.il
oc[:,-1].values
#SplittingthedatasetintotheTrainingsetand Test set
from sklearn.model_selectionimporttrain_test_split
X_train,X_test,y_train,y_test =train_test_split(X,y,test_size
=0.20,random_state=0)
#FeatureScaling
from sklearn.preprocessing importStandardScaler sc
=
StandardScaler()X_train=sc.fit_transform(X_train)X
_test
=sc.transform(X_test)
# Training the Naive Bayes model on theTraining
set from sklearn.naive_bayesimportGaussianNB
classifier =
GaussianNB()classifier.fit(X_train,y_tra
in)#PredictingtheTestsetresults
y_pred = classifier.predict(X_test)# Making
theConfusionMatrix
from sklearn.metrics import confusion_matrix,accuracy_score ac = accuracy_score(y_test,y_pred)cm=
confusion_matrix(y_test,y_pred

DEPT OF CSE Page62


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page63


mm

Artificial Intelligence and Machine Learning Lab 2024-2025


b):ImplementationofK-nearestNeighbour

import numpy as np importpandasas pd


from sklearn.model_selectionimport
train_test_split
fromsklearn.neighborsimport
KNeighborsClassifierimportmatplotlib.
pyplotaspltimportseabornassns
df=pd.read_csv('data.csv')y=
df['diagnosis']
X=df.drop('diagnosis',axis=1)
X = X.drop('Unnamed: 32', axis=1)X =
X.drop('id',axis=1)

#SeparatingthedependentandindependentvariableX_train,X_test,y_tra
in,y_test=train_test_split(X,y,
test_size=0.3,random_state=0)

# Splitting the data into training and testing dataK=[]


training =
[]test=[]scores={}
fork inrange(2,21):
clf =
KNeighborsClassifier(n_neighbors=k)clf.fit(X_train,
y_train)
training_score=clf.score(X_train,y_train)test_score =
clf.score(X_test, y_test)
K.append(k)training.append(training_score)

test.append(test_score)
scores[k] = [training_score,
test_score]ax=sns.stripplot(training)

ax.set(xlabel='valuesofk',ylabel='TrainingScore')plt.show()
ax=sns.stripplot(test)
ax.set(xlabel='valuesofk',ylabel='TestScore'

plt.show()
plt.scatter(K,training,color='k')plt.scatter(
K, test, color='g')plt.show()

DEPT OF CSE Page64


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page65


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions
1. Whatisnaiveinnaivebaye’sclassifier?
2. WriteanoteonSVM
3. GivetheformulaforBayes'Theorem
4. Listsomeoftheadvantagesanddisadvantagesofnaïvebayesclassifier

Faculty Signature

DEPT OF CSE Page66


mm

Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK-11:BuildArtificialNeuralNetworkmodelwithbackpropagationonagivendataset
Let’s first understand the term neural networks. In a neural
network,whereneuronsarefedinputswhichthenneuronsconsidertheweightedsum
over them and pass it by an activation function and passes out
theoutputtonextneuron.
Import numpy as np
X=np.array(([2,9],[1,5],[3,6]),dtype=float)
y=np.array(([92], [86],[89]),dtype=float)
X = X/np.amax(X, axis=0)# maximum of X
arraylongitudinallyy=y/100

#SigmoidFunctiondefsigmoid(x):return1/(1+
np.exp(-x))
# Derivative of Sigmoid
Functiondefderivatives_sigmoid(x):
returnx*(1-x)

#Variable initialization
epoch = 5# Setting training iterations lr =
0.1#Settinglearningrate
inputlayer_neurons=2
# number of features in data
sethiddenlayer_neurons= 3
# number of hidden layers
neuronsoutput_neurons=1
#number
ofneuronsatoutputlayer#weightandbiasinitia
lization
wh=np.random.uniform(size=(inputlayer_neurons,hiddenlayer_neurons))bh=
np.random.uniform(size=(1,hiddenlayer_neurons))
wout=np.random.uniform(size=(hiddenlayer_neurons,output_neurons))bout=
np.random.uniform(size=(1,output_neurons))
# draws a random range of numbersuniformlyofdim
x*yforiinrange(epoch):

#ForwardPropogationhinp1
=np.dot(X,wh)hinp=hinp1+bh
hlayer_act=sigmoid(hinp)
mm

outinp1 = np.dot(hlayer_act, wout)outinp=

DEPT OF CSE Page67


Artificial Intelligence and Machine Learning Lab 2024-2025

outinp1+bout

output=sigmoid(outinp)

# BackpropagationEO = y-
output
outgrad =
derivatives_sigmoid(output)d_output=EO*out
grad
EH=d_output.dot(wout.T)
# how much hidden layer wts contributed to
errorhiddengrad =
derivatives_sigmoid(hlayer_act)d_hiddenlayer=
EH*hiddengrad
# dotproduct of nextlayererror and currentlayeropwout +=
hlayer_act.T.dot(d_output)*lr
wh+=X.T.dot(d_hiddenlayer)*lr
print("-----------Epoch-",i+1,"Starts ---------- ")
print("Input: \n" + str(X))print("Actual
Output: \n" + str(y))print("Predicted
Output:\n",output)
print("-----------Epoch-",i+1,"Ends ---------- \n")
print("Input: \n" + str(X))print("Actual
Output: \n" + str(y))print("Predicted
Output:\n",output)

DEPT OF CSE Page68


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions
1. DefineANN
2. WhatarethetypesofArtificialNeuralNetworks?
3. ListsomeoftheApplicationsofArtificialNeuralNetworks

4. Whatisbackpropagationinneuralnetworks?

DEPT OF CSE Page69


Artificial Intelligence and Machine Learning Lab 2024-2025

WEEK-12:ImplementingK-meansClusteringAlgorithm.
# installations
#1.pipinstallscikit-learn
#2.pip installmatplotlib
# 3.pip install k-means-
constrained#4.pipinstallpandas
from
sklearn.datasetsimportmake_bl
obs
importmatplotlib.pyplotaspltfromk_means_
constrainedimport
KMeansConstrained import pandas as
pddf=pd.read_csv('student_clustering.csv')
X=df.iloc[:,:].values
km=KMeansConstrained(n_clusters=4,max_iter=500)y_means=km.fit
_predict(X)
plt.scatter(X[y_means==0, 0],X[y_means==0,1],
color='red')
plt.scatter(X[y_means == 1, 0], X[y_means == 1,
1],color='blue')
plt.scatter(X[y_means == 2, 0], X[y_means == 2,
1],color='green')
plt.scatter(X[y_means == 3, 0], X[y_means == 3,
1],color='yellow')plt.show()

DEPT OF CSE Page70


Artificial Intelligence and Machine Learning Lab 2024-2025

VivaQuestions

1. WhatisKNNinmachinelearning?

2. Why do weneedaK-NNAlgorithm?

3. WhatisKernelMethod?

4. ListsomeofthemajorKernelFunctioninSupportVectorMachine

Faculty Signature

DEPT OF CSE Page71


Artificial Intelligence and Machine Learning Lab 2024-2025

Exercise Programs

DEPT OF CSE Page72


Artificial Intelligence and Machine Learning Lab 2024-2025

DEPT OF CSE Page73

You might also like