0% found this document useful (0 votes)
20 views32 pages

AAI Pract 3 To 12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views32 pages

AAI Pract 3 To 12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Advanced AI

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject: Advanced AI Seat No: PIT24306
CERTIFICATE

This is to certify that the experiment work entered in


this journal is as per the syllabus in M.Sc. (Information
Technology) Part-II Semester-III class prescribed by University of
Mumbai for the subject “Advanced AI” was done in Computer
Lab of “Changu Kana Thakur College of Arts, commerce & science
at New Panvel” by Mrs Harshada Mayur Suryawanshi during
academic year 2024-2025.

Exam Seat No.: PIT 24306

Subject In-charge Co-ordinator M.Sc.(IT)

External Examiner

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject: Advanced AI Seat No: PIT24306
INDEX

No. Practical Name Date Sign

2
3 Implement Bayes Theorem using Python
4 Implement Conditional Probability and
joint probability using Python
5 Write a Program to implement BFS
algorithm.
6

7
8

10

11

12

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject: Advanced AI Seat No: PIT24306
Practical No. 03
Aim: Implement Bayes Theorem using Python.

Bayes’ Theorem states the following for any two events A and B:

P(A|B) = P(A)*P(B|A) / P(B)

where:

 P(A|B): The probability of event A, given event B has occurred.


 P(B|A): The probability of event B, given event A has occurred.
 P(A): The probability of event A.
 P(B): The probability of event B.

For example, suppose the probability of the weather being cloudy is 40%.

Also suppose the probability of rain on a given day is 20%.

Also suppose the probability of clouds on a rainy day is 85%.

If it’s cloudy outside on a given day, what is the probability that it will rain that
day?

Solution:

 P(cloudy) = 0.40
 P(rain) = 0.20
 P(cloudy | rain) = 0.85

Thus, we can calculate:

 P(rain | cloudy) = P(rain) * P(cloudy | rain) / P(cloudy)


 P(rain | cloudy) = 0.20 * 0.85 / 0.40
 P(rain | cloudy) = 0.425

If it’s cloudy outside on a given day, the probability that it will rain that day
is 42.5%.

We can create the following simple function to apply Bayes’ Theorem in Python:

def bayesTheorem(pA, pB, pBA):


return pA * pBA / pB

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
The following example shows how to use this function in practice.

Example: Bayes’ Theorem in Python

Suppose we know the following probabilities:

 P(rain) = 0.20
 P(cloudy) = 0.40
 P(cloudy | rain) = 0.85

To calculate P(rain | cloudy), we can use the following program:

#define function for Bayes' theorem


def bayesTheorem(pA, pB, pBA):
return pA * pBA / pB

#define probabilities
pRain = 0.2
pCloudy = 0.4
pCloudyRain = 0.85

#use function to calculate conditional probability


bayesTheorem(pRain, pCloudy, pCloudyRain)

0.425

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 04
Aim: Implement Conditional Probability and joint probability using Python.

Conditional Probability

Conditional probability, given by P(X | Y), is the probability of an event X


happening given that Y has occurred.

The formula for conditional probability is:

Where:

 P(X ∩ Y) is the joint probability of events X and Y


 P(Y) is the probability of Y

Joint Probability

Joint Probability represents the likelihood that two events, X and Y, occur together.
It’s denoted as P(X = x, Y = y), which can be read as the probability that both X = x
and Y = y are true.

The formula for calculating joint probability, P(X = x, Y = y), using conditional
probabilities, is:

This expression means that the joint probability of X and Y can be calculated by:

1. Multiplying P(Y = y | X = x) with P(X = x) or


2. Multiplying P(X = x | Y = y) with P(Y = y).

Calculating Joint and Conditional Probabilities in Python

Let’s use a dataset of individuals categorized by age group and interest in sports and
compute joint and conditional probabilities.

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Step 1: Creating Sample Data

Let’s create a sample dataset to use for our probability calculations.

Step 2: Calculating Joint Probability

We’ll calculate the joint probability of a person being in the “Teen” age group and
having an interest in sports (“Yes”).

 Define the conditions: We want both Age Group == “Teen” and


Sports_Interest == “Yes”
 Calculate the total number of observations.
 Count the occurrences that meet both conditions and divide by the total.

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Step 3: Calculating Conditional Probability

Now, let’s calculate the conditional probability of a person having an interest in


sports, given that they are a “Teen”.

Use only “Teen” rows (filter on “Age_Group”).


Calculate the probability of “Sports_Interest = Yes” within this filtered subset.

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Step 4: Defining Reusable Functions

To make these calculations more flexible, we’ll define two functions: one for joint
probability and one for conditional probability.

def calculate_joint_probability(df, condition1, condition2):


total_count = len(df)
joint_count = len(df[(df[condition1[0]] == condition1[1]) &
df[condition2[0]] == condition2[1])])
return joint_count / total_count

def calculate_conditional_probability(df, given_condition,


target_condition):
subset = df[df[given_condition[0]] == given_condition[1]]
conditional_count = len(subset[subset[target_condition[0]] ==
target_condition[1]])
return conditional_count / len(subset)

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Now let’s use the function calls with the conditions for our example:

# Joint Probability
joint_prob = calculate_joint_probability(df, ("Age_Group",
"Teen"), ("Sports_Interest", "Yes"))
print("Joint Probability (Teen and Sports Interest Yes):",
joint_prob)

# Conditional Probability
conditional_prob = calculate_conditional_probability(df,
("Age_Group", "Teen"), ("Sports_Interest", "Yes"))
print("Conditional Probability (Sports Interest Yes | Age Group
Teen):", conditional_prob)

This should give a similar output:

Joint Probability (Teen and Sports Interest Yes): 0.25


Conditional Probability (Sports Interest Yes | Age Group Teen):
0.667

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No: 05

Aim: Write a Program to implement BFS algorithm.


Program:

from collections import deque

# BFS from given source s


def bfs(adj, s):
# Create a queue for BFS
q = deque ()
# Initially mark all the vertices as not visited
# When we push a vertex into the q, we mark it as
# visited
visited = [False] * len(adj);
# Mark the source node as visited and enqueue it
visited[s] = True
q.append(s)
# Iterate over the queue
while q:
# Dequeue a vertex from queue and print it
curr = q.popleft()
print(curr, end=" ")
# Get all adjacent vertices of the dequeued
# vertex. If an adjacent has not been visited,
# mark it visited and enqueue it
for x in adj[curr]:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
if not visited[x]:
visited[x] = True
q.append(x)
# Function to add an edge to the graph
def add_edge(adj, u, v):
adj[u].append(v)
adj[v].append(u)
# Example usage
if __name__ == "__main__":
# Number of vertices in the graph
V=5
# Adjacency list representation of the graph
adj = [[] for _ in range(V)]
# Add edges to the graph
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 3)
add_edge(adj, 1, 4)
add_edge(adj, 2, 4)
# Perform BFS traversal starting from vertex 0
print("BFS starting from 0: ")
bfs(adj, 0)

Output:

BFS starting from 0 :


0 1 2 3 4

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 06
Aim: Write a Program to implement DFS algorithm.

Program:

def dfs_rec(adj, visited, s):


# Mark the current vertex as visited
visited[s] = True
# Print the current vertex
print (s, end=" ")
# Recursively visit all adjacent vertices
# that are not visited yet
for i in adj[s]:
if not visited[i]:
dfs_rec(adj, visited, i)
def dfs(adj, s):
visited = [False] * len(adj)
# Call the recursive DFS function
dfs_rec(adj, visited, s)
def add_edge(adj, s, t):
# Add edge from vertex s to t
adj[s].append(t)
# Due to undirected Graph
adj[t].append(s)
if __name__ == "__main__":

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
V=5

# Create an adjacency list for the graph


adj = [[] for _ in range(V)]
# Define the edges of the graph
edges = [[1, 2], [1, 0], [2, 0], [2, 3], [2, 4]]
# Populate the adjacency list with edges
for e in edges:
add_edge(adj, e[0], e[1])
source = 1
print("DFS from source:", source)
dfs(adj, source)

Output:

DFS from source: 1


1 2 0 3 4

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 07

Aim: Implementation of Python math Libraries.

1. Importing Math Module

import math

2. Euler’s Number

import math

print (math.e)

3. Pi

import math

print (math.pi)

4. find the area of the circle

import math

r=4

pie = math.pi

print(pie * r * r)

5. Finding the factorial of the number

import math

a=5

print ("The factorial of 5 is: ", end="")

print (math. Factorial(a))

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
6. Finding the power of exp

import math

test_int = 4

test_neg_int = -3

test_float = 0.00

print (math.exp(test_int))

print (math.exp(test_neg_int))

print (math.exp(test_float))

7. Finding the Logarithm

import math

print ("The value of log 2 with base 3 is: ", end="")

print (math.log (2,3))

print ("The value of log2 of 16 is: ", end="")

print (math.log2(16))

print ("The value of log10 of 10000 is: ", end="")

print (math.log10(10000))

8. Finding the Square root

import math

print(math.sqrt(0))

print(math.sqrt(4))

print(math.sqrt(3.5))

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
9. Finding sine, cosine, and tangent

import math

a = math.pi/6

print ("The value of sine of pi/6 is : ", end="")

print (math.sin(a))

print ("The value of cosine of pi/6 is : ", end="")

print (math.cos(a))

print ("The value of tangent of pi/6 is : ", end="")

print (math.tan(a))

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 08

Aim: Implementation of Python math Libraries.

1.Find How many cubic meters are in one liter?

from SciPy import constants

print(constants.liter)

2.Find root of the equation x + cos(x):

from scipy.optimize import root


from math import cos

def eqn(x):
return x + cos(x)

myroot = root(eqn, 0)

print(myroot.x)

3. Minimize the function x^2 + x + 2 with BFGS:

from scipy.optimize import minimize

def eqn(x):
return x**2 + x + 2

mymin = minimize(eqn, 0, method='BFGS')

print(mymin)

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
4. Find the shortest path from element 1 to 2

import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

arr = np.array([
[0, 1, 2],
[1, 0, 0],
[2, 0, 0]
])

newarr = csr_matrix(arr)

print(dijkstra(newarr, return_predecessors=True, indices=0))

5. Use the floyd_warshall() method to find shortest path between all pairs of
elements.

import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix

arr = np.array([
[0, 1, 2],
[1, 0, 0],
[2, 0, 0]
])

newarr = csr_matrix(arr)

print(floyd_warshall(newarr, return_predecessors=True))

6. Use bellman ford(), Find shortest path from element 1 to 2 with given graph
with a negative weight:

import numpy as np
from scipy.sparse.csgraph import bellman_ford

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
from scipy.sparse import csr_matrix

arr = np.array([
[0, -1, 2],
[1, 0, 0],
[2, 0, 0]
])

newarr = csr_matrix(arr)

print(bellman_ford(newarr, return_predecessors=True, indices=0))

7. Traverse the graph depth first for given adjacency matrix

import numpy as np
from scipy.sparse.csgraph import depth_first_order
from scipy.sparse import csr_matrix

arr = np.array([
[0, 1, 0, 1],
[1, 1, 1, 1],
[2, 1, 1, 0],
[0, 1, 0, 1]
])

newarr = csr_matrix(arr)

print(depth_first_order(newarr, 1))

8. Traverse the graph breadth first for given adjacency matrix:

import numpy as np
from scipy.sparse.csgraph import breadth_first_order
from scipy.sparse import csr_matrix

arr = np.array([
[0, 1, 0, 1],
[1, 1, 1, 1],

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
[2, 1, 1, 0],
[0, 1, 0, 1]
])

newarr = csr_matrix(arr)

print(breadth_first_order(newarr, 1))

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 09

Aim: Implementation of Python pandas Libraries.

Working with Pandas Library

Pandas is an open-source library for data analysis and manipulation. It provides a


wide range of data structures and tools for working with data. It is designed for easy
data wrangling and manipulation and can be used for a variety of tasks such as data
cleaning, data analysis, data visualization, and more. Pandas can be used for data
analysis in Python and other languages such as R and Julia. Give python example
Here is an example of using Pandas to read a CSV file and display the data as a
table:

Program 1:

# Import pandas

import pandas as pd

# reading csv file

df = pd.read_csv("example1.csv")

print(df)

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Program 2:

# Import pandas package

import pandas as pd

# Assign data

data = {'Name': ['Jai', 'Princi', 'Gaurav',

'Anuj', 'Ravi', 'Natasha', 'Riya'],

'Age': [17, 17, 18, 17, 18, 17, 17],

'Gender': ['M', 'F', 'M', 'M', 'M', 'F', 'F'],

'Marks': [90, 76, 'NaN', 74, 65, 'NaN', 71]}

# Convert into DataFrame

df = pd.DataFrame(data)

# Display data

print(df)

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 10
Aim: Implementation of Python Numpy Libraries.

1)Vector

Output:

2)2D Matrix

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 11
Aim: Implementation of Python Numpy Libraries.

1.Bar Graph

import numpy as np

import matplotlib.pyplot as plt

# creating the dataset

data = {'C':20, 'C++':15, 'Java':30, 'Python':35}

courses = list(data.keys())

values = list(data.values())

fig = plt.figure(figsize = (10, 5))

# creating the bar plot

plt.bar(courses, values, color ='maroon', width = 0.4)

plt.xlabel("Courses offered")

plt.ylabel("No. of students enrolled")

plt.title("Students enrolled in different courses")

plt.show()

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
2.Histogram

import matplotlib.pyplot as plt

import numpy as np

# Generate random data for the histogram

data = np.random.randn(1000)

# Plotting a basic histogram

plt.hist(data, bins=30, color='skyblue', edgecolor='black')

# Adding labels and title

plt.xlabel('Values')

plt.ylabel('Frequency')

plt.title('Basic Histogram')

# Display the plot

plt.show()

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
3.Line

Program:

import matplotlib.pyplot as plt

import numpy as np

x = np.array([1, 2, 3, 4])

y = x*2

plt.plot(x, y)

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.title("Any suitable title")

plt.show() # show first chart

# The figure() function helps in creating a

# new figure that can hold a new chart in it.

plt.figure()

x1 = [2, 4, 6, 8]

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
y1 = [3, 5, 7, 9]

plt.plot(x1, y1, '-.')

# Show another chart with '-' dotted line

plt.show()

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
4.Scatter

Program:

import matplotlib.pyplot as plt

x =[5, 7, 8, 7, 2, 17, 2, 9,

4, 11, 12, 9, 6]

y =[99, 86, 87, 88, 100, 86,

103, 87, 94, 78, 77, 85, 86]

plt.scatter(x, y, c ="blue")

# To show the plot

plt.show()

Output:

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
Practical No. 12

Aim: Implement Linear Regression: Using scikit-learn, implement


and train a linear regression model on a simple dataset.
# Python code on sklearn linear regression example

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
# Importing required libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# Loading the sklearn diabetes dataset


X, Y = load_diabetes(return_X_y=True)

# Taking only one feature to perform simple linear regression


X = X[:,8].reshape(-1,1)

# Splitting the dependent and independent features of the dataset into training
and testing dataset
X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 0.3, rand
om_state = 10 )

# Creating an instance for the linear regression model of sklearn


lr = linear_model.LinearRegression()

# Training the model by passing the dependent and independent features of th


e training dataset
lr.fit( X_train, Y_train )

# Creating an array of predictions made by the model for the unseen or test da
taset
Y_pred = lr.predict( X_test )

# The value of the coefficients for the independent feature through the multipl
e regression model
print("Value of the oefficients: \n", lr.coef_)

# The value of the mean squared error


print(f"Mean square error: {mean_squared_error( Y_test, Y_pred)}")

# The value of the coefficient of determination, i.e., R-square score of the mo


del
print(f"Coefficient of determination: {r2_score( Y_test, Y_pred )}")

# Plotting the output

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306
plt.scatter(X_test, Y_test, color = "black", label = "original data")
plt.plot(X_test, Y_pred, color = "blue", linewidth=3, label = "regression line"
)
plt.xlabel("Independent Feature")
plt.ylabel("Target Values")
plt.title("Simple Linear Regression")
plt.show()

Output:

Value of the coefficients:


[875.72247876]
Mean square error: 4254.602428877642
Coefficient of determination: 0.3276195356900222

Name: Harshada Suryawanshi Class: M.Sc.IT (Part II)


Subject : Advanced AI Seat No: PIT24306

You might also like