AI &ML LAB Manual
AI &ML LAB Manual
Solution:
The distance function calculates the Euclidean distance between two
points in a two-dimensional space. In simple terms, it measures the
straight-line distance between two points in a plane.
Once all cities are visited, return to the starting city to complete the
tour.
Step-by-Step Execution:
for i in range(num_cities):
if not visited[i] and i != current_city:
dist = distance(cities[current_city], cities[i])
if dist < min_dist:
min_dist = dist
nearest_city = i
distances.append(min_dist)
total_distance += min_dist
path.append(nearest_city)
visited[nearest_city] = True
Output:
V=4
for p in perm:
current_pathweight = 0
for i in range(V - 1):
current_pathweight += graph[p[i]][p[i + 1]]
current_pathweight += graph[p[-1]][p[0]] # Add return to start
city
all_paths.append((list(p), current_pathweight))
plt.figure(figsize=(8, 6))
plt.scatter(x_coords, y_coords, c='red', label='Cities')
plt.plot(x_coords[0], y_coords[0], 'go', label='Start/End') # Mark the
starting city
# Driver Code
if __name__ == "__main__":
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
start_city = 0
OUTPUT:
Optimal Path: [0, 1, 3, 2, 0]
Total Distance of Optimal Path: 80
class Node:
def __init__(self, state, parent=None, cost=0, heuristic=0):
self.state = state
self.parent = parent
self.cost = cost
self.heuristic = heuristic
while open_set:
current_node = heapq.heappop(open_set)
if current_node.state == goal:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return path[::-1]
closed_set.add(current_node.state)
return None
plt.legend()
plt.grid(visible=True)
plt.gca().invert_yaxis() # Invert y-axis to match grid representation
plt.show()
# Example usage:
start_state = (0, 0)
goal_state = (9, 9)
path = a_star_search(start_state, goal_state, get_neighbors,
manhattan_distance)
if path:
print("Path found:", path)
visualize_grid(start_state, goal_state, path)
else:
print("No path found.")
Output:
Path found: [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (3, 3),
(3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 9), (5, 9), (6, 9),
(7, 9), (8, 9), (9, 9)]
if 'OR' in condition:
OR_nodes = condition['OR']
Path_B =' OR '.join(OR_nodes)
PathB = min(H[node]+weight for node in OR_nodes)
cost[Path_B] = PathB
return cost
Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost, H)
# ADD TO PATH FOR AND PATH
else:
Path +='<--('+key[Index]+') '
Start = Next[0]
Path += '[' +shortest_path(Start, Updated_cost, H) + '
+'
Start = Next[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'
return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}
Conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
# weight
weight = 1
# Updated cost
print('Updated Cost :')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))
Output:
4. Write a program to demonstrate the working of the decision tree-based ID3 algorithm. Use
an appropriate data set for building the decision tree and apply this knowledge to classify a
new sample.
5. import math
6. import pandas as pd
7. from operator import itemgetter
class DecisionTree:
def __init__(self, df, target, positive, parent_val, parent):
self.data = df
self.target = target
self.positive = positive
self.parent_val = parent_val
self.parent = parent
self.childs = []
self.decision = ''
def update_nodes(self):
self.features = [col for col in self.data.columns if col !=
self.target]
self.entropy = self._get_entropy(self.data)
if self.entropy != 0:
self.gains = [(feat, self._get_gain(feat)) for feat in
self.features]
self._get_splitter()
residual_columns = [k for k in self.data.columns if k !
= self.splitter]
for val in self.data[self.splitter].unique():
df_tmp = self.data[self.data[self.splitter]==val]
[residual_columns]
tmp_node = DecisionTree(df_tmp, self.target,
self.positive, val, self.splitter)
tmp_node.update_nodes()
self.childs.append(tmp_node)
def print_tree(n):
for child in n.childs:
if child:
print(child.__dict__.get('parent', ''))
print(child.__dict__.get('parent_val', ''), '\n')
print_tree(child)
df = pd.read_csv('id3.csv')
df
dt = DecisionTree(df, 'Play', 'Yes', '', '')
dt.update_nodes()
print_tree(dt)
6. Build an Artificial Neural Network by
implementing the Backpropagation algorithm
and test the same using appropriate data
sets
Solution:
Artificial Neural Network (ANN) using the backpropagation algorithm:
An Artificial Neural Network (ANN) is a computational model inspired
by the way biological neural networks in the human brain operate. It
consists of interconnected nodes, called neurons, organized in
layers. In a typical ANN, there are three types of layers:
Input Layer: This layer receives input signals and passes them on to
the next layer. The number of neurons in the input layer
corresponds to the number of input features in your dataset.
Output Layer: This layer produces the final output of the neural
network. The number of neurons in the output layer depends on the
nature of the problem you are trying to solve (e.g., regression,
classification).
The backpropagation algorithm is a method used to train neural
networks. It works by iteratively adjusting the weights of the
connections in the network to minimize the difference between the
predicted output and the actual output. This is done by computing
the gradient of the loss function with respect to the weights using
the chain rule of calculus and updating the weights in the direction
that reduces the loss.
import numpy as np
# scale units
X = X/np.amax(X, axis=0) # maximum of X array
y = y/100 # max test score is 100
class Neural_Network(object):
def __init__(self):
# Parameters
self.inputSize = 2
self.outputSize = 1
self.hiddenSize = 3
# Weights
self.W1 = np.random.randn(self.inputSize,
self.hiddenSize) # (3x2) weight matrix from input to
hidden layer
self.W2 = np.random.randn(self.hiddenSize,
self.outputSize) # (3x1) weight matrix from hidden to
output layer
NN = Neural_Network()
for i in range(1000): # trains the NN 1,000 times
print ("\nInput: \n" + str(X))
print ("\nActual Output: \n" + str(y))
print ("\nPredicted Output: \n" + str(NN.forward(X)))
print ("\nLoss: \n" + str(np.mean(np.square(y -
NN.forward(X))))) # mean sum squared loss)
NN.train(X, y)
Output:
7.Write a program to implement the naïve Bayesian classifier for a sample training data set
stored as a .CSV file. Compute the accuracy of the classifier, considering few test data sets.
# import necessary libarities
import pandas as pd
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
le_Temperature = LabelEncoder()
X.Temperature = le_Temperature.fit_transform(X.Temperature)
le_Humidity = LabelEncoder()
X.Humidity = le_Humidity.fit_transform(X.Humidity)
le_Windy = LabelEncoder()
X.Windy = le_Windy.fit_transform(X.Windy)
classifier = GaussianNB()
classifier.fit(X_train,y_train)
In the context of the Iris dataset, the k-NN algorithm can be used to
classify iris flowers into one of the three species based on their
sepal and petal measurements. The algorithm calculates the
distances between the new flower and all other flowers in the
dataset, then selects the k nearest neighbors and assigns the class
label based on the majority class among those neighbors.
Code:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score,
recall_score, f1_score
import matplotlib.pyplot as plt
import numpy as np
from tabulate import tabulate
plt.figure(figsize=(10, 5))
plt.bar(labels, values, color=['blue', 'green', 'orange', 'red'])
plt.ylabel('Score')
plt.title('Performance Metrics of k-NN on Iris Dataset')
plt.ylim(0, 1)
plt.show()
print("\nActual vs Predicted:")
print(tabulate(table_data, headers=['Actual', 'Predicted'],
tablefmt='grid'))
Output:
Accuracy: 1.0
Precision: 1.0
Recall: 1.0
F1-score: 1.0
10. Implement the non-parametric Locally Weighted Regression algorithm in
order to fit data points. Select the appropriate dataset for your experiment and
draw gr
Answer:
To implement the Locally Weighted Regression (LWR) algorithm, we'll use Python.
We'll also select a dataset and fit data points using LWR. For this example, let's use
the boston dataset from the sklearn—datasets module, which contains housing prices
and other information about houses in Boston suburbs. We'll fit a regression line using
LWR and plot the results.
from math import ceil
import numpy as np
from scipy import linalg
residuals = y - yest
s = np.median(np.abs(residuals))
delta = np.clip(residuals / (6.0 * s), -1, 1)
delta = (1 - delta ** 2) ** 2
return yest
import math
n = 100
x = np.linspace(0, 2 * math.pi, n)
y = np.sin(x) + 0.3 * np.random.randn(n)
f =0.25
iterations=3
yest = lowess(x, y, f, iterations)
Output: