AI-ML LAB Manual Format
AI-ML LAB Manual Format
ABSTRACT: Artificial intelligence (AI) is the theory and development of computer systems
capable of performing tasks that historically required human intelligence, such as recognizing speech,
making decisions, and identifying patterns. AI is an umbrella term that encompasses a wide variety of
technologies, including machine learning, deep learning, and natural language processing
(NLP). The term is commonly used to describe a range of different technologies in use today, many
disagree on whether these actually constitute artificial intelligence. Instead, some argue that much of
the technology used in the real world today actually constitutes highly advanced machine learning
that is simply a first step towards true artificial intelligence, or “general artificial intelligence” (GAI).
LIST OF EXPERIMENTS
Ex.
No. Programs
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
Aim:
Algorithm
Step 1: Start
Step 2: Initialize Graph
Step 3: Create list for visited node
Step 4: Create list to initialize queue
Step 5: Perform Breadth First Search
Step 6: print the order of node visited
Step 7: Stop
Source Code
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited
nodes. queue = [] #Initialize a
queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
Output
Result
Thus the Breadth First Program is implemented and executed successfully using
Python Programming.
Aim:
Algorithm
Step 1: Start
Step 2: Initialize Graph
Step 3: Create list for visited node
Step 4: Create list to initialize queue
Step 5: Perform Depth First Search
Step 6: print the order of node visited
Step 7: Stop
Source Code
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 is the Depth-First Search") dfs(visited, graph, '5')
Output
Result
Thus the Depth First Program is implemented and executed successfully using
Python Programming.
Algorithm
Step 1: Start
Step 2: Initialize heap
Step 3: Initialize heuristic value for all node
Step 4: Perform A* Search
Step 5: print the destination node heuristic value
Step 6: Stop
Source Code
import heapq
def astar(graph, heuristic, start, goal):
visited = set()
heap = [(0, start)]
while heap:
(cost, node) = heapq.heappop(heap)
if node in visited:
continue
visited.add(node)
if node == goal:
return cost
for neighbor, distance in graph[node].items():
if neighbor not in visited:
heapq.heappush(heap, (cost + distance + heuristic[neighbor], neighbor))
return -1
graph = {
'A': {'B': 2, 'C': 3},
'B': {'D': 4},
'C': {'D': 2},
'D': {'E': 3},
'E': {}
}
heuristic = {
'A': 7,
'B': 6,
'C': 4,
'D': 2,
'E': 0
}
print("A*:")
print(astar(graph, heuristic, 'A', 'E'))
Output
A*:
14
Result
Thus the A* search is implemented and executed successfully using Python Programming.
Aim:
Algorithm
Step 1: Start
Step 2: Import priority queue
Step 3: Initialize graph and heuristic value for all node
Step 4: Initialize weights for all paths
Step 5: Perform Memory Bounded heuristic search
Step 6: print the result
Step 7: Stop
Source Code
from queue import PriorityQueue
import sys
graph = {
'A': {'B': 2, 'C': 3},
'B': {'D': 4},
'C': {'D': 2},
'D': {'E': 3},
'E': {}
}
heuristic = {
'A': 7,
'B': 6,
'C': 4,
'D': 2,
'E': 0
}
class Node:
def init (self, state, parent=None, action=None, path_cost=0, heuristic_cost=0):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.heuristic_cost = heuristic_cost
self.f_cost = path_cost + heuristic_cost
def lt (self, other):
return self.f_cost < other.f_cost
def memory_bounded_a_star_search(problem, memory_limit=sys.maxsize):
start_node = Node(problem.initial_state)
if problem.goal_test(start_node.state):
return start_node.state
frontier = PriorityQueue()
frontier.put(start_node)
explored = {}
while frontier:
node = frontier.get()
state = node.state
if problem.goal_test(state):
return state
if state in explored and explored[state].f_cost <= node.f_cost:
continue
explored[state] = node
if node.f_cost > memory_limit:
continue
for action in problem.actions(state):
child_state = problem.result(state, action)
child_path_cost = node.path_cost + problem.step_cost(state, action, child_state)
child_heuristic_cost = problem.heuristic(child_state)
child_node = Node(child_state, node, action, child_path_cost, child_heuristic_cost)
if child_state not in explored or child_node.f_cost < explored[child_state].f_cost:
frontier.put(child_node)
return None
Output
Result
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Import iris dataset from sklearn datasets
Step 4: Import all required packages to perform naive bias classification in machine learning
Step 5: Display the result
Step 6: Stop
Source Code
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
# Load the iris dataset
iris = load_iris()
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2,
random_state=0)
# Train a Gaussian Naive Bayes classifier
classifier = GaussianNB()
classifier.fit(X_train, y_train)
# Predict the test set labels
y_pred = classifier.predict(X_test)
# Calculate the accuracy score
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
Output
Result
Thus the Naive Bias model for iris dataset is implemented and executed successfully
using Python Program
Aim:
To implement Bayesian Network to find the probability rate of patient having heart
disease using Python Programming.
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Import heardisease dataset as csv
Step 4: Import all required packages to perform Bayesian Network in machine learning
Step 5: Display the result
Step 6: Stop
print(heartDisease.dtypes)
Source Code – Fitting model in Bayesian Network
model= BayesianModel([('age','heartdisease'),('gender','heartdisease'),('exang','heartdisease'),
('cp','hear tdisease'),('heartdisease','restecg'),('heartdisease','chol')])
print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)
Source Code – Reduce redundant variables print('\
n Inferencing with Bayesian Network:')
HeartDiseasetest_infer = VariableElimination(model)
Source Code – Predicting Probability value of heartdisease for evidence restecg
print('\n 1. Probability of HeartDisease given evidence= restecg')
q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1})
print(q1)
Output
Result
Thus the Bayesian model for heart disease dataset is implemented and executed
successfully using Python Programming.
Aim:
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform Linear regression in machine learning
Step 5: Display the result
Step 6: Stop
import numpy as np
from sklearn.linear_model import LinearRegression
Source code - Data and Reshape of x and display of y value
x = np.array([2, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38])
x
y
model = LinearRegression()
model.fit(x, y)
print(f"slope: {model.coef_}")
y_new = model.predict(x_new)
y_new
Result
Thus the Single Linear Regression for is implemented and executed successfully
using Python Programming.
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform Multiple Linear regression in
machine
learning
Step 5: Display the result
Step 6: Stop
Source Code - import
pandas as pd data = {'year':
[2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,20
16,2016,2016,2016,2016,2016,2016,2016],
'month': [12,11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
'interest_rate':
[2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,
1.75,1.75],
'unemployment_rate':
[5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
'index_price':
[1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,94
9,884,866,876,822,704,719]
}
df = pd.DataFrame(data)
print(df)
Output:
import pandas as pd
import matplotlib.pyplot as plt
data = {'year':
[2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,20
16,2016,2016,2016,2016,2016,2016,2016],
'month': [12,11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
'interest_rate':
[2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,
1.75,1.75],
'unemployment_rate':
[5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
'index_price':
[1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,94
9,884,866,876,822,704,719]
}
df = pd.DataFrame(data)
plt.scatter(df['interest_rate'], df['index_price'], color='red')
plt.title('Index Price Vs Interest Rate', fontsize=14)
plt.xlabel('Interest Rate', fontsize=14)
plt.ylabel('Index Price', fontsize=14)
plt.grid(True)
plt.show()
Output
df = pd.DataFrame(data)
plt.scatter(df['unemployment_rate'], df['index_price'],
color='green') plt.title('Index Price Vs Unemployment Rate',
fontsize=14) plt.xlabel('Unemployment Rate', fontsize=14)
plt.ylabel('Index Price', fontsize=14)
plt.grid(True)
plt.show()
Output
import statsmodels.api as sm
data = {'year':
[2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,20
16,2016,2016,2016,2016,2016,2016,2016],
'month': [12,11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
'interest_rate':
[2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,
1.75,1.75],
'unemployment_rate':
[2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,
1.75,1.75],
'unemployment_rate':
[5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
'index_price':
[1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,94
9,884,866,876,822,704,719]
}
df = pd.DataFrame(data)
x = df[['interest_rate','unemployment_rate']]
y = df['index_price']
# with sklearn
regr = linear_model.LinearRegression() regr.fit(x, y)
Result
Aim:
To implement Logistic Regression library to predict digit values from images using
Python Programming
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Import image dataset
Step 4: Import all required packages to perform Logistic regression in machine learning
Step 5: Display the result
Step 6: Stop
Importing libraries
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as ply
import seaborn as sns
from sklearn import metrics
%matplotlib inline
digits = load_digits()
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
(414)
Result
Thus the Logistic Regression to predict digit values from images is implemented
and executed successfully using Python Program
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform Decision tree in machine learning
Step 5: Display the result
Step 6: Stop
Loading Data
Pima Indian Diabetes dataset
col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']
# load dataset
pima = pd.read_csv("diabetes.csv", header=None, names=col_names)
pima.head()
Feature Selection
#split dataset in features and target variable
Splitting Data
# Split dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70%
training and 30% test
Building Decision Tree Model
Let's create a decision tree model using Scikit-learn.
# Create Decision Tree classifer object
clf = DecisionTreeClassifier()
# Train Decision Tree Classifer
clf = clf.fit(X_train,y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
Example
Decision Tree
Result
Thus the Decision Tree to predict Diabetes from the given feature is implemented
and executed successfully using Python Program
Aim:
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform Random Forest in machine learning
Step 5: Display the result
Step 6: Stop
Source Code – Hyperparameter tuning for Random Forest using GridSearchCV and fit
the data
rf = RandomForestClassifier(random_state=42, n_jobs=-1)
params = {
'max_depth': [2,3,5,10,20],
'min_samples_leaf': [5,10,20,50,100,200],
'n_estimators': [10,25,30,50,100,200]
}
from sklearn.model_selection import GridSearchCV
# Instantiate the grid search model
grid_search = GridSearchCV(estimator=rf,
param_grid=params,
cv = 4,
n_jobs=-1, verbose=1, scoring="accuracy")
grid_search.fit(X_train, y_train)
grid_search.best_score_
rf_best = grid_search.best_estimator_
rf_best
rf_best.feature_importances_
imp_df = pd.DataFrame({
"Varname": X_train.columns,
"Imp":
rf_best.feature_importances_
})
imp_df.sort_values(by="Imp", ascending=False)
Result
Thus the Random Forest to predict heart disease from the given feature in dataset is
implemented and executed successfully using Python Programming.
To implement SVM model to predict customer is purchase the product or not based on
given features using python programming.
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform Support Vector Machine in machine learning
Step 5: Import Grid Search to find optimal Hyper parameters for SVM
Step 6: Display the result
Step 7: Stop
Source Code – Import the data set and divide it into input and output variables
from google.colab import drive
drive.mount('/content/drive')
df = pd.read_csv("/content/drive/My Drive/customer_purchases.csv")
df.head()
Source Code
print out the target/output class to verify that our data is a binary set
# printing the target values
print(dataset.Purchased)
pip install chart_studio
pyoff.iplot(fig)
plt.contour f(X1,X2,classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),alpha = 0.75, cmap = ListedColormap(('black', 'white')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
# plorting scattred graph for the testing values
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],c = ListedColormap(('red', 'blue'))(i),
label = j)
# labelling the graph
plt.title('Purchased vs Not-purchased Predictions')
plt.xlabel('Salary')
plt.ylabel('Age')
plt.legend()
plt.show()
Result
Thus the Support Vector Machine to predict customer purchase the product or not from the
given feature in dataset is implemented and executed successfully using Python
Programming.
To implement Ada Boost Ensembling model to predict classify flower species based on
given dataset using Python Programming
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform AdaBoost Ensembling model in machine
learning
Step 5: Display the result
Step 6: Stop
Result
Thus the AdaBoost to predict the class of the flower from the given feature in dataset
is implemented and executed successfully using Python Programming.
Algorithm
Step 1: Start
Step 2: Import sklearn
Step 3: Initialize features and labels
Step 4: Import all required packages to perform K-means clustering
Step 5: Display the result
Step 6: Stop
y_kmeans = kmeans.fit_predict(X)
# Create the visualization plot of the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 100, c = 'black',
label = 'Centroids')
plt.title('IRIS Clusters')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.legend()
plt.show()
Result
Thus the K-means Cluster to predict the species of the flower from the given feature in
dataset is implemented and executed successfully using Python Programming.
Algorithm
Step 1: Start
Step 2: Initialize features and labels
Step 3: Assign weight for features
Step 4: Import all required packages to perform Neural Computation
Step 5: Display the result
Step 6: Stop
data : an ndarray
the same data arary with the hidden node column filled in
"""
hidden_params = np.array(mb.prob_table[mb.hidden].values())
previous_params = np.array(mb.prob_table[mb.hidden].values())
i += 1
if i == max_iter:
print 'Maximum iterations reached.'
#-----fill in the hidden node data by sampling the distribution
labels = {}
for key, prob in expected_counts.counts.items():
try:
labels[key[1:]].append((key[0], prob))
except:
labels[key[1:]] = [(key[0], prob)]
for key, counts in ct.table.items():
def
search_hidden(
data):
Parameters
Returns
"""
ind = np.where(is_col_nan)
if np.size(ind)==1:
ind_h = ind[0][0]
else:
return ind_h
class MarkovBlanket():
"""
An object for storing info on nodes within the markov blanket of the
hidden node
Parameters
ind_h : int
index of the hidden node within the model
Attributes
hidden : int
index of the hidden node
parents : list of int
a list of indices of the parent nodes
children : list of int
prob_table : dict
a dict of probabilities table of nodes within the Markov blanket
"""
def init (self, ind_h):
self.hidden = ind_h
self.parents = []
self.children = []
self.coparents = []
self.prob_table = {}
def populate(self, model):
"""populate the parents, children, and coparents nodes
"""
state_indices = {state.name : i for i, state in enumerate(model.states)}
edges_list = [(parent.name, child.name) for parent, child in
model.edges]
edges_list = [(state_indices[parent],state_indices[child])
for parent, child in edges_list]
idxs = distribution.column_idxs
table = self.prob_table[ind_state] # dict
# marginal counts
for mb_key in mb_keys:
# marginal counts of node + parents
num +=
ct.table[mb_key[1:]]*expected_counts.counts[mb_key]
mb : a MarkovBlanket
mb : object
MarkovBlanket object
self.table[tuple(row)] += 1
self.ind[tuple(row)].append(i)
except KeyError:
Bayesian Network
import numpy as np
from pomegranate import *
data = np.array([[np.nan, 'yellow', 'sweet', 'long'],
[np.nan, 'green', 'sour', 'round'],
[np.nan, 'green', 'sour', 'round'],
[np.nan, 'yellow', 'sweet', 'long'],
[np.nan, 'yellow', 'sweet', 'long'],
[np.nan, 'green', 'sour', 'round'],
[np.nan, 'green', 'sweet', 'long'],
[np.nan, 'green', 'sweet', 'round']])
Result
Thus the EM for Bayesian Network is implemented and executed successfully using Python
Programming.
Aim:
Algorithm
Step 1: Start
Step 2: Initialize features and labels
Step 3: Assign weight for features
Step 4: Import all required packages to perform Neural Computation
Step 5: Display the result
Step 6: Stop
Output
Result
Thus the simple Neural Network is implemented and executed successfully using
Python Programming.
Algorithm
Step 1: Start
Step 2: Import keras
Step 3: Initialize features and labels
Step 4: Initialize weights, bias values, optimizers, and hidden layers
Step 4: Import all required packages to perform Neural computation
Step 5: Display the result
Step 6: Stop
Making Predictions
predictions = model.predict(x)
print([round(x[0]) for x in predictions])
Result
Thus the deep Neural Network to predict diabetes based on given features is
implemented and executed successfully using Python Programming.