23CS401 Aiml Lab Manual PDF
23CS401 Aiml Lab Manual PDF
NAME : ………………………………………………….
VISION
● To develop students with intellectual curiosity and technical expertise to meet the
global needs.
MISSION
VISION
● To produce globally competent technical professionals for digitized society.
MISSION
● To establish conducive academic environment by imparting quality education and
value added training.
● To encourage students to develop innovative projects to optimally resolve the
challenging social problems.
● Develop into the most knowledgeable professional to pursue higher education and Research
or have a successful carrier in industries.
● Successfully carry forward domain knowledge in computing and allied areas to solve
complex and real world engineering problems.
● Meet the technological revolution they are continuously upgraded with the technical knowledge.
LIST OF EXPERIMENTS:
1. Implementation of Uninformed search algorithms (BFS, DFS)
2. Implementation of Informed search algorithms (A*, memory-bounded A*)
3. Implement naïve Bayes models
4. Implement Bayesian Networks
5. Build Regression models
6. Build decision trees and random forests
7. Build SVM models
8. Implement ensembling techniques
9. Implement clustering algorithms
10.Implement EM for Bayesian networks
11.Build simple NN models
12.Build deep learning NN models
OUTCOMES:
At the end of this course, the students will be able to:
CO1: Use appropriate search algorithms for problem solving
CO2: Apply reasoning under uncertainty
CO3: Build supervised learning models
CO4: Build ensembling and unsupervised models
CO5: Build deep learning neural network models
23CS401 ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING
Course Outcomes
After completion of the course, Students are able to learn the listed Course Outcomes.
Knowledge
Cos Course Code Course
Outcome Level
s
Demonstrate the concepts of AI problems and use appropriate Apply (K3)
CO1 search algorithms for problem solving
Apply reasoning under uncertainty and predicate logic methods Apply (K3)
CO2 for knowledge representation.
Implement supervised learning models for different Artificial Apply (K3)
CO3 Intelligence
Demonstrate ensembling and unsupervised models to AI Apply (K3)
CO4 techniques in machine learning.
CO5 Illustrate the evaluation of the various algorithms and build Understand(K2)
deep learning neural network models.
3.
Develop a Program to implement the A* search CO1
algorithm in the Eight puzzle PO1,2,3 PSO1,2
4.
Develop a Program to implement Best First Search CO1
algorithm PO1,2,3 PSO1,2
AIM:
To Develop a Program to implement Breadth First Search Method.
Algorithm:
1. Start at the root node and push it onto the stack.
2. Check for any adjacent nodes of the tree and select one node.
3. Traverse the entire branch of the selected node and push all the nodes into the stack.
4. Upon reaching the end of a branch (no more adjacent nodes) ie nth leaf node,
move back by a single step and look for adjacent nodes of the n-1th node.
5. If there are adjacent nodes for the n-1th node, traverse those branches and push
nodes onto the stack.
PROGRAM:
from queue import Queue
graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2], 6: []}
print("The adjacency List representing the graph is:")
print(graph)
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 2
Date: UNINFORMED SEARCH ALGORITHMS
AIM:
To Develop a Program to implement Depth First Search Method.
ALGORITHM :
Input: Graph(Adjacency list) and Source vertex
OUTPUT: DFS traversal of graph
Start:
1.Create an empty stack S.
2.Create an empty list to keep record of visited vertices.
3.Insert source vertex into S, mark the source as visited.
4.If S is empty, return. Else goto 5.
5.Take out a vertex v from S.
6.Print the Vertex v.
7. Insert all the unvisited vertices in the adjacency list of v into S and mark them
visited. 10.Goto 4.
Stop.
PROGRAM:
graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2], 6: []}
print("The adjacency List representing the graph is:")
print(graph)
OUTPUT:
RESULT:
Thus the above program was successfully executed and the output was obtained
Ex.No: 3
Date: INFORMED SEARCH ALGORITHMS
AIM:
To Develop a Program to implement the A* search algorithm in the Eight puzzle
ALGORITHM:
1. The implementation of A* Algorithm involves maintaining two lists- OPEN
and CLOSED.
2. OPEN contains those nodes that have been evaluated by the heuristic function
but have not been expanded into successors yet.
3. CLOSED contains those nodes that have already been visited.
PROGRAM:
from copy import deepcopy
import numpy as np
import time
def bestsolution(state):
bestsol = np.array([], int).reshape(-1, 9)
count = len(state) - 1
while count != -1:
bestsol = np.insert(bestsol, 0, state[count]['puzzle'], 0)
count = (state[count]['parent'])
return bestsol.reshape(-1, 3, 3)
def coordinates(puzzle):
pos = np.array(range(9))
for p, q in enumerate(puzzle):
pos[q] = p
return pos
hn = misplaced_tiles(coordinates(openstates), costg)
# generate and add new state in the list
q = np.array([(openstates, position, gn, hn)], dtstate)
state = np.append(state, q, 0)
# f(n) is the sum of cost to reach
node fn = gn + hn
q = np.array([(len(state) - 1, fn)], dtpriority)
priority = np.append(priority, q, 0)
if np.array_equal(openstates, goal):
print(' The 8 puzzle is solvable \n')
return state, len(priority)
#goal state
goal = []
goal.append(1
)
goal.append(2
)
goal.append(3
)
goal.append(8
)
goal.append(0
)
goal.append(4
)
goal.append(7
)
goal.append(6
)
goal.append(5
)
state, visited = evaluvate_misplaced(puzzle, goal)
bestpath = bestsolution(state)
print(str(bestpath).replace('[', ' ').replace(']', ''))
totalmoves = len(bestpath) - 1
print('\nSteps to reach goal:',totalmoves)
visit = len(state) - visited
print('Total nodes visited: ',visit, "\n")
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 4
Date: INFORMED SEARCH ALGORITHMS
AIM:
To Develop a program implement Best First Search algorithm
Algorithm:
Step 1 : Create a priorityQueue .
Step 2 : insert ‘start’ in pqueue : pqueue.insert(start)
Step 3 : delete all elements of pqueue one by one.
Step 3.1 : if, the element is goal . Exit.
Step 3.2 : else, traverse neighbours and mark the node examined.
Step 4 : End.
PROGRAM:
from queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]
source = 0
target = 9
best_first_search(source, target,
v)
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 5
Date: NAÏVE BAYES MODEL
AIM:
To develop a Program to Implement Naive Bayes Classification in Python by using the
Advertisement clicking dataset (about users clicking the ads or not). Compute the accuracy
of the classifier, considering few test data sets
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 6
Date: LINEAR REGRESSION MODEL
AIM:
To develop a Program to build a Linear Regression Model
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
def
estimate_coef(x,y):
n=np.size(x)
m_x=np.mean(x)
m_y=np.mean(y)
SS_xy=np.sum(x*y)-n*m_y*m_x
SS_xx=np.sum(x*x)-n*m_x*m_x
def plot_regression_line(x,y,b):
plt.scatter(x,y,color="m",marker="o",s=30)
y_pred=b[0]+b[1]*x
plt.plot(x,y_pred,color="g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def main():
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])
b=estimate_coef(x,y)
print("estimated coefficient :\nb_0={}\nb_1={}".format(b[0],b[1]))
plot_regression_line(x,y,b)
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 7
Date: LOGISTIC REGRESSION MODEL
AIM:
To develop a Program to build a Logistic Regression Model
PROGRAM:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
insurance=pd.read_csv('C:\\Users\\CSELAB21\\Downloads\\claimants.csv')
insurance.columns
insurance.drop(['CASENUM'],axis=1,inplace=True
) insurance.columns
insurance.isna().sum()
insurance.iloc[:,:4]
insurance.ATTORNEY.value_counts()
insurance.ATTORNEY.mode()[0]
insurance.CLMSEX.value_counts()
insurance.CLMSEX.mode()[0]
insurance.iloc[:,:4]=insurance.iloc[:,:4].apply(lambda x: x.fillna(x.mode()[0]))
insurance.CLMAGE=insurance.CLMAGE.fillna(insurance.CLMAGE.mean()
) insurance.isna().sum()
############Model building###################
import statsmodels.formula.api as smf
insurance_model=smf.logit('ATTORNEY~CLMSEX+CLMINSUR+SEATBELT+C
LMAGE+LOSS',data=insurance).fit()
insurance_model.summary()
insurance_model1=smf.logit('ATTORNEY~CLMSEX+CLMINSUR+CLMAGE+LO
SS',data=insurance).fit()
insurance_model1.summary()
#seatbelt is not significant
insu_pred=insurance_model1.predict(insurance)
insu_pred
insurance['pred_prob']=insu_pred
insurance['att_val']=0
insurance.loc[insu_pred>=0.5,'att_val']=1
insurance.att_val
#############Confusion matrix############
from sklearn.metrics import classification_report
classification_report(insurance.ATTORNEY,insurance.att_val)
confusion_matrix=pd.crosstab(insurance.ATTORNEY,insurance.att_val)
confusion_matrix
accuracy=(436+504)/(436+249+151+504)
accuracy
############ROC curve##################
from sklearn import metrics
fpr,tpr,threshold=metrics.roc_curve(insurance.ATTORNEY,insu_pred)
plt.plot(fpr,tpr);plt.xlabel('false positive');plt.ylabel('true positive')
roc_auc=metrics.auc(fpr,tpr)#area under curve
roc_auc# -*- coding: utf-8 -*-
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 8
Date: IMPLEMENT BAYESIAN NETWORKS
AIM:
To develop a Program to construct a Bayesian network by considering medical data. Use
this model to demonstrate the diagnosis of heart patients using standard Heart Disease
Data Set.
PROGRAM:
import numpy as np
import csv
import pandas as pd
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.models import BayesianNetwork
from pgmpy.inference import VariableElimination
model = BayesianNetwork([
('age', 'Lifestyle'),
('Gender', 'Lifestyle'),
('Family', 'heartdisease'),
('diet', 'cholestrol'),
('Lifestyle', 'diet'),
('cholestrol',
'heartdisease'), ('diet',
'cholestrol')
])
model.fit(heart_disease, estimator=MaximumLikelihoodEstimator)
HeartDisease_infer = VariableElimination(model)
print(q)
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 9 DECISION TREES MODEL
Date:
AIM:
To develop a Program to build Decision tree and classify the result using the Gini
Index,Entrophy
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, classification_report
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 10 RANDOM FOREST MODEL
Date:
AIM:
To develop a Random Forest algorithm by using the data set of Kyphosis patients to
predict whether or not patients have the disease
PROGRAM:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#matplotlib inline
# Load the data from the CSV file
raw_data = pd.read_csv('C:\\Users\\jenim\\Downloads\\AI ML\\AI
ML\\kyphosis.csv')
# Explore the data with info() and pairplot()
raw_data.info()
sns.pairplot(raw_data, hue='Kyphosis')
# Split the data into training and test sets using train_test_split()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
# Measure the performance of the decision tree model
from sklearn.metrics import classification_report, confusion_matrix
print(classification_report(y_test, predictions))
print(confusion_matrix(y_test, predictions))
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No:11
Date: SUPPORT VECTOR MACHINE MODEL
AIM:
To develop a Program to build Support Vector Machine by using the Social Network
advertisement Dataset and find the accuracy of the given dataset.
PROGRAM:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import LabelEncoder
plt.title('Apples Vs Oranges')
plt.xlabel('Weights In Grams')
plt.ylabel('Size In cms')
plt.legend()
plt.show()
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 12
Date: ENSEMBLE TECHNIQUE-VOTING CLASSIFER
AIM:
To develop a Program to implement Ensemble Voting classifier technique for IRIS dataset
and find the accuracy score of Hard Voting and Soft Voting
PROGRAM:
# importing libraries
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size = 0.20,random_state = 42)
# using accuracy_score
score = accuracy_score(y_test, y_pred)
print("Soft Voting Score % d" % score)
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 13
Date: ENSEMBLE TECHNIQUE-AVERAGING
AIM:
To develop a Program to implement Ensemble Averaging classifier technique and find the
accuracy score of Averaging Classifier.
PROGRAM:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import VotingClassifier
# get a list of base models
def get_models():
models = list()
models.append(('lr', LogisticRegression()))
models.append(('cart', DecisionTreeClassifier()))
models.append(('bayes', GaussianNB()))
return models
# evaluate each base model
def evaluate_models(models, X_train, X_val, y_train, y_val):
# fit and evaluate the models
scores = list()
for name, model in models:
# fit the model
model.fit(X_train, y_train)
# evaluate the model
yhat = model.predict(X_val)
acc = accuracy_score(y_val, yhat)
# store the performance
scores.append(acc)
# report model performance
return scores
# define dataset
X, y = make_classification(n_samples=10000, n_features=20, n_informative=15,
n_redundant=5, random_state=7)
# split dataset into train and test sets
X_train_full, X_test, y_train_full, y_test = train_test_split(X, y, test_size=0.50,
random_state=1)
# split the full train set into train and validation sets
X_train, X_val, y_train, y_val = train_test_split(X_train_full, y_train_full, test_size=0.33,
random_state=1)
# create the base models
models = get_models()
# fit and evaluate each model
scores = evaluate_models(models, X_train, X_val, y_train, y_val)
print(scores)
# create the ensemble
ensemble = VotingClassifier(estimators=models, voting='soft', weights=scores)
# fit the ensemble on the training dataset
ensemble.fit(X_train_full, y_train_full)
# make predictions on test set
yhat = ensemble.predict(X_test)
# evaluate predictions
score = accuracy_score(y_test, yhat)
print('Weighted Avg Accuracy: %.3f' % (score*100))
# evaluate each standalone model
scores = evaluate_models(models, X_train_full, X_test, y_train_full, y_test)
for i in range(len(models)):
print('>%s: %.3f' % (models[i][0], scores[i]*100))
# evaluate equal weighting
ensemble = VotingClassifier(estimators=models, voting='soft')
ensemble.fit(X_train_full, y_train_full)
yhat = ensemble.predict(X_test)
score = accuracy_score(y_test, yhat)
print('Voting Accuracy: %.3f' % (score*100))
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained.
Ex.No: 14
Date: K MEANS CLUSTERING ALGORITHM
AIM:
To develop a Program to build k-means clustering algorithm by generate isotropic Gaussian
Clustering blobs and find the optimal number of clusters by using the Elbow Method.
PROGRAM:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#from sklearn.datasets.samples_generator import make_blobs
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10,
random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 15
Date: K NEAREST NEIGHBOUR CLUSTERING ALGORITHM
AIM:
To develop a Program to build k-nearest neighbour clustering algorithm by using classified
dataset and find prescion, recall ,f1 score, support by using different number of clusters.
PROGRAM:
#K Nearest Neighbors with Python
#Import Libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
#Load the Data
df = pd.read_csv('C://Users//jenim//Downloads//AI ML//AI ML//ensemble//Classified
Data.csv',index_col=0)
df.head()
#Standardize the Variables
#Because the KNN classifier predicts the class of a given test observation
#by identifying the observations that are nearest to it, the scale of the
#variables matters. Any variables that are on a large scale will have a much
#larger effect on the distance between the observations, and hence on the KNN
#classifier, than variables that are on a small scale.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop('TARGET CLASS',axis=1))
scaled_features = scaler.transform(df.drop('TARGET CLASS',axis=1))
df_feat = pd.DataFrame(scaled_features,columns=df.columns[:-1])
df_feat.head()
#Train-Test Split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(scaled_features,df['TARGET CLASS'],
test_size=0.30)
## Using KNN
#Remember that we are trying to come up with a model to predict whether someone
#will TARGET CLASS or not. We'll start with k=1.
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
metric_params=None, n_jobs=1, n_neighbors=1, p=2,
weights='uniform')
pred = knn.predict(X_test)
#Predicting and evavluations
#Let's evaluate our knn model.
from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,pred))
#chosing a K Value
#Let's go ahead and use the elbow method to pick a good K Value:
error_rate = []
for i in range(1,40):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train,y_train)
pred_i = knn.predict(X_test)
error_rate.append(np.mean(pred_i != y_test))
plt.figure(figsize=(10,6))
plt.plot(range(1,40),error_rate,color='blue',
linestyle='dashed', marker='o',markerfacecolor='red',
markersize=10)
plt.title('Error Rate vs. K Value')
plt.xlabel('K')
plt.ylabel('Error Rate')
# FIRST A QUICK COMPARISON TO OUR ORIGINAL K=1
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
pred = knn.predict(X_test)
print('WITH K=1')
print('\n')
print(confusion_matrix(y_test,pred))
print('\n')
print(classification_report(y_test,pred)
) # NOW WITH K=23
knn = KNeighborsClassifier(n_neighbors=23)
knn.fit(X_train,y_train)
pred = knn.predict(X_test)
print('WITH K=23')
print('\n')
print(confusion_matrix(y_test,pred))
print('\n')
print(classification_report(y_test,pred)
)
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained
Ex.No: 16
Date: EXPECTATION MAXIMIZATION
AIM:
To develop a Program to implement Expectation Maximization algorithm
PROGRAM:
# For plotting
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
%matplotlib inline
#for matrix math
import numpy as np
#for normalization + probability density function computation
from scipy import stats
#for data preprocessing
import pandas as pd
from math import sqrt, log, exp, pi
from random import uniform
random_seed=36788765
np.random.seed(random_seed)
# generate data
y1 = np.random.normal(Mean1, Standard_dev1, 1000)
y2 = np.random.normal(Mean2, Standard_dev2, 500)
data=np.append(y1,y2)
class Gaussian:
"Model univariate Gaussian"
def init (self, mu, sigma):
#mean and standard deviation
self.mu = mu
self.sigma = sigma
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained.
Ex.No: 17
Date: SEQUENTAIL NEURAL NETWORK MODEL
AIM:
To develop a Program to build a sequential Neural Network Model.
PROGRAM:
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
# Use numpy arrays to store inputs (x) and outputs (y):
x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [1], [1], [0]])
# Define the network model and its arguments.
# Set the number of neurons/nodes for each layer:
model = Sequential()
model.add(Dense(2, input_shape=(2,)))
model.add(Activation('sigmoid'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
# Compile the model and calculate its accuracy:
model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['accuracy'])
# Print a summary of the Keras model:
model.summary()
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained.
Ex.No: 18
Date: DEEP LEARNING NN MODEL
AIM:
To develop a Program to build a Deep Learning NN model
PROGRAM:
import tensorflow as tf
#load training data and split into train and test sets
mnist = tf.keras.datasets.mnist
(x_train,y_train), (x_test,y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28,28)),
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
#define loss function variable
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
probability_model = tf.keras.Sequential([
model,
tf.keras.layers.Softmax()])
OUTPUT:
RESULT:
Thus the above Program was successfully executed and the Output was obtained