Artificial_Intelligence_Lab_Manual_BCA6_UGCA1945
Artificial_Intelligence_Lab_Manual_BCA6_UGCA1945
Sr. Contents
No.
1. Institute V/M; Department V/M/PEO; PO/PSO Statements
2. Academic Calendar
3. Lab Course Syllabus
4. Lab Course Data Sheet (with Complete details)
5. Lab Course Outcomes – Assessment Plan Sheet
6. Time Table of the Concerned Faculty Member
7. Detailed Lab Course Coverage
8. Lab Manuals
9. Quiz/Viva Sample Questions
10. Continuous Evaluation ( Lab Evaluation Sheets)
11. Sample Experiment Files (Two best , Two average & Two poor students)
12. Gaps & Plans for Add-on Experiments
13. Value Aided Experiments/Design Experiment/Open Ended Experiments
Any Innovative Method Adopted; Description (I.e. Projects/ charts/
14. PPTs/ Videos etc.)
15. Internal Awards Compilation Record (on Attached Performa)
Lab Course Outcomes Assessment (For NBA), Corrective Actions on CO Attainments
16.
Institute Vision
"To emerge as the most preferred educational group with global recognition, developing competent
and socially sensitive leaders committed to excellence."
Institute Mission
To make incessant endeavor to translate our vision into a reality & achieve the following objectives:
• To create world class facilities & ambiance for advance level of teaching and
practical training.
• To develop students as global citizens with conscience, commitment & education.
• To continuously grow & become fountain head among Institutes of Technical
Higher Education in India.
• To strengthen Industry-Institute Interface & promote Entrepreneurial development activities.
• To continuously strive for research, development & innovation in all relevant fields,
thereby providing the faculty & students the requisite platform to showcase their talents &
win laurels.
• To have collaboration with leading Universities of the world with a view to
provide opportunities to the students for higher studies & seek placement avenues
abroad.
• To maintain the first position in placements in the North region, thereby ensuring that
every CGCians gets the best possible placement opportunities.
Department Vision
To provide imperative skills to students for meeting industry needs, and to become responsible
engineers, entrepreneurs and citizens.
Department Mission
• To educate the students in the field of Computer-Science with ever-changing
technologies and skills.
• To enable the students in solving real-time problems and make use of new technologies.
• To have industry collaboration and interaction with professional societies for
continuous development.
• To help students in becoming successful entrepreneurs.
PEOs
PEO 1: To impart core theoretical and practical knowledge of Graphics and Web Designing for
PEO 2: To develop the ability to critically think, analyze, design and develop Graphics and Web based
solutions.
PEO 3: To imbibe the life-long learning and understanding of ethical values, their duties toward
environmental issues and sensitize them toward their social responsibility as Graphics Designer and
Web Developer.
PSOs
PSO 1: Able to acquire practical competency with emerging technologies and skills needed for
PSO 2: Able to assess hardware and software aspects necessary to develop Graphics and Web
Designing
Program Outcomes (PO’s)
Program: BCA L: 0 T: 0 P: 4
Branch: BSC GWD Credits: 2
Semester: 6th Contact hours: 4 hours per week
Internal max. marks: 60 Theory/Practical: Practical
External max. marks: 40 Duration of end semester exam (ESE): 3hrs
Total marks: 100 Elective status: Core
Course Outcomes:
CO Course outcomes
#
CO1 Illustrate right tool for different AI based problems.
CO4 Determine the use of the Bayesian approach and NLP to solve uncertain problems.
Assignments:
2. Python script for comparing mathematical expressions and finding out unknown values.
3. Use logic programming in Python to check for prime numbers.
4. Use logic programming in Python parse a family tree and infer the relationships
between the family members.
6. Implementation of Naïve Bayes classifier, computing its accuracy and visualizing its
performance.
7. Creation of a fuzzy control system which models how you might choose to tip at a
restaurant.
8. Implementation of uninformed search techniques in Python.
TEXT/REFERENCE BOOKS:
R1 Artificial Intelligence with Python, Prateek Joshi, Packt Publishing.
COURSE PRE-REQUISITES:
Prerequisite: - Working Knowledge of Python Programming Language
COURSE OUTCOMES:
SNo DESCRIPTION
.
CO Illustrate right tool for different AI based problems.
1
CO Develop basic applications using AI tool.
2
CO List various real life problem domains using logic based techniques.
3
CO Determine the use of the Bayesian approach and NLP to solve uncertain problems.
4
POs REFERENCE:
PO1 Graphics knowledge PO7 Environment and sustainability
PO2 Problem analysis PO8 Ethics
PO3 Design/development of solutions PO9 Individual and team work
Conduct investigations of complex
PO4 problems PO1 Communication
0
PO5 Modern tool usage PO1 Project management and finance
1
PO6 The engineer and society PO1 Life-long learning
2
DELIVERY/INSTRUCTIONAL METHODOLOGIES:
✔ CHALK & TALK, PPT ✔ STUD. ASSIGNMENT ✔ WEB RESOURCES ✔ NPTEL/OTHERS
✔ LCD/SMART BOARDS ✔ STUD. SEMINARS ☐ ADD-ON COURSES ☐ WEBNIARS
ASSESSMENT METHODOLOGIES-DIRECT
✔ ASSIGNMENTS ✔ STUD. SEMINARS ✔ TESTS/MODEL ✔ UNIV. EXAMINATION
EXAMS
✔ STUD. LAB ☐ STUD. VIVA ☐ MINI/ ☐ CERTIFICATIONS
PRACTICES MAJOR
PROJECTS
☐ ADD-ON COURSES ☐ OTHERS
ASSESSMENT METHODOLOGIES-INDIRECT
✔ ASSESSMENT OF COURSE OUTCOMES (BY ✔ STUDENT FEEDBACK ON FACULTY (TWICE)
FEEDBACK, ONCE)
☐ ASSESSMENT OF MINI/MAJOR PROJECTS BY ☐ OTHERS
EXT. EXPERTS
Provide research-based and world-class computer education and training, and produce ethically
sound and technically competent versatile professionals.
MISSION:
● Develop the ability to adapt to technological skills to fulfill the challenges of the
ever- evolving global world.
● Students get to know about business software and help them to analyze the
requirements for developing systems.
● BCA graduates from CGC Jhanjeri will have the option to specialize in system
software, legacy application software or mobile applications.
8. Implementation of uninformed
search techniques in CO2 20/02/25
Python.
9. Implementation of heuristic search techniques
in Python. CO2 27/02/25
Theory:-
In logic programming, a fact is a basic assertion about the world, such as a parent-child relationship, which
forms the foundational element of the program. A rule defines logical relationships between facts and allows
new facts to be inferred. Queries are questions posed to the system to retrieve information based on the
defined facts and rules. Unification is the process of matching logical expressions by finding suitable variable
substitutions, enabling pattern matching and inference. Backtracking is a method used to explore all possible
solutions by trying one path at a time and reversing if a solution fails. In Python, facts can be represented using
simple data structures, and rules can be implemented as functions. The query method is used to extract
meaningful information from the logic program by evaluating these facts and rules
Program/Code:-
False
# Driver code if
_name=='main_':
print(AND(1, 0))
print("+ +
# working of OR gate
return False
# Driver code if
_name=='main_':
print(OR(0, 0))
print("+ +
+") print(" | OR
== 1 and b == 1:
return False
else:
return True
# Driver code if
_name=='main_':
print(NAND(1, 0))
print("+ +
+") print(" |
if a != b:
return 1
else: return 0
# Driver code if
_name=='main_':
print(XOR(5, 5))
print("+ +
def NOT(a):
return not a
# Driver code if
_name=='main_':
print(NOT(0))
=",NOT(True)," | ")
return 0
return 0
return 0
# Driver code if
_name=='main_':
print(NOR(0, 0))
print("+ +
+") print(" |
def XNOR(a,b):
if(a == b):
else:
return 0
return 1
# Driver code if
_name=='main_':
print(XNOR(1,1))
print("+ +
+") print(" |
y = symbols('x y')
{sol_dict[y]}')
Sample Viva voice Questions
(num % i) == 0:
print(num,"is a prime
Theory:- Logic programming can be effectively used to parse a family tree and infer relationships between
family members by defining facts and rules. Facts represent direct relationships, such as parent-child pairs.
Rules are used to infer additional relationships, such as siblings or grandparents, based on existing facts. For
instance, siblings can be inferred by identifying children with the same parents. The logic program queries
these facts and rules to derive new relationships. This declarative approach allows the separation of the logic
(what the relationships are) from the control (how to derive them), making it easier to understand and modify.
Program/Code:-
kanren
import json
conde([father(x,y)], [mother(x,y)])
def
grandparent(x,y):
return
conde((father(temp,x), grandparent(temp,y)))
return
conde((father(temp,x), grandparent(temp,y))) if
Relation() with
open(r'/content/relationship.json') as f:
d = json.loads(f.read())
facts(father,(list(item.keys())[0], list(item.values())[0]))
[0])) x = var()
print(item)
'Adam'
print(item)
print(item)
print(item)
# David's siblings name = 'David'
print(item)
item in output:
print(item)
output=run(0,(a,b),(father,a,c),
print('Husband:',item[0],'<==> Wife:',item[1])
Relationship.json file
"father":[
{"John":"William"},
{"John":"David"},
{"John":"Adam"},
{"William":"Chris"},
{"William":"Stephanie"},
{"David": "Wayne"},
{"David":"Tiffany"},
{"David":"Julie"},
{"David":"Neil"},
{"David":"Peter"},
{"Adam":"Sophia"}
],
"mother":[
{"Megan":"William"},
{"Megan":"David"},
{"Megan":"Adam"},
{"Emma":"Stephanie"},
{"Emma":"Chris"},
{"Olivia":"Tiffany"}
{"Olivia":"Julie"},
{"Olivia":"Neil"},
{"Olivia":"Peter"},
{"Lily":"Sophia"}
]}
OUTPUT:-
2. What is the advantage of using logic programming for parsing a family tree?
3. Can logic programming handle complex family relationships?
4.
var()
= lall(
print('\t\t'.join(attribs)) print('=' *
Aim:- Implementation of Naïve Bayes classifier, computing its accuracy and visualizing its performance
Objective:- The objective is to implement a Naïve Bayes classifier, evaluate its accuracy, and visualize its
performance on a dataset.
Theory:-
The Naïve Bayes classifier is a probabilistic machine learning model based on Bayes' theorem, with the
"naïve" assumption of feature independence. Despite its simplicity, it is highly effective for many
classification problems. The classifier estimates the probability of a class given a set of features and
chooses the class with the highest probability. The objective of this experiment is to implement the Naïve
Bayes classifier, evaluate its performance in terms of accuracy, and visualize the results using a
confusion matrix. This allows us to understand the strengths and weaknesses of the model and how well
it performs on a given dataset.
Program/Code:-
pandas as pd
iris = pd.read_csv('/content/Iris.csv')
iris
iris.info()
iris.head()
iris.drop('Id',axis=1,inplace=True)
iris
= iris['Species']
= tree_model.fit(X_train, y_train)
y_pred = tree_model.predict(X_test)
accuracy_score(y_pred, y_test)
tree_model.predict([[6.2, 3.4, 5.4, 2.3]])
Output:-
Sample Viva voice Questions
1. What is a Naïve Bayes classifier?
2. What is Bayes' theorem?
3. Why is it called "naïve"?
4. What are the different types of Naïve Bayes classifiers?
5. How do you evaluate the performance of a Naïve Bayes classifier?
6. What is a confusion matrix?
7. What does the classification report provide?
8. Can Naïve Bayes classifiers handle continuous data?
Experiment-7
Aim:- Creation of a fuzzy control system which models how you might choose to tip at a restaurant.
Objective:- Create a fuzzy control system to model the decision-making process for determining a tip amount
at a restaurant based on service quality and food quality.
Software used:- Anaconda(Jupyter), Google colab
Theory:- Fuzzy logic is a form of many-valued logic that deals with reasoning that is approximate rather than
fixed and exact. In fuzzy control systems, fuzzy logic is used to handle the uncertainty and vagueness
inherent in real-world situations. Instead of using binary true/false values, fuzzy logic variables can have a
degree of truth ranging between 0 and 1. This approach is particularly useful for decision-making systems
like determining tips, where inputs (such as service quality and food quality) are not always clear-cut. The
fuzzy control system for tipping will use fuzzy sets to represent linguistic variables (e.g., service quality: poor,
average, excellent) and fuzzy rules to model the decision process. The output will be a crisp value
representing the tip amount, derived by defuzzifying the fuzzy results.
Program/Code:-
!pip install scikit-fuzzy
# Rule base
= ctrl.ControlSystemSimulation(tipping_ctrl)
tipping.input['service_quality'] = 8 tipping.input['food_quality']
=9
Output:-
class Node:
self.value = value
self.children = []
queue = [root]
while queue:
current_node = queue.pop(0)
print("Visiting:", current_node.value)
if current_node.value == goal:
return True
queue.extend(current_node.children)
return False
print("Visiting:", node.value)
if node.value == goal:
return True
depth_first_search(child, goal):
return
True return
False
# Example usage: #
Create a simple
tree root =
Node("A")
= [Node("D"), Node("E")]
goal_node_value = "E"
# Breadth-First Search
# Depth-First Search
dfs_result = depth_first_search(root, goal_node_value) print("\nDFS
Result:", "Goal Found!" if dfs_result else "Goal Not Found!")
Output:-
# Calculating the Manhattan distance between the current position and the goal position
# Initializing a priority queue (heap) with the starting position and its heuristic
value heap = [(heuristic(start, goal), start)] visited = set() # Initializing a set to keep
continue # Skip the rest of the loop and continue to the next iteration
print(f"Visiting: {current_position}") # Print a message indicating the current position being visited
neighbors = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Possible moves: right, left, up, down
# Check if the new position is within the grid boundaries and is not blocked by an obstacle
if (
grid[new_position[0]][new_position[1]] != 1
and
):
Calculate the heuristic cost for the new
position heapq.heappush(heap, (new_cost,
heap new_position)) # Push the new position and
new_cost = heuristic(new_position, goal) #
its cost to the
print("Goal not reachable.") # Print a message indicating that the goal is not reachable
=[
[0, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
# Call the heuristic_search function with the provided grid, start, and goal heuristic_search(grid,
start, goal)
Output:-
Sample Viva voice
Questions
sent_tokenize
nltk.download('punkt')
def tokenize_sentences(text):
sentences = sent_tokenize(text)
return sentences
def tokenize_words(sentence):
words = word_tokenize(sentence)
return words
def main():
text = "Hello, how are you? I hope you're doing well. I am doing BSc from CGC Jhanjeri. I am in the
sixth semester. This is a AI Lab. And this is tenth Program of AI. I am performing tokenization in this
program. Tokenization is an important step in NLP."
sentences = tokenize_sentences(text)
enumerate(sentences, start=1):
in enumerate(sentences, start=1):
words = tokenize_words(sentence)
main()
Sample Viva voice
Questions
1. What is tokenization?
2. Why is tokenization important in natural language processing?
3. What are different tokenization techniques?
4. How does word_tokenize function in NLTK work?
5. What are the challenges of tokenization in natural language processing?
Experiment-11
Objective:- Implement a Bag of Words (BoW) model in Python to extract the frequency of terms from a
collection of text documents. This model is fundamental in natural language processing for representing text
data numerically based on the frequency of words present
Theory:- The Bag of Words model is a simplified representation used in natural language processing and
information retrieval. It disregards grammar and word order, focusing only on the occurrence and frequency of
words in a document. To create a BoW model:
2. Vocabulary Creation: Create a vocabulary of all unique words across all documents.
3. Vectorization: Represent each document as a vector where each dimension corresponds to a word
in the vocabulary, and the value represents the frequency of that word in the document.
Once vectorized, documents can be compared based on the similarity of their word frequencies, making BoW
useful for tasks like document classification, sentiment analysis, and information retrieval.
Program/Code:-
re
tokenize(text):
# Convert the text to lowercase and split it into individual words (tokens)
tokens = text.lower().split()
# Return the list of tokens
return tokens
term_frequency = Counter(tokens)
# Return a dictionary where keys are terms and values are their frequencies
return term_frequency
Sample text
text = "Hi, I am doing MCA from CGC Jhanjeri. I am in the third semester. This is a AISC Lab and
doing seventh Program of AISC. I am performing this program to calculate the bag of words in this
program "
term_frequency = get_term_frequency(text)
print("Term Frequency:")
{frequency}")
main()
Sample Viva voice
Questions
1. What is the Bag of Words (BoW) model?
2. How does the CountVectorizer in scikit-learn work?
3. What are the limitations of the Bag of Words model?
4. How do you handle stopwords and punctuation in the Bag of Words model?
5. What are TF (Term Frequency) and TF-IDF (Term Frequency-Inverse Document Frequency)?
Experiment-12
Aim:- Predict the category to which a given piece of text belongs
Objective:- Develop a text classification model in Python to predict the category or class label of a given piece
of text based on its content. Text classification is a fundamental task in natural language processing used for
sentiment analysis, spam detection, topic labeling, and more.
Software Used:- Anaconda(Jupyter), Google Colab
Theory:- Text classification involves training a machine learning model to automatically assign predefined
categories or labels to text documents. The process typically includes:
1. Data Preparation: Preprocess text data by tokenizing, normalizing, and vectorizing it into a
numerical format suitable for machine learning algorithms.
2. Feature Extraction: Extract features from text data using techniques like Bag of Words (BoW), TF-
IDF (Term Frequency-Inverse Document Frequency), or word embeddings.
3. Model Training: Train a classification algorithm (e.g., Naïve Bayes, Support Vector Machines,
or Neural Networks) on labeled training data.
4. Prediction: Use the trained model to predict the category of new, unseen text documents based on
their features.
Program/Code:-
nltk.download('punkt')
nltk.download("vader_lexicon")
import nltk
nltk.download('vader_lexicon') analyzer =
SentimentIntensityAnalyzer()
analyze_sentiment(text): sentiment_scores =
analyzer.polarity_scores(text) compound_score
= sentiment_scores['compound']
if compound_score >=
elif
compound_score <= -0.05:
return "Negative"
else:
return "Neutral"
# Analyze sentiment
sentiment = analyze_sentiment(input_text)
librosa.display import
matplotlib.pyplot as plt
1, 1)
librosa.display.waveshow(audio, sr=sr)
(s)") plt.ylabel("Amplitude")
1, 2)
plt.tight_layout() plt.show()
Sample Viva voice
Questions
def
endpoint=False)
return t,
audio_signal
8))
for i in range(len(frequencies)): t, audio_signal = generate_audio_signal(frequencies[i],
Objective:- Create a Python script to synthesize tones and generate music programmatically. This involves
generating multiple audio signals (tones) of varying frequencies, durations, and amplitudes to compose music or
simulate musical instruments.
Software Used:- Anaconda(Jupyter), Google colab
Theory:- Synthesizing tones to generate music programmatically involves simulating the characteristics of
musical notes using waveform generation and modulation techniques:
1. Waveform Generation: Use mathematical functions (e.g., sine, square, triangle waves) to
create fundamental tones.
2. Harmonics and Timbre: Combine multiple tones and harmonics to replicate the timbre and richness
of different musical instruments.
3. Envelope Shaping: Apply amplitude modulation (envelope shaping) to simulate attack, sustain,
decay, and release phases of musical notes.
4. Sequencing: Arrange synthesized tones in sequences (melodies) and patterns (chords) to
compose music.
Program/Code:-
import numpy as np import
matplotlib.pyplot as plt
"""
Parameters:
Returns:
wave. """
"""
Parameters:
waveform. """
(s)')
plt.ylabel('Amplitude')
plt.title('Generated Waveform')
plt.show()
= 1 # 1 second
sampling_rate)
Sample Viva voice Questions