Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Artificial Intelligence Codes in python language
Description: These are codes for every method in AI and are well explained using comments within the codes. As I have also previously uploaded the theory notes for these. You can refer them for better understanding.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


AI Practicals
Practical 1 - Random Search Algorithm
Q1
...
choice(directions)
if move_blank_tile(current_board, random_direction):
num_moves += 1
if is_goal_state(current_board, goal_state):
return current_board, num_moves
initial_board = [[2, 8, 3], [1, 6, 4], [7, 0, 5]]
goal_state = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
solved_board, num_moves = random_search(initial_board,
goal_state)
print(solved_board,"\n",num_moves)

Q2
...

import random
def quadratic_function(x): # finding the value of the function
return 2 * x**2 - 5 * x + 3
def find_minimum_random_search(max_iterations=1000): #Finding
the minimum
best_x = None
best_value = float('inf') # Initialize with positive
infinity
for _ in range(max_iterations):
x = random
...
WAPP for password cracking using random search, incorporating character combinations
import random
import string
def generate_possible_passwords(length):
characters = string
...
digits +
string
...
join(random
...
Implement the water jug problem using BFS
from collections import deque
def BFS_SEARCH(cap1, cap2, target):
closed = set()
open = deque()
open
...
popleft()
print("Current State : ", current_state)
if current_state in closed:
continue
closed
...
append((cap1,y))
#Fill in 2nd jug
if yopen
...
append((x-a,y+a))
#Pour from 2 to 1
if x+y>=cap2 and y>0:
a = min(cap2, cap1-x)
open
...
append((0,y))
#Empty 2nd jug
if y>0:
open
...
Implement Water jug problem using DFS
from collections import deque
def DFS_SEARCH(cap1, cap2, target):
closed = set()
open = deque()
open
...
pop()
print("Current State : ", current_state)
if current_state in closed:

continue
closed
...
append((cap1,y))
#Fill in 2nd jug
if yopen
...
append((x-a,y+a))
#Pour from 2 to 1
if x+y>=cap2 and y>0:
a = min(cap2, cap1-x)
open
...
append((0,y))
#Empty 2nd jug
if y>0:
open
...
Demonstrate the implementation of Uniform cost search for a small city map
from geopy
...
distance
geolocator = Nominatim(user_agent="DistanceCalculator")

def get_lat_long(city):
loc = geolocator
...
latitude, loc
...
distance
...
km
graph = {"nodes": set(), "edges": {}}
def add_locations(location1,location2):
if location1 not in graph["nodes"]:
graph["nodes"]
...
add(location2)
graph["edges"][location2] = []
print(graph)
position1 = get_lat_long(location1)
position2 = get_lat_long(location2)
print(position1, position2)
distance =
round(calculateDistance(position1[0],position1[1],position2[0]
,position2[1]),2)
print(distance)
graph["edges"][location1]
...
append((location1,distance))
def uniform_cost_search(start, goal):
priority_queue = [(0,start,[])]
while priority_queue:
(cost, current_location,path) = priority_queue
...
append((cost+distance, neighbour, path))
priority_queue
...
Implement 8-Puzzle Problem Using Best-First Search
import heapq
import copy
#Displaying the 8 puzzle:
def print_puzzle(state):
for i in range(3):
for j in range(3):
print(state[i][j],"|",end = " ")
print()
# counting misplaced value
def heuristic(current_state, goal_state):
sum = 0
for i in range(3):
for j in range(3):
if current_state[i][j]!=0 and
current_state[i][j]!=goal_state[i][j]:
sum +=1
return sum
# get neighbors
def get_neighbors(state):
neighbors = []
#get_blanktile:
for i in range(3):
for j in range(3):
if state[i][j]==0:
row, col = i, j

for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 3 and 0 <= new_col < 3:
new_state = copy
...
append(new_state)
return neighbors
# best_first_search algorithm
def best_first_search(initial_state, goal_state):
start_node = initial_state
goal_node = goal_state
priority_queue = [(heuristic(initial_state, goal_state),
start_node)]
while priority_queue:
h_value, current_node = heapq
...
heappush(priority_queue,(heuristic(neighbor_state,
goal_state), neighbor_state))
return "Failure"
start = [[1,2,3],
[0,5,6],
[4,7,8]]
goal = [[1,2,3],
[4,5,6],
[7,8,0]]
best_first_search(start,goal)
Q2
...
deepcopy(state)
new_state[row][col],new_state[new_row][new_col] =
new_state[new_row][new_col],new_state[row][col]
neighbors
...
heappop(priority_queue)
print_puzzle(current_node)
print("The heuristic value: ", h_value)

if (current_node == goal_state):
print("puzzle solved!")
return True
cost += 1 #change
for neighbor_state in get_neighbors(current_node):
heapq
...
Implement tic tac toe game using Minimax algorithm
...
Create a fuzzy control system which models how you might choose to tip at a restaurant
...
You use
this to leave a tip of between 0 and 25%
...
Antecedent(np
...
Antecedent(np
...
Consequent(np
...
automf(3)
service
...
view()
# Custom membership functions for tips:
tip['low'] = fuzz
...
universe, [0, 0, 13])
tip['medium'] = fuzz
...
universe, [0, 13, 25])
tip['high'] = fuzz
...
universe, [13, 25, 25])
tip
...
Rule(quality['poor'] | service['poor'],
tip['low'])
rule2 = ctrl
...
Rule(service['good'] | quality['good'],
tip['high'])
tipping_ctrl = ctrl
...
ControlSystemSimulation(tipping_ctrl)
tipping
...
5
tipping
...
8
tipping
...
output['tip'])
tip
...
Demonstrate the use of linear discriminant analysis for a classification problem
...
pyplot as plt
from sklearn
...
model_selection import train_test_split
from sklearn
...
metrics import confusion_matrix
# Preparing dataset:
from sklearn
...
data
y = dt
...
fit_transform(X,y)
lda
...
xlabel('LD1')
plt
...
scatter(lda_t[:,0],lda_t[:,1],c=y,cmap='rainbow',edgecolor
s='black')
Practical 8 - CNN(Kmeans)
Q1
...
Perform Clustering of
MNIST dataset using CNN & K-means
# Importing necessary libraries
import numpy as np
import tensorflow as tf
from tensorflow
...
cluster import KMeans
from sklearn
...
pyplot as plt
# Load MNIST dataset
mnist = tf
...
datasets
...
load_data()
# Printing sample data images
for i in range(5):

plt
...
imshow(x_train[i], cmap='gray')
plt
...
axis('off')
plt
...
0, x_test / 255
...
expand_dims(x_train, axis=-1)
x_test = np
...
Sequential([
layers
...
MaxPooling2D(pool_size=(2, 2)),
layers
...
MaxPooling2D(pool_size=(2, 2)),
layers
...
Dense(128, activation='relu'),
layers
...
5),
layers
...
compile(optimizer='adam',
loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
cnn_model = build_cnn(input_shape=x_train[0]
...
utils import plot_model
plot_model(cnn_model, show_shapes=True, show_layer_names=True)
cnn_model
...
Model(inputs=cnn_model
...
layers[-2]
...
predict(x_train)
features_test = feature_extractor
...
fit(features_train)
# Predict clusters for test data
cluster_labels = kmeans
...
figure(figsize=(10, 10))
for cluster_id in range(10):
cluster_indices = np
...
subplot(10, 3, cluster_id*3 + i + 1)
plt
...
reshape(28, 28),
cmap='gray')
plt
...
title(f'Cluster {cluster_id}', fontsize=10)
# Show the plot
plt
...
show()
Practical 9 - Decision Tree and KNN algorithm
Q1
...

import numpy as np
import matplotlib
...
read_csv('Social_Network_Ads
...
iloc[:, :-1]
...
iloc[:, -1]
...
model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size = 0
...
preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc
...
transform(X_test)
from sklearn
...
fit(X_train, y_train)
from sklearn
...
Develop a K-NN model to predict whether the customer will make a purchase or not
based on age and salary
...
pyplot as plt
import pandas as pd
dataset = pd
...
csv')
X = dataset
...
values
y = dataset
...
values
from sklearn
...
25, random_state = 0)
from sklearn
...
fit_transform(X_train)
X_test = sc
...
neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 5, metric =
'minkowski', p = 2)
classifier
...
predict(X_test)
print(np
...
reshape(len(y_pred),1),
y_test
...
metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print(cm)
accuracy_score(y_test, y_pred)


Title: Artificial Intelligence Codes in python language
Description: These are codes for every method in AI and are well explained using comments within the codes. As I have also previously uploaded the theory notes for these. You can refer them for better understanding.