Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Master of Computer Application

Lab Manual

Subject: Artificial Intelligence and Soft Computing


Subject Code:PGCA1929

MCA 2nd Year –3rd Semester

CHANDIGARH ENGINEERING
COLLEGE
CGC-Landran, Mohali -140307
Chandigarh Engineering College-CGC
Landran, Mohali, Punjab
Masters of Computer Application

Artificial Intelligence and Soft Computing Laboratory (PGCA1929) C116


COURSE OUTCOMES

C116.1 Develop the skills to gain a basic understanding of neural network theory
and fuzzy logic theory.
C116.2 Apply artificial neural networks and fuzzy logic theory for various
problems.
C116.3 Determine the use of Genetic algorithms to obtain optimized solutions to
problems.
Chandigarh Engineering College-CGC
Landran, Mohali, Punjab
Masters of Computer Application

Artificial Intelligence & Soft Computing (PGCA1929) Year 2023-24

COURSE
OUTCOMES PROGRAMME OUTCOMES (2023-24)

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PS03

C116.1 3 1 3 2 1 1 2

C116.2 2 3 3 2 2 1 1 2 1

C116.3 3 2 1 2 1 2 1 2 1

PGCA-1929 3 2 2 2 2 1 2 1 2 1 2 1
Chandigarh Engineering College-CGC
Landran, Mohali, Punjab
Masters of Computer Application

Artificial Intelligence and Soft Computing (PGCA1929)

Internal Max. Marks:70

External Max. Marks:30 LTP

Total Marks: 100 004

Prac.No Name of Practical Page Releva


. No n
cet
o
Co
s
Use logic programming in Python to check for prime
1 numbers. 1 CO1
Use logic programming in Python parse a family
2. tree and infer the relationships between 2 CO1
thefamily members.
3 Python script for building a puzzle solver. 3 CO1
Implementation of uninformed search techniques
4 in Python. 4 CO1
Implementation of heuristic search techniques in
5 Python. 5 CO1
Python script for tokenizing text data.
6 6 CO2
Extracting the frequency of terms using a Bag of
7 Words model. 7 CO2

Predict the category to which a given piece of text


8 belongs. 8 CO2

Python code for visualizing audio speech signal


9 9 CO2
Python code for Generating audio signals
10 10 CO2
Create a perceptron with appropriate no. of inputs
and outputs. Train it using fixed increment
11 learning algorithm until no change in weights is
11 CO3

required.
Output the final weights.
Implement AND function using ADALINE
12 with bipolar inputs and outputs. 12 CO-3
Chandigarh Engineering College-CGC
Landran, Mohali, Punjab
Masters of Computer Application

Implement AND function using MADALINE with


13 bipolar inputs and outputs. 13 CO-3
Construct and test auto associative network for input
14 vector using HEBB rule. 14 CO-3
Construct and test auto associative network for
15 input vector using outer product rule. 15 CO-3
Construct and test hetero associative network for binary
16 inputs and targets. 16 CO-3
Create a back propagation network for a given input
17 pattern. Perform 3 epochs of operation. 17 CO-2
Implement Union, Intersection, Complement
and Difference operations on fuzzy sets.
18 Also create fuzzy relation by Cartesian product of 18 CO-2
any two fuzzy sets and perform maxmincomposition
on any two fuzzy relations.
Maximize the function f(x)=x2 using GA, where x
19 ranges form 0-25. Perform 6 iterations. 19 CO3

Content Beyond Syllabus


Write a program to construct a Bayesian network
20 20-21 CO3
from a given data

PREPARED BY: APPROVED BY:


LAB INCHARGE HOD(MCA)
Chandigarh Engineering College-CGC
Landran, Mohali, Punjab
Masters of Computer Application

IKGPTU Syllabus
Course Code: PGCA1929
Course Name: Artificial Intelligence & Soft Computing Laboratory

Program: MCA L: 0T: 0 P: 4


Branch: Computer Applications Credits: 4
Semester: 3rd Contact hours: 4 hours per week
Theory/Practical: Practical Percentage of numerical/design problems: --
Internal max. marks:70 Duration of end semester exam (ESE): 3hrs
External max. marks:30 Elective status: Core
Total marks: 100

Prerequisite: -NA-
Co-requisite: -NA-
Additional material required in ESE: -NA-

Course Outcomes: Students will be able:

CO# Course outcomes


CO1 Develop the skills to gain a basic understanding of neural network theory and fuzzy
logic theory.
CO2 Apply artificial neural networks and fuzzy logic theory for various problems.
CO3 Determine the use of Genetic algorithms to obtain optimized solutions to problems.
Instructions: Develop the assignments in MATLAB/Python.

Assignments:

1. Use logic programming in Python to check for prime numbers.


Use logic programming in Python parse a family tree and infer the relationships
2.
between thefamily members.
3. Python script for building a puzzle solver.
4. Implementation of uninformed search techniques in Python.
5. Implementation of heuristic search techniques in Python.
6. Python script for tokenizing text data.
7. Extracting the frequency of terms using a Bag of Words model.
8. Predict the category to which a given piece of text belongs.
9. Python code for visualizing audio speech signal
10. Python code for Generating audio signals
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Create a perceptron with appropriate no. of inputs and outputs. Train it using fixed
11. increment learning algorithm until no change in weights is required. Output the final
weights.
12. Implement AND function using ADALINE with bipolar inputs and outputs.
13. Implement AND function using MADALINE with bipolar inputs and outputs.
14. Construct and test auto associative network for input vector using HEBB rule.
15. Construct and test auto associative network for input vector using outer product rule.
16. Construct and test heteroassociative network for binary inputs and targets.
17. Create a back propagation network for a given input pattern. Perform 3 epochs of operation.
Implement Union, Intersection, Complement and Difference operations on fuzzy sets.
18. Also create fuzzy relation by Cartesian product of any two fuzzy sets and perform maxmin
composition on any two fuzzy relations.
19. Maximize the function f(x)=x2 using GA, where x ranges form 0-25. Perform 6 iterations.

Text Books:
1. Principles of Soft Computing, S.N. Sivanandam, S.N. Deepa, Wiley India
2. Artificial Intelligence with Python, Prateek Joshi, Packt Publishing.
3. Neural Networks, Fuzzy Logic and Genetic Algorithms: Synthesis& Applications ,
S.Rajasekaran, G. A. Vijayalakshami, PHI.
Reference Books:
1. Soft Computing: With Matlab Programming, N. P. Padhy, S. P. Simon, Oxford
HigherEducation
2. Neuro - Fuzzy & Soft Computing - C. T. Sun, E. Mizutani, J. S. R. Jang, Pearson
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 1: Use logic programming in Python to check for prime numbers.

Algorithm:

Step 1: Start
Step 2: Initialize variables num,flag=1, j=2
Step 3: Read num from user
Step 4: If num<=1 // Any number less than 1 is not a prime number
Display "num is not a prime number"
Goto step 7
Step 5: Repeat the steps until j<[(n/2)+1]
If remainder of number divide j equals to 0,
Set flag=0
Goto step 6
j=j+1
Step 6: If flag==0,
Display num+" is not prime number"
Else
Display num+" n is prime number"
Step 7: Stop

Flow Chart:

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 2: Use logic programming in Python parse a family tree and infer the
relationships between the family members.

Algorithm:-
Step 1:- family := a new map that contains lists as values
Step 2:- head := the current head of the family
dead := a set
Step 3:- Define a function birth() . This will take p_name, c_name
insert c_name at the end of family[p_name]
Step 4:- Define a function death() . This will take name
add(name) to the set dead
Step 5:- Define a function inheritance() . This will take
ans := a new list
depth_search(head)
return ans
Step 6:- Define a function depth_search() . This will take current
if current is not in dead, then
insert current at the end of ans
for each child in family[current], do
depth_search(child)

2
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 3: Python script for building a puzzle solver.

Algorithm:

Step 1:- We iterate through the puzzle from left to right from top to bottom.

Step 2:- Iterate through the puzzle till you find an empty cell.

Step 3:- Fill in a valid number. A valid number is the one that is neither in the row in which the cell
exists, the column in which the cell exists and the 3 x 3 block the cell exists. This is because no
number can repeat more than once in a row, column and in the 3 x 3 block.

Step 4:- Once you find a valid number, repeat steps 2 and 3.

Step 5:- While performing step 4, if we reach a point where no number is valid in the empty cell, we
backtrack and move to the previous cell filled by the algorithm to find the next valid number and
continue repeating the puzzle steps 2 and 3 using backtracking and finding the next valid number.
Backtracking might sound a bit complex but I shall take time and explain it along with the code
below.

Step 6:- Repeat process until no empty cell exists in the puzzle.

Output:

3
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab

Prog 4: Implementation of uninformed search techniques in Python.

Algorithm:

Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until QUEUE is empty

Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).

Step 5: Enqueue all the neighbors of N that are in the ready state (whose STATUS = 1) and set

their STATUS = 2

(waiting state)

[END OF

LOOP]

Step 6: EXIT

Output:

4
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab

Prog 5: Implementation of heuristic search techniques in Python.

Algorithm :-

Step 1: Evaluate the initial state. If it is the goal state, then return success and Stop.

Step 2: Loop Until a solution is found or there is no new operator left to apply.

Step 3: Select and apply an operator to the current state.

Step 4: Check new state:

If it is a goal state, then return to success and quit.

Else if it is better than the current state, then assign a new state as a current state.

Else if not better than the current state, then return to step2.

Step 5: Exit.

Output:

5
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application
Program 6: Python script for tokenizing text data.

Algorithm:
STEP 1 : As the frequency of ‘r_’ is highest (6+3), we combine ‘r_’ to form a new token.

STEP 2: As frequency of ‘er_’ is highest (6+3), we get ‘er_’

STEP 3: As the frequency of ‘ew’ is highest (6+2), we get ‘ew’

6
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 7: Extracting the frequency of terms using a Bag of Words model.

Algorithm:

Step 1: Convert the above sentences in lowercase as the case of the word does not hold any information.

Step 2: Remove special characters and stopwords from the text. Stopwords are words that do
not contain much information about the text like ‘is’, ‘a’,’the and many more’.
After applying the above steps, the sentences are changed to
Sentence 1: ”welcome great learning now start learning”
Sentence 2: “learning good practice”
Although the above sentences do not make much sense the maximum information is contained in these
words only.

Step 3: Go through all the words in the above text and make a list of all of the words in our model
vocabulary.
welcome
great
learning
now
start
good
practice

Output:

7
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Program 8: Python code for visualizing audio speech signal.


Algorithm:

Step1:-
Step2:- Load the audio file using a library like librosa.

Step3:- Obtain the audio waveform and sampling rate from the loaded file.

Step4:- Plot the waveform using a library like matplotlib.

Step5:- Convert the waveform to a spectrogram using the Short-Time Fourier Transform (STFT)
method from the libro library.

Step6:- Plot the spectrogram using librosa.display.specshow().

Step7:- Display the waveform and spectrogram plots.

Step8:-
Output:

8
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Program 9: Implement AND function using ADALINE with bipolar inputs


and outputs.

Algorithm:
Step 2:- Initialize weights randomly for each input feature.
Step 1:-
Step 3:- Define the bipolar activation function: f(x)=1 if x≥0,−1 otherwise.

Step 4:- Define learning rate ( α) and maximum epochs.

Step 5:- Prepare the dataset with bipolar inputs and outputs for the AND function.

Step
 6:- For eachtheepoch
Calculate weighted sum of inputs: weighted_sum=∑i(input[i]×weights[i]).
 Compute the predicted output using the bipolar activation function:
For each training example (input, target)
prediction=activation(weighted_sum) prediction=activation(weighted_su .
 Compute the error: error=target−prediction error=target−predictio .
 Update weights: weights[i]=weights[i]+α×error×input[i].

Step 7:- End epochs


Step 8:- Test the ADALINE model with test inputs.

Step 9:- Display the predicted outputs.

Step 10:-

Output:

9
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 10: Create a back propagation network for a given input pattern. Perform 3
epochs of operation.

Algorithm:

Step1:-
 Define the neural network architecture (number of layers, neurons in each layer).
 Initialize weights and biases randomly.
Step2:-
 SetInitialize
learning rate ( α) and the number of epochs.

Step3:- For each epoch do:


 For each training example do:

Compute the weighted sum and activation for each neuron in each layer.
Forward
Pass the inputs through the network to get the predicted output.
 Calculate
Compute the error between the predicted output and the actual target.
 Backpropagatio
Compute the gradient of the error with respect to the output layer.
Backpropagate the gradient through the network to update the weights and biases.

 End Training Example

Step4:- End Epoch

Step5:-

Outp

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 11. Python Program to Check Prime Number

Algorithm:-

Step1:- Start

Step2:- Read the input number n.

Step3:- If n is less than 2, it's not a prime number. Go to step 9.

Step4:- Initialize a variable is_primeis_prime to True


.
Step5:- Loop i from 2 to n:

 If n is divisible evenly by i, set is_primeis_prime to False and break the loop.

Step6:- If is_primeis_prime is True, n is a prime number. Go to step 8


.
Step7:- If is_primeis_prime is False, n is not a prime number.

Step8:- Print n is a prime number.

Step9:- End

Flowchart:

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

er:1717 is

Prog 12. WAP How to append element in the list?

Algorithm:-

Step1:- Start

Step2:- Read the element to be appended (new_element).

Step3:- Initialize the list (my_list) with the existing elements or as an empty list if starting from

scratch. Step4:- Append new_element to my_list using the append() method.

Step5:- Optionally, repeat steps 2-4 to append more elements to the list.

Step6:- If you want to append elements from another list, use the extend() method.

Step7:- If you want to insert an element at a specific position, use the insert(index, element) method.

Step8:- Print or use my_list for further operations.

Step9:- End

Flowchart:

Current names List is: ['Joseph',


'Peter', 'Cook', 'Tim']

Please enter a name:


Devansh
Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 13. Python program to create a Circular Linked List of N nodes and count the
number of nodes?

Algorithm:

Step1:-
Step2:- Initialize a class
No with attributes and next.
 data stores the value of the node. da
 next points to the next node in the list.

Sep3:- Initialize a class


linked list. CircularLinkedLi with a method append(dat to add nodes to the circular
 Create a new node with the given data.
 If the list is empty, set the new node as the head and point its next to itself.
 If the list is not empty, traverse to the last node and update its next to the new node. Set the new
node's ne to the head to maintain the circular structure.

Step4:- Initialize a method


count_nodes in the CircularLinkedLi class to count the number of nodes
in the circular linked list.
 If the list is empty, return 0.
 Initialize a count variable to 1 and a temporary pointer pointing to the next node after the head.
 Traverse the list until the pointer reaches the head, incrementing the count for each node visited.
 Return the count.

Step5:-
Flowchart:

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Count of nodes present in circular li


Prog 14. Python Function to Display Calendar

Algorithm:

Step1:-
Step 2:- Accept the input for the month from the user.
 If the input is not a valid integer between 1 and 12, display an error message and go to step 2.

Step 3:- Accept the input for the year from the user.
 If the input is not a valid integer, display an error message and go to step 3.

Step 4:- Check if the input month is between 1 and 12 (inclusive).


 If not, display an error message and go to step 2.

Step 5:- Generate the calendar for the specified month and year using the calendar.month(year, month).

Step 6:- Display the generated calendar.

Step7:-

Flowchart

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application
Prog 15. Bubble Sort in Python

Algorithm:-
Step1:- Start

Step2:- Initialize a variable swapped to True indicating that a swap has occurred.

Step3:- Repeat the following steps until swapped is False (meaning no more swaps are needed):

a. Set swapped to False.


b. Iterate through the list from the first element to the second-to-last element:

 If the current element is greater than the next element:


 Swap the current element and the next element.
 Set swapped to True to indicate that a swap has occurred.

Step4:- If no swaps occurred in the last pass, the list is sorted. If swaps occurred, repeat step 3.

Step5:- End

Flowchart:

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application
The unsorted list is: [5, 3, The unsorted list is
Prog 16. Python program to search an element in a doubly linked list.

Algorithm:

Step 1:- Start

Step 2:- Create a class Node with attributes data, prev (pointer to the previous node), and next
(pointer to the next node).

Step 3:- Create a class Doubly LinkedList with methods append(data) to add nodes and search(key)
to search for an element in the list.

Step 4:- Initialize an empty Doubly Linked List (dll).

Step 5:- To append(data):


 Create a new node with the given data.
 If the list is empty (dll. head is None), set the new node as the head.
 If the list is not empty, traverse to the last node, update its next to the new node, and set the new
node's prev to the last node.
Step 6:- To search(key):
 Start from the head of the list (current = dll. head).
 While current is not None, compare current. data with the key.
 If they are equal, the element is found. Return True.
 If not, move to the next node (current = current. next).
 If the end of the list is reached and the element is not found, return False.
Step 7:- End

Flowchart:

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application
Prog 17. Python Program to generate a Random String

Algorithm:

Step1:- Start

Step2:- Accept the input for the desired length of the random string.

Step3:- Define a string characters containing all possible characters that can be used in
the random string (usually, this includes uppercase letters, lowercase letters, and digits).

Step4:- Initialize an empty string random_string to store the generated random string.

Step5:- Repeat the following steps length times:


a. Randomly select a character from the characters string.
b. Add the selected character to the random_string.

Step6:- The random_string now contains a random string of the specified length.

Step7: End

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application
Prog 18. How to convert int to string in Python
Algorithm:-

Step 1:- Start

Step 2:- Accept the integer input that needs to be converted to a string
.
Step 3:- Use the str() function to convert the integer to a string.

Step 4:- The result is the string representation of the input integer.

Step 5:- End

Output:

<class 'int'>
25

<class 'str'>
25

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

Prog 19. Python program to rotate doubly linked list by N nodes.

Algorithm:-

Step 1:- Start

Step 2:- Accept the input for the number of nodes to rotate (N).

Step 3:- Create a class Node with attributes data, prev (pointer to the previous node), and next (pointer to the
next node).

Step 4:- Create a class Doubly Linked List with methods append(data) to add nodes and rotate(N) to rotate the
list by N nodes.

Step 5:- Initialize an empty doubly linked list (dll).

Step 6:- To append(data):


 Create a new node with the given data.
 If the list is empty (dll. head is None), set the new node as the head.
 If the list is not empty, traverse to the last node, update its next to the new node, and set the new node's
prev to the last node.

Step 7:- To rotate(N):


 Traverse the list to find the Nth node (current).
 If the Nth node is None, the list is rotated back to its original position, no changes are made.
 Otherwise, update the pointers to rotate the list:
 Set the next of the last node to the current head.
 Set the prev of the current head to the last node.
 Set the head of the list to the next of the Nth node.
 Set the prev of the new head to None.
 Set the next of the Nth node to None.

Step 8:- End

Original List:
12345
Updated List:
45123

1
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

20. Write a program to construct a Bayesian network from a given data.

Algorithm:-

Step1:- Start

Step 2:- Import necessary libraries: from pgmpy.models import BayesianNetwork and from pgmpy. factors.
discrete import Tabular CPD.

Step 3:- Define the dataset: Specify the variables (A, B, C) and their corresponding values based on the given
data.

Step 4:- Define the structure of the Bayesian Network:


 Create an instance of Bayesian Network.
 Specify the edges representing the relationships between variables (A -> C and B -> C).

Step 5:- Define Conditional Probability Distributions (CPDs) for each variable:
 Create Tabular CPD instances for each variable, specifying variable name, cardinality (number of
states), and conditional probability values based on the given data.

Step 6:- Add the CPDs to the Bayesian Network model using the add_cpds() method.

Step 7:- Verify if the model is valid using the check_model() method.
 If the model is not valid, handle errors or adjust CPDs as needed.

Step 8:- Optionally, perform inference on the constructed model to answer probabilistic queries:
 Create an instance of Variable Elimination for inference.
 Use the query() method to perform queries, specifying variables and evidence.

Step 9:- Print the Bayesian Network structure (edges) and CPDs.

Step10:- End

2
Chandigarh Engineering College-
CGC Landran, Mohali, Punjab
Masters of Computer Application

You might also like