Aitt PBL
Aitt PBL
WEEK - 2
Exp# 1 Week# 2 Date#
Aim :
Write a program to input graph and display adjacency nodes for a node given by user.
Program:
def adj(graph,ele):
return graph[ele]
graph={
"A":["B","C"],
"B":["A","C","E","D"],
"C":["A","B","D","E"],
"D":["B","C","E","F"],
"E":["B","C","D","F"],
"F":["E","F"]
}
ad=adj(graph,"B")
print("adjacent elements of B : ",ad)
Output:
adjacent elements of B : ['A', 'C', 'E', 'D']
Observation:
G
● raph is represented using dictionary
● H ere the adjacent nodes of the graph is stored as key value pairs in a
dictionary
● When we enter A’s node then it displaying BC
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Aim :
To demonstrate the operations of a queue data structure.
program:
def enqueue(queue,ele):
queue.append(ele)
def dequeue():
return queue.pop(0)
def size():
return len(queue)
queue=[]
print("Enter number of elements : ")
n=int(input())
print("Enter n elements to enqueue : ")
for i in range(0,n):
k=input()
enqueue(queue,k)
print("Queue elements : ",queue)
d=dequeue()
print("Dequeue element : ",d)
print(queue)
print("size of queue : ",size())
Output:
nter number of elements :
E
3
Enter n elements to enqueue :
2
1
A3CIL202 - AI Tools and Techniques Lab 22331A0597
4
Queue elements : ['2', '1', '4']
Dequeue element : 2
['1', '4']
size of queue : 2
Observation:
H
● ere we give input as any data type
● We can perform both insertion and deletion operations at both of its ends of the queue.
Aim :
To demonstrate the operations of a stack data structure.
program:
def push(stack,i):
stack.append(i)
def pop():
return stack.pop()
def size():
return len(stack)
stack=[]
print("Enter no of elements to push : ")
n=int(input())
print("Enter n elements to push : ")
for i in range(0,n):
k=input()
push(stack,k)
print("stack elements : ",stack)
p=pop()
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Output:
nter no of elements to push :
E
3
Enter n elements to push :
hi
hey
hello
stack elements : ['hi', 'hey', 'hello']
pop element : hello
Size of stack : 2
Observation:
I f we use get then it only retrieves the value
●
● Stack operations will perform at only one side
● Here we give any data type of elements as input
Aim :
Demonstrate Breadth-First Search (BFS) AI uninformed search algorithm.
Program:
q ueue =[]
vis =[]
def enqueue(val,q):
A3CIL202 - AI Tools and Techniques Lab 22331A0597
q .append(val)
def GetNode(c):
return graph[c]
def bfs(start):
enqueue(start,queue)
for i in queue:
if i not in vis:
for j in GetNode(i):
enqueue(j,queue)
vis.append(i)
graph={
"A":["B","C"],
"B":["A","C","D","E"],
"C":["A","B","D","E"],
"E":["B","C","D","F"],
"D":["B","C","E","F"],
"F":["D","E"]
}
bfs('A')
print(vis)
Output:
['A', 'B', 'C', 'D', 'E', 'F']
Observation:
● T he graph is represented as a dictionary where each key is a node and its
corresponding value is a list of neighboring nodes.
● Queue is used to represent the Breadth First Search.
● BFS explore all the neighbors in the present depth level and then moves to the next
depth level.
Aim :
Demonstrate Depth-First Search (DFS) AI uninformed search algorithm.
NONE
Program:
s tack=[]
vis=[]
def push(val,s):
s.append(val)
def pop(s):
return s.pop()
def get(val):
return graph[val]
def dfs(val):
push(val,stack)
while stack:
n=pop(stack)
if n not in vis:
vis.append(n)
for j in get(n):
push(j,stack)
graph={ "A":["B","C"], "B":["A","D"], "C":["A","E"], "D":["B","E"], "E":["C","D"] }
dfs('A')
print(vis)
Output:
['A', 'C', 'E', 'D', 'B']
Observation:
S
● tack is used to implement Depth First Search
● The vis set keeps track of visited nodes to avoid revisiting them.
● The graph is represented as a dictionary where each key is a node and its corresponding
value is a list of neighboring nodes.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 3
Exp# 6 Week# 3 Date#
Aim :
Calculate distance between two nodes in a graph using euclidean distance
Program:
import math
a=int(input())
b=int(input())
c=int(input())
d=int(input())
dis=math.sqrt(pow((d-b),2)+pow((c-a),2))
print('Distance between two points : ',dis)
Output:
2
3
4
5
Distance between two points : 2.8284271247461903
Observation:
● T
he Euclidean distance is calculated using the Pythagorean theorem, which is the
squarerootofthesumofthesquaresofthedifferencesbetweenthex-coordinatesand
the y-coordinates of the two nodes.
● In this program we use ** instead of pow().
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Aim :
Calculate distance between two nodes in a graph using manhattan distance.
program:
a =int(input())
b=int(input())
c=int(input())
d=int(input())
mdis=abs(d-b)+abs(c-a)
print("manhattan distance : ",mdis)
Output:
2
3
4
5
manhattan distance : 4
Observation:
I f we give non-integer value it will raise an value error
●
● The distance is calculated by using formula abs(x2-x1)+abs(y2-y1)
● We can use fabs instead of abs, But it returns float value
Aim :
Demonstrate Best-First Search (BFS) AI informed search algorithm.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
program:
import heapq
def bfs(graph,sc):
hq=[(0,sc)]
vis=set()
while hq:
s,d=heapq.heappop(hq)
if d not in vis:
vis.add(d)
for x,wt in graph[d]:
heapq.heappush(hq,(wt,x))
return list(vis)
graph={
'A':[('B',5),('C',7)],
'B':[('A',5),('D',4)],
'C':[('A',7),('E',6)],
'D':[('B',4),('E',2)],
'E':[('C',6),('D',2)]
}
sc='A'
res=bfs(graph,sc)
print(res)
Output:
['B', 'A', 'C', 'E', 'D']
Observation:
T
● he program can also calculate the negative costs.
● We can get an Index Error if the nodes are out of range.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 4
Exp 9 Week 4 Date
Aim :
Demonstrate various NumPy array creation, manipulation, and statistical functions.
dim:T
n he ndim property returns the number of dimensionof the DataFrame. ariables:
V
dtype:T he NumPy array object has a property called dtype that returns the arr(list),arr
data type of the array: 1(list),arr2(
reshape:Reshaping means changing the shape of an array.The shape of an list),arr3(li
array is the number of elements in each dimension. st)
Arrange():This function is used to create an arraywith a range of values.
add():this function is used when we want to compute the addition of two
arrays.
subtract(): this function is used when we want tocomputethedifferenceof
two array.
transpose():We can perform thesimplefunctionoftransposewithinoneline
by using transpose method of Numpy.
dot():D ot product of two arrays.
sin():T hismathematicalfunctionhelpsusertocalculatetrigonometricsinefor
all x
cos():This mathematical function helps usertocalculatetrigonometriccosine
for all x
tan():T hismathematicalfunctionhelpsusertocalculatetrigonometricsinefor
all x
sum():Thesum()function returns a number, the sumof all items in an iterable.
power():Arrayelementfromfirstarrayisraisedtothepowerofelementfrom
second element(all happens element-wise).
min():The min() method returns the smallest elementof an array along an axis.
max():The max() method returns the largest element.
mean():It is used to calculate the mean/average ofinput values or data set.
average():calculates the mean (average) of the givendata set.
PROGRAM:
import numpy as np
arr=np.array([1,2,3,4,5,6])
print("Given Array : ",arr)
A3CIL202 - AI Tools and Techniques Lab 22331A0597
p rint("Type : ",type(arr))
print("No of dimensions : ",arr.ndim)
print("Data type : ",arr.dtype)
rarr=arr.reshape(2,3)
print("Reshaped array : ",rarr)
a=np.random.randint(1,10)
print("Random number : ",a)
ar=np.array([1.,2.,3.,4.,0.5])
print("Reciprocal of array : ",np.reciprocal(ar))
print("Power fo array : ",np.power(arr,2))
print("Mod 2 of array : ",np.mod(arr,2))
#Arithmetic operations
arr1=np.array([1,2,3,4])
arr2=np.array([5,6,7,8])
print("Addition : ",np.add(arr1,arr2))
print("Subtraction : ",np.subtract(arr1,arr2))
print("Multiplication : ",np.multiply(arr1,arr2))
print("Division : ",np.divide(arr1,arr2))
print("Sum of array : ",np.sum(arr1))
print("dot product : ",np.dot(arr1,2))
print("Sin func : ",np.sin(arr1))
print("cos func : ",np.cos(arr1))
print("tan func : ",np.tan(arr1))
arr3=np.array([[1,2,3],[4,5,6]])
print("Transpose matrix : ",arr3.transpose())
print("Length of array : ",len(arr1))
print("Arranged values : ",np.arange(4))
print("Min of arr2 : ",np.min(arr2))
print("Max of arr2 : ",np.max(arr2))
print("mean of arr1 : ",np.mean(arr1))
print("Average of arr2 : ",np.average(arr2))
Output:
iven Array : [1 2 3 4 5 6]
G
Type : <class 'numpy.ndarray'>
No of dimensions : 1
Data type : int64
Reshaped array : [[1 2 3]
[4 5 6]]
A3CIL202 - AI Tools and Techniques Lab 22331A0597
andom number : 3
R
Reciprocal of array : [1. 0.5 0.33333333 0.25 2. ]
Power fo array : [ 1 4 9 16 25 36]
Mod 2 of array : [1 0 1 0 1 0]
Addition : [ 6 8 10 12]
Subtraction : [-4 -4 -4 -4]
Multiplication : [ 5 12 21 32]
Division : [0.2 0.33333333 0.42857143 0.5 ]
Sum of array : 10
dot product : [2 4 6 8]
Sin func : [ 0.84147098 0.90929743 0.14112001 -0.7568025 ]
cos func : [ 0.54030231 -0.41614684 -0.9899925 -0.65364362]
tan func : [ 1.55740772 -2.18503986 -0.14254654 1.15782128]
Transpose matrix : [[1 4]
[2 5]
[3 6]]
Length of array : 4
Arranged values : [0 1 2 3]
Min of arr2 : 5
Max of arr2 : 8
mean of arr1 : 2.5
Average of arr2 : 6.5
Observation:
● N umPy arrays are different from Python lists and are optimized for numerical
operations.
● import numpy as np is used to import the numpy library into a python program and
give a short alias np i.e we can use np.array instead of numpy.array to create an array.
Aim :
emonstrate Pandas methods that reads and analyzes a dataset, perform tasks such as data
D
loading, display, manipulation, grouping, sorting, plotting, and handling missing values.
Methods: ariables:
V
● pd.read_csv(): Reads a CSV file into a DataFrame. dt=dataofacsv
● .head():Returnsthefirstfewrows(defaultis5)oftheDataFrameto file
give a preview of the data. uni=unique
● tail():Returns the last few rows (default is 5) of the DataFrame to names
give a preview of the data. nuni=number
● .info(): Provides a summary of the DataFrame, including the of unique
number of rows, columns, column data types, and memory usage. values
● .shape: Returns the shape of the DataFrame, which is a tuple new=dataframe
containing the number of rows and columns. after dropping
● .columns: Returns the column labels of the DataFrame. a column
● .isnull(): Detects missing values in the DataFrame. sort=dataframe
● .unique(): Finds the unique values in a column. after sorting
● sort_values():Thesort_values()method sorts the DataFrameby the based on last
specified label. name
● nunique():Pandas dataframe.nunique() function returns a series with re_name=after
the specified axis’s total number of unique observations. renaming
● rename():rename columns in dataframe by using the rename() dataset
function.
PROGRAM:
import pandas as pd
df = pd.read_csv('std.csv')
print("Content of std : \n",df.to_string())
print("Last two rows : \n",df.tail(2))
print("First Two rows : \n",df.head(2))
print("Attribute data types : \n",df.dtypes)
print("Size of std : ",df.size)
print("Shape of std : ",df.shape)
print("Unique data : ",df['Name'].unique())
print("std Column names : ",df.columns)
print("Highest Ages : \n",df.nlargest(2,'Age'))
new=df.rename(columns={'Name':'Sname'})
print("Rename the Name : \n",new.head(2))
new['clg']='MVGR'
print("Adding new column : \n",new.tail(2))
Output:
Content of std :
Name Age Gender
0 Gowtham 19 M
A3CIL202 - AI Tools and Techniques Lab 22331A0597
1 Bhanu 19 M
2 Lilli 18 F
3 Bhaskar 20 M
4 Bhanu 18 M
Last two rows :
Name Age Gender
3 Bhaskar 20 M
4 Bhanu 18 M
First Two rows :
Name Age Gender
0 Gowtham 19 M
1 Bhanu 19 M
Attribute data types :
Name object
Age int64
Gender object
dtype: object
Size of std : 15
Shape of std : (5, 3)
Unique data : ['Gowtham' 'Bhanu' 'Lilli' 'Bhaskar']
std Column names : Index(['Name', 'Age', 'Gender'], dtype='object')
Highest Ages :
Name Age Gender
3 Bhaskar 20 M
0 Gowtham 19 M
Rename the Name :
Sname Age Gender
0 Gowtham 19 M
1 Bhanu 19 M
Adding new column :
Sname Age Gender clg
3 Bhaskar 20 M MVGR
4 Bhanu 18 M MVGR
Observation:
● A ttributeError if trying to use inplace with methods that do not support it.Confirm that
the method being used supports the inplace parameter. For instance, fillna() supports
inplace=True, but other methods may not.
● By using this we can get top 999 rowspd.options.display.max_rows=999;
● astype() is used to change the datatype of a column
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 5
Exp 11 Week 5 Date
Aim :
Demonstrate loading of remote datasets using pandas.
load_iris()=load_iris is a function from sklearn . The link provides V ariables:
documentation: iris in your code will be a dictionary-like object iris,df_iris
.map:Themap()functionisusedtoapplyagivenfunctiontoeveryitemof
an iterable, such as a list or tuple, and returns a mapobject(whichisan
iterator).
.target_names:
.data:consist of data
.feature_names:get attribute names
enumerate():Enumerate in Python is used to loop over an iterable and
automatically provide an index for each item.
PROGRAM:
# Import necessary libraries
import pandas as pd
from sklearn.datasets import load_iris # Import load_iris
iris = load_iris()
# Convert to DataFrame
df_iris = pd.DataFrame(data=iris.data, columns=iris.feature_names)
print(df_iris.columns)
#print(df_iris.to_string())
df_iris['species'] = iris.target
print(df_iris["species"])
# Map target values to species names
df_iris['species'] = df_iris['species'].map(dict(enumerate(iris.target_names)))
print(df_iris["species"])
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Output:
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
'petal width (cm)'],
dtype='object')
0 0
1 0
2 0
3 0
4 0
..
145 2
146 2
147 2
148 2
149 2
Name: species, Length: 150, dtype: int64
0 setosa
1 setosa
2 setosa
3 setosa
4 setosa
...
145 virginica
146 virginica
147 virginica
148 virginica
149 virginica
Name: species, Length: 150, dtype: object
Observation:
1 . Data Loaded: The Iris dataset is loaded into a DataFrame.
2. Data Structure: The data has 150 rows and 5 columns (4 features + 1 target).
3. Data Summary: The summary statistics show the central tendency and variability
of the features.
4. Data Types: The features are numeric, while the target is categorical.
5. Data Size: The dataset has 150 samples.
Aim :
Demonstrate loading of toy/real world datasets using sklearn.datasets
A3CIL202 - AI Tools and Techniques Lab 22331A0597
load_iris() ariables:
V
.data iris_df
.feature_names
.target
.target_names
Categorical.from_codes(iris.target, iris.target_names)
PROGRAM:
f rom sklearn.datasets import load_iris
import pandas as pd
Output:
s epal length (cm) sepal width (cm) petal length (cm) petal width (cm) \
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
species
0 setosa
1 setosa
2 setosa
3 setosa
4 setosa
sepal length (cm) sepal width (cm) petal length (cm) \
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Aim :
emonstrate identification for missing values in a dataset and apply various cleaning
D
techniques using pandas.
Methods: ariables:
V
● pd.read_csv(): Reads a CSV file into a DataFrame. u_c=to store
● .head(): Returns the first few rows (default is 5) of the DataFrame to used cars
give a preview of the data. dataset
● tail():Returns the last few rows (default is 5) of the DataFrame to
give a preview of the data.
● .info(): Provides a summary of the DataFrame, including the
number of rows, columns, column data types, and memory usage.
● .shape: Returns the shape of the DataFrame, which is a tuple
containing the number of rows and columns.
● .columns: Returns the column labels of the DataFrame.
● .isnull(): Detects missing values in the DataFrame.
● .unique(): Finds the unique values in a column.
● sort_values():The sort_values() methodsortstheDataFramebythe
specified label.
● nunique():Pandasdataframe.nunique()functionreturnsaserieswith
the specified axis’s total number of unique observations.
● rename():rename columns in dataframe by using the rename()
function.
● sample():Pandassample()isusedtogenerateasamplerandomrow
or column from the function caller data frame.
● describe():method in Pandas is a convenient way to get a quick
overview of your data.
● tostring():The to_string() method in Pandas is used to convert a
DataFrame or Series into a string representation.
● dataframe. isnull(). sum() returns the number of missing valuesin
the dataset.
● Theduplicated()methodreturnsaSerieswithTrueandFalsevalues
that describe which rows in the DataFrame are duplicated and not.
PROGRAM:
import pandas as pd
import numpy as np
u_c=pd.read_csv("used_cars.csv")
u_c.head(5)
u_c.columns
u_c.describe()
u_c.shape
u_c.dtypes
u_c.info()
# The inplace=True argument modifies the DataFrame directly and returns None.
# Assigning it to newu_c is unnecessary and causes the error.
# Instead, use the following:
u_c.dropna(inplace=True)
A3CIL202 - AI Tools and Techniques Lab 22331A0597
f uel_type engine \
0 E85 Flex Fuel 300.0HP 3.7L V6 Cylinder Engine Flex Fuel Capa...
1 Gasoline 3.8L V6 24V GDI DOHC
3 Hybrid 354.0HP 3.5L V6 Cylinder Engine Gas/Electric H...
6 Gasoline 292.0HP 2.0L 4 Cylinder Engine Gasoline Fuel
7 Gasoline 282.0HP 4.4L 8 Cylinder Engine Gasoline Fuel
... ... ...
4003 Gasoline 241.0HP 2.0L 4 Cylinder Engine Gasoline Fuel
4004 Gasoline 6.0L W12 48V PDI DOHC Twin Turbo
4005 Gasoline 349.0HP 3.0L V6 Cylinder Engine Gasoline Fuel
4007 Gasoline 450.0HP 3.5L V6 Cylinder Engine Gasoline Fuel
4008 Gasoline 248.0HP 2.0L 4 Cylinder Engine Gasoline Fuel
e ngine 0
transmission 0
ext_col 0
int_col 0
accident 113
clean_title 596
price 0
dtype: int64
brand 0
model 0
model_year 0
milage 0
fuel_type 0
engine 0
transmission 0
ext_col 0
int_col 0
accident 0
clean_title 0
price 0
0 False
1 False
2 False
3 False
4 False
...
4004 False
4005 False
4006 False
4007 False
4008 False
Length: 4009, dtype: bool
brand 0
model 0
model_year 0
milage 0
fuel_type 0
engine 0
transmission 0
ext_col 0
int_col 0
accident 113
clean_title 596
price 0
dtype: int64
[3269 rows x 12 columns]
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
E
● ither fillna or dropna use both can’t be used
● AttributeError if trying to use inplace with methods that do not support it.Confirm that
the method being used supports the inplace parameter. For instance, fillna() supports
inplace=True, but other methods may not.
● By using this we can get top 999 rowspd.options.display.max_rows=999;
● astype() is used to change the datatype of a column
● Data Structure: The data is stored in a pandas DataFrame, which is a
2-dimensional labeled data structure.
Aim :
Demonstrate LogisticRegression Supervised ML algorithm with any dataset.
Output:
tudy_Hours Attendance
S
0 1 50
7 8 95
2 3 65
9 10 100
4 5 80
3 4 70
6 7 90
[1 0 1]
Accuracy: 1.0
Confusion Matrix:
[[1 0]
[0 2]]
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
1 . Data Preparation: The code loads the simple dataset, splits the data into
features and target, and splits the data into training and testing sets.
2. Model Training: A Linear Regression model is trained on the training data.
3. Model Evaluation: The model is evaluated on the test data, and the MSE and R2
score are calculated.
4. Model Performance: The MSE and R2 score indicate the model's performance,
with lower MSE and higher R2 score indicating better performance.
5. Coefficients: The coefficients of the model are printed, indicating the contribution
of each feature to the predicted target value.
Aim :
Demonstrate Linear Regression Supervised ML algorithm with any dataset.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
=df1.drop('Salary',axis=1)
X
#print(X)
y=df1.Salary
X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0,test_size=0.30)
from sklearn.linear_model import LinearRegression
LR=LinearRegression()
LR.fit(X_train,y_train)
print(LR.intercept_)
print(LR.coef_)
LR.predict(X_test)
[9360.26128619]
[ 16]:
array([ 40818.78327049, 123189.08258899, 65155.46261459, 63283.41035735,
115700.87356004, 108212.66453108, 116636.89968866, 64219.43648597,
76387.77615802])
f uel_type engine \
0 E85 Flex Fuel 300.0HP 3.7L V6 Cylinder Engine Flex Fuel Capa...
1 Gasoline 3.8L V6 24V GDI DOHC
(4009, 12)
A3CIL202 - AI Tools and Techniques Lab 22331A0597
b rand object
model object
model_year int64
milage object
fuel_type object
engine object
transmission object
ext_col object
int_col object
accident object
clean_title object
price object
dtype: object
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4009 entries, 0 to 4008
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 brand 4009 non-null object
1 model 4009 non-null object
2 model_year 4009 non-null int64
3 milage 4009 non-null object
4 fuel_type 3839 non-null object
5 engine 4009 non-null object
6 transmission 4009 non-null object
7 ext_col 4009 non-null object
8 int_col 4009 non-null object
9 accident 3896 non-null object
10 clean_title 3413 non-null object
11 price 4009 non-null object
dtypes: int64(1), object(11)
memory usage: 376.0+ KB
fuel_type 170
accident 113
clean_title 596
dtype: int64
0 False
1 False
3 False
6 False
A3CIL202 - AI Tools and Techniques Lab 22331A0597
7 False
...
4003 False
4004 False
4005 False
4007 False
4008 False
Length: 3269, dtype: bool
-1947876.7036248783
[ 1006.12786195 -22963.95727474 -16012.05946607 ... 624.13596452
-352.07534734 0. ]
[ 3.46184624e+04 3.94432492e+04 1.37342567e+03 7.32900762e+04
5.67404888e+04 7.01105267e+04 1.47821619e+05 6.11777246e+04
-4.13817338e+02 4.37912418e+03]
Observation:
The code loads the wine dataset and splits it into training and testing sets. This
●
allows for evaluating the model's performance on unseen data.
● A LinearRegression model is trained using the training data and makes predictions
on the test data.
ValueError if train_test_split is incorrectly applied, leading to mismatched training and
testing sets.
Aim :
Demonstrate various plots using matplotlib.
g roupby(dataframe).sum().plot(kind='pie',y=’dataframe'):This is a pandas
method for plotting pie charts.
PROGRAM:
# plot
from matplotlib import pyplot as pt
x = [ 1,3,5,7,9 ]
y = [ 6,9,3,15,17]
pt.plot(x, y)
pt.show()
#bar
from matplotlib import pyplot as pt
x = [ 1,3,5,7,9 ]
y = [ 6,9,3,15,17]
pt.bar(x, y)
pt.show()
#stem
from matplotlib import pyplot as pt
x = [ 1,3,5,7,9 ]
y = [ 6,9,3,15,17]
pt.stem(x, y)
pt.show()
#scatter
from matplotlib import pyplot as pt
x = [ 1,3,5,7,9 ]
y = [ 6,9,3,15,17]
pt.scatter(x, y)
pt.show()
#legend
from matplotlib import pyplot as pt
x = [ 1,3,5,7,9 ]
y = [ 6,9,3,15,17]
pt.plot(x)
pt.plot(y )
pt.legend(['Weight','Height'])
pt.show()
#pie chart
import pandas as pd;
df=pd.DataFrame({'party':['ycp','tdp','janasena','bjp'],
A3CIL202 - AI Tools and Techniques Lab 22331A0597
'result':[11,138,21,5]});
df.groupby(['party']).sum().plot(kind='pie',y='result');
Output:
A3CIL202 - AI Tools and Techniques Lab 22331A0597
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
e labeled the x-axis and y-axis and plt.show() displays the line plotting for the given
W
input on the window
Creates a scatter plot with plt.scatter(), using x and y as the coordinates for the points.
The points are marked with dots (.) and colored in blue.
● And we labeled the x-axis and y-axis.
● plt.show() displays the scatter plot,barplot,stem on the window
● Creates a bar plot with plt.bar(), using x for the bar labels and y for the bar heights.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 6
Exp 17 Week 6 Date
Aim :
Using hand written digits dataset(or any other dataset) classify using SVM classifier.
PROGRAM:
f rom sklearn import datasets,svm,metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
cancer=datasets.load_breast_cancer()
data,target=cancer.data,cancer.target
print("Data shape : ",data.shape)
print("Target shape : ",target.shape)
print("Feature name : ",cancer.feature_names)
clf=svm.SVC(gamma=0.001)
A3CIL202 - AI Tools and Techniques Lab 22331A0597
x _train,x_test,y_train,y_test=train_test_split(data,target,test_size=0.5,shuffle=True,random_sta
te=42)
clf.fit(x_train,y_train)
pre=clf.predict(x_test)
print("classification report for classifier",clf)
print(metrics.classification_report(y_test,pre))
acc=accuracy_score(y_test,pre)
print("Accuracy :",f"{acc*100:.2f}")
Output:
ata shape : (569, 30)
D
Target shape : (569,)
Feature name : ['mean radius' 'mean texture' 'mean perimeter' 'mean area'
'mean smoothness' 'mean compactness' 'mean concavity'
'mean concave points' 'mean symmetry' 'mean fractal dimension'
'radius error' 'texture error' 'perimeter error' 'area error'
'smoothness error' 'compactness error' 'concavity error'
'concave points error' 'symmetry error' 'fractal dimension error'
'worst radius' 'worst texture' 'worst perimeter' 'worst area'
'worst smoothness' 'worst compactness' 'worst concavity'
'worst concave points' 'worst symmetry' 'worst fractal dimension']
classification report for classifier SVC(gamma=0.001)
precision recall f1-score support
Observation:
S
● VM is best suited for classification tasks.
● The primary objective of the SVM algorithm is to identify the optimal hyperplane in
an N-dimensional space that can effectively separate data points into different classes
in the feature space.
● The algorithm ensures that the margin between the closest points of different classes,
known as support vectors, is maximized.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
● T
he dimension of thehyperplanedepends on the number of features. For instance, if
there are two input features, the hyperplane is simply a line, and if there are three input
features, the hyperplane becomes a 2-D plane.
Aim :
Using any dataset of your choice classify the dataset using K-MEANS classifier.
PROGRAM:
f rom sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
n_samples = 300
random_state = 170
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
kmeans = KMeans(n_clusters=3, random_state=random_state, n_init="auto")
# Fit the model to the data
kmeans.fit(X)
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Output:
Observation:
● he choice of the number of clusters (K) is crucial for KMeans clustering.
T
● If K is too small, you might under-cluster your data (combine distinct clusters).
● If K is too large, you might overfit (create unnecessary clusters).
● Visualizing the results of KMeans clustering can help in understanding the cluster
structure.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 7
Exp 19 Week 7 Date
Aim :
emonstrate different image processing
D operations on colour images.
1. Reading an image and displaying the image.
2. Reading a color image and converting it into grayscale.
3. Program to Rotate an image by 90/180 degrees clockwise using OpenCV.
4. Program to write and display an image using OpenCV.
5. Program for extracting image properties using OpenCV.
6. Program for accessing and modifying pixel values.
7. Program for color mixing in OpenCV.
PROGRAM:
1 )
import cv2
import matplotlib.pyplot as plt
A3CIL202 - AI Tools and Techniques Lab 22331A0597
5 )
# Read the image
image = cv2.imread('dog.jpg') # Replace 'image.jpg' with your image file
# Get image properties
height, width, channels = image.shape
size = image.size
# Print image properties
print(f"Image Height: {height}")
print(f"Image Width: {width}")
print(f"Number of Channels: {channels}")
print(f"Image Size (in bytes): {size}")
6)
# Read the image
image = cv2.imread('dog.jpg') # Replace 'image.jpg' with your image file
# Accessing a pixel value at (x=100, y=50)
pixel_value = image[50, 100] # BGR format
print(f"Original Pixel Value at (100, 50): {pixel_value}")
# Modify the pixel value to a new color (e.g., pure red)
image[50, 100] = [0, 0, 255] # BGR format for red
# Display the modified image
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Modified Image')
plt.axis('off')
plt.show()
7)
import numpy as np
# Create two solid color images (Red and Blue)
red_image = np.zeros((300, 300, 3), dtype=np.uint8)
red_image[:] = [0, 0, 255] # BGR for red
blue_image = np.zeros((300, 300, 3), dtype=np.uint8)
blue_image[:] = [255, 0, 0] # BGR for blue
# Mix the images (50% each)
mixed_image = cv2.addWeighted(red_image, 0.5, blue_image, 0.5, 0)
# Display the mixed image
plt.imshow(cv2.cvtColor(mixed_image, cv2.COLOR_BGR2RGB))
plt.title('Color Mixing: Red and Blue')
plt.axis('off')
plt.show()
Output:
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
I mage Reading and Displaying:You can load and visualizeimages using cv2.imread() and
matplotlib.pyplot.
Grayscale Conversion:Color images can be convertedto grayscale for simpler analysis.
Image Rotation:OpenCV provides straightforward functionsfor rotating images by specific
A3CIL202 - AI Tools and Techniques Lab 22331A0597
d egrees.
Image Writing:You can save images to disk using cv2.imwrite().
Image Properties:You can extract and print propertieslike dimensions and size of an image.
Pixel Access and Modification:You can directly accessand modify pixel values using
NumPy array indexing.
Color Mixing:Use cv2.addWeighted() to blend two colorsor images.
Aim :
Demonstrate Face and Eye detection using Haar cascade classifier in OpenCV.
PROGRAM:
import cv2
import matplotlib.pyplot as plt
# Step 1: Load the Haar cascades for face and eye detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml') # Fixed:
Assigned to eye_cascade instead of face_cascade
# Step 2: Load an image
image = cv2.imread('group1.jpg')
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
aar Cascade Efficiency:Haar cascades are fast andefficient for detecting objects,
H
especially faces. This method can detect faces in real-time if applied to video streams.
Detection Parameters:The choice of scaleFactor, minNeighbors,and minSize parameters
affects the performance and accuracy of the detection.
Single Face Detection:This code is suitable for detectinga single face in a well-lit
environment.
A3CIL202 - AI Tools and Techniques Lab 22331A0597
WEEK - 8
Exp 21 Week 8 Date
Aim :
perform corner detection algorithms harris corner and shi thomshi corner detection algorithms.
Output:
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
threshold is applied to retain only the strongest corners. Points with values in the corner
A
response image (dst) greater than 1% of the maximum response (0.01 * dst.max()) are
considered corners.
These corners are marked in red ([0, 0, 255]).
Harris Corner Detectionis sensitive to changes inthe image, making it effective in detecting
sharp edges or corner-like features.
Shi-Tomasi Corner Detection:
● Selects only the strongest corners, which results in fewer, more distinct corners.
● More computationally efficient than Harris and performs better in noisy environments.
Aim :
redict whether two images are similar using SIFT for feature detection and BF matcher
P
algorithms.
Libraries, Methods & Variables Used:
A3CIL202 - AI Tools and Techniques Lab 22331A0597
p lt.axis('off')
plt.show()
# Calculate the number of good matches
num_matches = len(matches)
# Define a threshold for determining similarity
similarity_threshold = 10 # Adjust this based on experimentation
if num_matches > similarity_threshold:
return f"Images are similar with {num_matches} good matches."
else:
return f"Images are not similar with only {num_matches} matches."
# Example usage
img1_path = 'dog.jpg'
img2_path = 'dog1.jpg'
result = detect_and_match(img1_path, img2_path)
print(result)
Output:
WEEK - 9
Exp 23 Week 9 Date
Aim :
Demonstrate implementation of a chatbot in botpress.
Description:
chatbotis an artificial intelligence (AI) softwarethat can simulate a conversation with a
A
user in natural language through messaging applications, websites, mobile apps, or via the
telephone. It is designed to automate interactions and provide instant responses to user
inquiries, helping to streamline customer service, enhance user engagement, and improve
productivity.
Output:
A3CIL202 - AI Tools and Techniques Lab 22331A0597
Observation:
The distinction between rule-based and AI-powered chatbots helps readers understand the
●
different levels of chatbot capabilities, from handling simple to complex queries.
● They enhance user experience through personalised interactions and continuous learning
while being flexible and easy to manage.
● The platform's visual tools and modular design make it accessible for users with varying
technical skills.