0% found this document useful (0 votes)
54 views85 pages

Artificial_Intelligence_Lab_Manual_BCA6_UGCA1945

The document outlines the curriculum and objectives for the Artificial Intelligence Laboratory course as part of the BCA program, detailing course outcomes, prerequisites, and assessment methodologies. It emphasizes the institute's vision and mission to develop competent professionals through advanced education and industry collaboration. Additionally, it includes a structured course plan with specific topics, assignments, and teaching methodologies aimed at enhancing students' practical skills in AI using Python.

Uploaded by

lovepreet
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)
54 views85 pages

Artificial_Intelligence_Lab_Manual_BCA6_UGCA1945

The document outlines the curriculum and objectives for the Artificial Intelligence Laboratory course as part of the BCA program, detailing course outcomes, prerequisites, and assessment methodologies. It emphasizes the institute's vision and mission to develop competent professionals through advanced education and industry collaboration. Additionally, it includes a structured course plan with specific topics, assignments, and teaching methodologies aimed at enhancing students' practical skills in AI using Python.

Uploaded by

lovepreet
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/ 85

Table of Contents

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

leading successful careers in industries, pursuing higher studies or entrepreneurial endeavors.

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

becoming an effective graphics and web designer.

PSO 2: Able to assess hardware and software aspects necessary to develop Graphics and Web

Designing
Program Outcomes (PO’s)

At the end of the Program, a graduate will be able to:


PO1: Graphics knowledge: Apply the knowledge of mathematics, science and IT to the complex graphics
design.
PO2: Problem analysis: Identify, formulate, research literature, and analyze complex problems reaching
substantiated conclusions using principles of mathematics, natural sciences, and IT.
PO3: Design/development of solutions: Develop solutions for complex graphics and web designing
problems that meet the specified needs with appropriate consideration for the cultural, societal, and
environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and methods
including analysis and interpretation of data that can explore different approaches in computer graphics
and web development.
PO5: Modern tool usage: Create, select, and apply various aspects of interactive websites, motion
graphics, video and informational graphics with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
practice.
PO7: Environment and sustainability: Understand the impact of the graphics and website development
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the professional practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex graphics and web design activities with the
professional community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
development and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
(BCA- 6thsem)

Course Code: UGCA 1945


Course Name: Artificial Intelligence Laboratory

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

Prerequisite: Working Knowledge of Python Programming Language


Corequisite: Installing Python, Installing packages, Loading data
Additional material required in ESE: -NA-

Course Outcomes:

CO Course outcomes
#
CO1 Illustrate right tool for different AI based problems.

CO2 Develop basic applications using AI tool.


CO3 List various real life problem domains using logic based techniques.

CO4 Determine the use of the Bayesian approach and NLP to solve uncertain problems.
Assignments:

1. Learn the building blocks of Logic Programming in Python.

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.

5. Python script for building a puzzle solver.

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.

9. Implementation of heuristic search techniques in Python.

10. Python script for tokenizing text data.

11. Extracting the frequency of terms using a Bag of Words model.

12. Predict the category to which a given piece of text belongs.

13. Python code for visualizing audio speech signal.

14. Python code for Generating audio signals.

15. Python code for Synthesizing tones to generate music.

TEXT/REFERENCE BOOKS:
R1 Artificial Intelligence with Python, Prateek Joshi, Packt Publishing.
COURSE PRE-REQUISITES:
Prerequisite: - Working Knowledge of Python Programming Language

Corequisite: - Installing Python, Installing packages, Loading data


Additional material required in ESE: -NA

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

GAPES IN THE SYLLABUS - TO MEET INDUSTRY/PROFESSION REQUIREMENTS, POs:


SN DESCRIPTION PROPOSED ACTIONS / ACTION TAKEN
O
Implement concept of call by value and call
1 by reference using C programming. Extra Class/Content Beyond Syllabus

2 How to Create header files in C Extra Class/Content Beyond Syllabus


PROPOSED ACTIONS: TOPICS BEYOND SYLLABUS/ASSIGNMENT/INDUSTRY VISIT/GUEST LECTURER/NPTEL ETC
TOPICS BEYOND SYLLABUS/ADVANCED TOPICS/DESIGN:
SN DESCRIPTION PROPOSED ACTIONS / ACTION TAKEN
O
1 Implement concept of call by value and
call by reference using C programming. PPT Shared/Content Beyond Syllabus

2 How to Create header files in C Extra Class/Content Beyond Syllabus


WEB SOURCE REFERENCES:
1 https://www.tutorialspoint.com/ai programming/index.htm
2 https://www.w3schools.com/ai/
3 https://www.geeksforgeeks.org/ai/
4 https://www.youtube.com/watch?v=KJgsSFOSQv0
5 https://www.youtube.com/watch?v=Bz4MxDeEM6k

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

INNOVATIONS IN TEACHING/LEARNING/EVALUATION PROCESSES:


1. Group Discussion.
2. PPT by students.
3. Open book test.
4. Online courses
5. MCQ’s

Prepared by: Checked by: Approved by:


(Mr. Sunil Kumar) (PAQIC Members) HOD, Dept. Of Computer
Applications Asst. Professor Computer Applications
COURSE PLAN VISION:

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.

● Induce knowledge that foster continuous improvement, self-learning, and innovation


for higher education.

● Create a unique organizational value-based culture, professionalism in education,


service, and management and learner-centered education of excellence

PROGRAM EDUCATIONAL OBJECTIVES:

● provide a foundation of business practices and computing principles to effectively


manage and use enterprise software and information systems.

● 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.

Subject: Artificial Semest Contact Hour: L Total


intelligence Laboratory er: 6th 4 per week 4 = 4
(UGCA1945)
Branch: Computer Applications Faculty:
Prerequisite Course: NA
Teacher Centric Approach TC1: Chalk and Talk, TC2: PPT, TC3: Video Lectures etc (Add any
other as per our NIT Poly)
Learner Centric Approach: LC1: Assignment, LC2: Mini project, LC3: Quiz, LC 4: Seminar on
recent trends LC5: Group Task etc (Add any other as per our NIT Poly
Lectur CO Plann Act
e Topics to be covered ed ual Sig
Covere
Numb Date Dat n
d
er e
1. Learn the building blocks of Logic
Programming in Python. CO1 19/01/25

2. Python script for comparing mathematical


expressions and finding out unknown values. CO1 23/01/25

3. Use logic programming in Python to check for


CO1 26/01/25
prime numbers.
4. Use logic programming in Python parse a family
tree and infer the relationships between the CO2 30/01/25
family members.

5. Python script for building a puzzle solver. CO2 05/02/25


6. Implementation of Naïve Bayes
classifier, computing its accuracy and CO2 12/02/25
visualizing its performance.

7. Creation of a fuzzy control system that models


how you might choose to tip at a restaurant. CO2 15/02/25

8. Implementation of uninformed
search techniques in CO2 20/02/25
Python.
9. Implementation of heuristic search techniques
in Python. CO2 27/02/25

10. Python script for tokenizing text data. CO2 05/03/25


11. Extracting the frequency of terms using a Bag
CO3 12/03/25
of Words model.
12. Predict the category to which a given piece of
CO3 15/03/25
text belongs.
13. Python code for visualizing audio speech signal. CO3 19/03/25

14. Python code for Generating audio signals. CO3 26/03/25

15 Python code for Synthesizing tones to generate


music. CO3 05/04/25
Experiment-1
Aim:- Learn the building blocks of Logic Programming in Python.

Software used:- Anaconda(Jupyter), Google colab

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:-

**# Python3 program to illustrate

# working of AND gate** def AND

(a, b): if a == 1 and b == 1:

return True else: return

False

# Driver code if

_name=='main_':

print(AND(1, 0))

print("+ +

+") print(" | AND

Truth Table | Result |")

print(" A = False, B = False | A AND B =",AND(False,False)," | ")

print(" A = False, B = True | A AND B =",AND(False,True)," | ") print("

= True, B = False | A AND B =",AND(True,False)," | ") print(" A =

True, B = True | A AND B =",AND(True,True)," | ")


# Python3 program to illustrate

# working of OR gate

def OR(a, b): if a == 1 or b

==1: return True else:

return False

# Driver code if

_name=='main_':

print(OR(0, 0))

print("+ +

+") print(" | OR

Truth Table | Result |")

print(" A = False, B = False | A OR B =",OR(False,False)," | ")

print(" A = False, B = True | A OR B =",OR(False,True)," | ") print("

A = True, B = False | A OR B =",OR(True,False)," | ") print(" A =


True, B = True | A OR B =",OR(True,True)," | ")
# Python3 program to illustrate

# working of NAND gate

def NAND (a, b): if a

== 1 and b == 1:

return False

else:

return True

# Driver code if

_name=='main_':

print(NAND(1, 0))

print("+ +

+") print(" |

NAND Truth Table | Result |")


print(" A = False, B = False | A AND B =",NAND(False,False)," | ")

print(" A = False, B = True | A AND B =",NAND(False,True)," | ") print(" A =

True, B = False | A AND B =",NAND(True,False)," | ") print(" A = True,

= True | A AND B =",NAND(True,True)," | ")

# Python3 program to illustrate

# working of Xor gate

def XOR (a, b):

if a != b:

return 1

else: return 0

# Driver code if

_name=='main_':

print(XOR(5, 5))
print("+ +

+") print(" | XOR

Truth Table | Result |")

print(" A = False, B = False | A XOR B =",XOR(False,False)," | ")

print(" A = False, B = True | A XOR B =",XOR(False,True)," | ") print("

= True, B = False | A XOR B =",XOR(True,False)," | ") print(" A =

True, B = True | A XOR B =",XOR(True,True)," | ")


# Python3 program to illustrate

# working of Not gate

def NOT(a):

return not a

# Driver code if

_name=='main_':

print(NOT(0))

print("+---------------+----------------+") print(" | NOT

Truth Table | Result |") print(" A = False | A NOT

=",NOT(False)," | ") print(" A = True, | A NOT

=",NOT(True)," | ")

# Python3 program to illustrate

# working of NOR gate


def NOR(a, b): if(a == 0)

and (b == 0): return

1 elif(a == 0) and (b == 1):

return 0

elif(a == 1) and (b == 0):

return 0

elif(a == 1) and (b == 1):

return 0

# Driver code if

_name=='main_':

print(NOR(0, 0))

print("+ +

+") print(" |

NOR Truth Table | Result |")

print(" A = False, B = False | A NOR B =",NOR(False,False)," | ")

print(" A = False, B = True | A NOR B =",NOR(False,True)," | ") print("

= True, B = False | A NOR B =",NOR(True,False)," | ") print(" A =

True, B = True | A NOR B =",NOR(True,True)," | ")


# Python3 program to illustrate

# working of Not gate

def XNOR(a,b):

if(a == b):

else:
return 0
return 1

# Driver code if

_name=='main_':

print(XNOR(1,1))

print("+ +

+") print(" |

XNOR Truth Table | Result |")

print(" A = False, B = False | A XNOR B =",XNOR(False,False)," | ")

print(" A = False, B = True | A XNOR B =",XNOR(False,True)," | ") print(" A =


True, B = False | A XNOR B =",XNOR(True,False)," | ") print(" A = True, B

= True | A XNOR B =",XNOR(True,True)," | ")

Sample Viva voice Questions

1. What is a fact in logic programming?


2. What is a rule in logic programming?
3. What is a query in logic programming?
4. What is unification in logic programming?
5. How does backtracking function in logic programming?
6. Can you give an example of a fact in Python?
7. What is the purpose of the query method in a logic program?
Aim:- Python script for comparing mathematical expressions and finding out unknown values.
Software used:- Anaconda(Jupyter), Google colab
Theory:- In solving mathematical expressions to find unknown values, the process involves defining
the expressions and the unknown variables, simplifying the difference between the expressions, and
solving the resulting equation(s) for the unknowns. SymPy, a Python library for symbolic mathematics,
provides tools for parsing, simplifying, and solving mathematical expressions. By representing
unknowns as symbols, the library allows for manipulating algebraic equations to isolate and solve for
these unknowns. This approach is useful in various applications, including algebraic problem-solving,
engineering simulations, and scientific research, where comparing mathematical models and finding
unknown parameters are essential tasks.
Program/Code:-

from sympy import symbols, Eq, solve

# Define symbolic variables x,

y = symbols('x y')

# Define symbolic equations with a right-hand side

eq1 = Eq(x + y, 4) eq2 = Eq(x - y, -2)

# Display the equations print("Equation

1:", eq1) print("Equation 2:", eq2)

solve((eq1,eq2), (x, y))

sol_dict = solve((eq1,eq2), (x, y))

print(f'x = {sol_dict[x]}') print(f'y =

{sol_dict[y]}')
Sample Viva voice Questions

1. What is SymPy in Python?


2. How do you define symbols for unknowns in SymPy?
3. What function in SymPy is used to simplify expressions?
4. How can you parse a string expression into a SymPy expression?
5. What is the purpose of finding the difference between two expressions in this context?
6. Which function in SymPy is used to solve equations?
7. Can SymPy handle systems of equations?
Experiment -3
Aim:- Use logic programming in Python to check for prime numbers.
Software used:- Anaconda(Jupyter), Google colab
Theory:- Logic programming can be used to check for prime numbers by defining facts and rules within
a logic system. Facts represent the numbers to be checked, and rules define the conditions for a number
to be prime. In this approach, a prime number is determined by checking if it is greater than 1 and not
divisible by any number other than 1 and itself. The rule iterates through each number (fact) and applies
the prime-checking condition. This method leverages the declarative nature of logic programming,
focusing on defining what constitutes a prime number and allowing the system to determine which
numbers meet the criteria.
Program/Code:-
# Input from the user num =

int(input("Enter a number: ")) # If

number is greater than 1 if num >1:

# Check if factor exist


for i inrange(2,num): if

(num % i) == 0:

print(num,"is not a prime

number") break else:

print(num,"is a prime

number") else: print(num,"is

not a prime number")


Sample Viva voice Questions

1. How does the prime_rule function determine if a number is prime?


2. Why do we use the all function in the prime_rule?
3. Can logic programming handle complex conditions and multiple rules?
4. What are some advantages of using logic programming for checking prime numbers?
5. How does logic programming differ from procedural programming in this context?
Aim:- Use logic programming in Python parse a family tree and infer the relationships between the
family members.

Software used:- Anaconda(Jupyter), Google Colab

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:-

pip install kanren pip install

--upgrade kanren pip show

kanren

import json

from kanren import Relation, facts, run, conde, var,

eq def parent(x,y): return

conde([father(x,y)], [mother(x,y)])

def

grandparent(x,y):

temp = var() return

conde((parent(x,temp), parent(temp,y))) def

sibling(x,y): temp = var()

return conde((parent(temp, x), parent(temp, y)))

def uncle(x, y): temp = var()

return

conde((father(temp,x), grandparent(temp,y)))

def uncle(x, y): temp = var()

return
conde((father(temp,x), grandparent(temp,y))) if

_name=='main_': father = Relation() mother =

Relation() with

open(r'/content/relationship.json') as f:
d = json.loads(f.read())

for item in d['father']:

facts(father,(list(item.keys())[0], list(item.values())[0]))

for item in d['mother']:

facts(mother, (list(item.keys())[0], list(item.values())

[0])) x = var()

# John's children name = 'John'

output = run(0, x, father(name, x))

print("\nList of " + name + "'s

children:") for item in output:

print(item)

# William's mother name = 'William'

output = run(0, x, mother(x,name))[0]

print("\n" + name + "'s mother:\n" +

output) # Adam's parents name =

'Adam'

output = run(0, x, parent(x, name))

print("\nList of " + name + "'s

parents:") for item in output:

print(item)

# Wayne's grandparents name = 'Wayne'

output = run(0, x, grandparent(x, name))

print("\nList of " + name + "'s

grandparents:") for item in output:

print(item)

# Megan's grandchildren name = 'Megan

output = run(0,x, grandparent(name, x))


print("\nList of " + name + "'s

grandchildren:") for item in output:

print(item)
# David's siblings name = 'David'

output = run(0, x, sibling(x, name))

siblings = [x for x in output if x !=

name] print("\nList of " + name + "'s

siblings:") for item in siblings:

print(item)

# Tiffany's uncles name = 'Tiffany'

name_father = run(0, x, father(x,name))[0]

output = run(0, x, uncle(x, name)) output =

[x for x in output if x!=name_father]

print("\nList of "+name+"'s uncles:") for

item in output:

print(item)

# All spouses a,b,c=var(),var(),var()

output=run(0,(a,b),(father,a,c),

(mother,b,c)) print("\nList of all spouses:")

for item in output:

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:-

Sample Viva voice Questions

1. How does the parent_rule function infer relationships?

2. What is the advantage of using logic programming for parsing a family tree?
3. Can logic programming handle complex family relationships?

4.

How does the child_rule function work in this context?


Experiment-5
Aim:- Python script for building a puzzle solver.
Objective:- Develop a Python script to solve puzzles programmatically, demonstrating algorithmic problem-
solving skills and applying search or constraint satisfaction techniques to find solutions efficiently.

Software Used:- Anaconda(Jupyter), Google colab


Theory:- Building a puzzle solver in Python involves implementing algorithms that explore potential solutions
and check constraints until a valid solution is found:
1. Problem Representation: Define the puzzle's structure, initial state, and constraints that must
be satisfied for a solution.
2. Search Algorithms: Select appropriate search strategies such as Depth-First Search (DFS),
Breadth- First Search (BFS), or heuristic-based search (like A* algorithm) based on the puzzle's
complexity and solution space.
3. Constraint Satisfaction: For constraint-based puzzles, use techniques like backtracking or
constraint propagation to systematically explore and prune invalid paths.
4. Solution Validation: Verify each potential solution against puzzle rules and constraints to
ensure correctness before finalizing it.
Program/Code:-

pip install kanren pip

install --upgrade kanren

pip show kanren from

kanren import * from

kanren.core import lall #

Define variables people =

var()

# Define rules rules

= lall(

(eq, (var(), var(), var(), var()), people),

(membero, ('Steve', var(), 'blue', var()), people),

(membero, (var(), 'cat', var(), 'Canada'), people),

(membero, ('Matthew', var(), var(), 'USA'), people),

(membero, (var(), var(), 'black', 'Australia'), people),

(membero, ('Jack', 'cat', var(), var()), people),


(membero, ('Alfred', var(), var(), 'Australia'), people),

(membero, (var(), 'dog', var(), 'France'), people),

(membero, (var(), 'rabbit', var(), var()), people)

# Find solutions solutions =

run(0, people, rules)

# Extract information about the owner of the rabbit output =

[house for house in solutions[0] if 'rabbit' in house][0][0] print('\

n' + output + ' is the owner of the rabbit')

# Print all the details print('\nHere

are all the details:') attribs =

['Name', 'Pet', 'Color', 'Country']

print('\t\t'.join(attribs)) print('=' *

57) for item in solutions[0]:


Sample Viva voice
Questions

1. What are the key components of a puzzle-solving algorithm?


2. How does Depth-First Search (DFS) work in solving puzzles?
3. What are some common types of puzzles that can be solved programmatically?
4. How can you optimize a puzzle solver to improve performance?
5. What are the differences between constraint-based puzzles and search-based puzzles?
Experiment-6

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.

Software used:- Anaconda(Jupyter), Google Colab, Kaggle

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:-

import numpy as np # linear algebra import

pandas as pd

iris = pd.read_csv('/content/Iris.csv')

iris

iris.info()

iris.head()

iris.drop('Id',axis=1,inplace=True)
iris

x = iris[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']] y

= iris['Species']

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=123)

from sklearn.tree import DecisionTreeClassifier

tree_model = DecisionTreeClassifier() tree_model

= tree_model.fit(X_train, y_train)

from sklearn.metrics import accuracy_score

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

import numpy as np import

skfuzzy as fuzz from skfuzzy

import control as ctrl

# Create input variables

service_quality = ctrl.Antecedent(np.arange(0, 11, 1), 'service_quality') food_quality

= ctrl.Antecedent(np.arange(0, 11, 1), 'food_quality')

# Create output variable

tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

# Define membership functions

service_quality['poor'] = fuzz.trimf(service_quality.universe, [0, 0, 5]) service_quality['average']

= fuzz.trimf(service_quality.universe, [0, 5, 10]) service_quality['excellent'] =

fuzz.trimf(service_quality.universe, [5, 10, 10])


food_quality['poor'] = fuzz.trimf(food_quality.universe, [0, 0, 5]) food_quality['average']

= fuzz.trimf(food_quality.universe, [0, 5, 10]) food_quality['excellent'] =

fuzz.trimf(food_quality.universe, [5, 10, 10])

tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])


tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25]) tip['high']

= fuzz.trimf(tip.universe, [13, 25, 25])

# Rule base

rule1 = ctrl.Rule(service_quality['poor'] | food_quality['poor'], tip['low']) rule2 =

ctrl.Rule(service_quality['average'] | food_quality['average'], tip['medium']) rule3 =

ctrl.Rule(service_quality['excellent'] | food_quality['excellent'], tip['high'])

# Create control system

tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3]) tipping

= ctrl.ControlSystemSimulation(tipping_ctrl)

# Input values (you can modify these values accordingly)

tipping.input['service_quality'] = 8 tipping.input['food_quality']

=9

# Compute the result tipping.compute()


# Output the result

print("Recommended tip:", tipping.output['tip']) tip.view(sim=tipping)

Output:-

Sample Viva voice


Questions
1. What is fuzzy logic?
2. What are fuzzy sets?
3. How does a fuzzy control system work?
4. What is the purpose of the defuzzification process?
5. What is a membership function in fuzzy logic?
6. How are fuzzy rules constructed?
7. What is the role of the ControlSystem in scikit-fuzzy?
8. Why might fuzzy logic be preferred over traditional binary logic in certain applications?
Experiment-8

Aim:- Implementation of Uninformed Search Techniques in python


Objective:- Implement uninformed search techniques in Python to explore and traverse a search space without
specific knowledge about the goal or the structure of the problem, aiming to find a solution efficiently.
Software used:- Anaconda(Jupyter), Google colab
Theory:- Uninformed search algorithms are used when the search space is unstructured or when there is no
additional information available about the problem beyond the definition of states and actions. These algorithms
operate based on the current state of the search and the transitions between states, without using any domain-
specific knowledge that could guide the search towards a solution. Common uninformed search algorithms
include Breadth-First Search (BFS) and Depth-First Search (DFS). BFS explores all nodes at the present depth
level before moving on to nodes at the next depth level, making it suitable for finding the shortest path in an
unweighted graph. DFS, on the other hand, explores as far as possible along each branch before backtracking,
which can be useful for exploring deeper paths first.
Program/Code:-

from collections import deque

class Node:

def _init_(self, value):

self.value = value

self.children = []

def breadth_first_search(root, goal):

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

def depth_first_search(node, goal):

print("Visiting:", node.value)

if node.value == goal:

return True

for child in node.children: if

depth_first_search(child, goal):

return

True return

False

# Example usage: #

Create a simple

tree root =

Node("A")

root.children = [Node("B"), Node("C")] root.children[0].children

= [Node("D"), Node("E")]

goal_node_value = "E"

# Breadth-First Search

bfs_result = breadth_first_search(root, goal_node_value) print("\nBFS

Result:", "Goal Found!" if bfs_result else "Goal Not Found!")

# 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:-

Sample Viva voice


Questions

1. What is the difference between BFS and DFS?


2. When would you prefer using BFS over DFS, and vice versa?
3. How does BFS guarantee finding the shortest path in an unweighted graph?
4. What are the memory requirements for BFS and DFS?
5. Can BFS and DFS be used for searching in graphs with cycles?
Experiment-9
Aim:- Implementation Of Heuristic Search Technique in python
Objective:- Implement a heuristic search technique in Python to efficiently navigate and search through
a problem space using domain-specific knowledge or heuristics to guide the search towards a solution.
Software Used:- Anaconda(Jupyter), Google Colab
Theory:- Heuristic search techniques, unlike uninformed search, use domain-specific information (heuristics) to
prioritize and guide the search towards more promising paths that are likely to lead to a solution faster. One of
the most commonly used heuristic search algorithms is A* (A-star) search. A* combines the advantages of both
breadth-first and greedy best-first searches by using a heuristic function to estimate the cost of reaching the
goal from any given node. It maintains a priority queue to always expand the node with the lowest estimated
total
cost (path cost from the start plus heuristic estimate to the goal). This makes A* optimal and complete under
certain conditions, providing an efficient way to find the shortest path in weighted graphs or solve various
optimization
problems.
Program/Code:-
import heapq # Importing the heapq module, which provides functions for heap queues

def heuristic(current, goal):

# Basic Manhattan distance heuristic

# Calculating the Manhattan distance between the current position and the goal position

return abs(current[0] - goal[0]) + abs(current[1] - goal[1])

def heuristic_search(grid, start, goal):

# 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

track of visited positions

while heap: # Loop until the heap is empty


current_cost, current_position = heapq.heappop(heap) # Pop the minimum-cost position from the
heap

if current_position == goal: # If the current position is the goal position

print("Goal reached!") # Print a message indicating that the goal is reached

return # Exit the function, indicating success


if current_position in visited: # If the current position has been visited before

continue # Skip the rest of the loop and continue to the next iteration

visited.add(current_position) # Add the current position to the set of visited positions

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

for dx, dy in neighbors: # Loop through each possible move


new_position = (current_position[0] + dx, current_position[1] + dy) # Calculate the new position

# Check if the new position is within the grid boundaries and is not blocked by an obstacle

if (

0 <= new_position[0] < len(grid) and

0 <= new_position[1] < len(grid[0]) and

grid[new_position[0]][new_position[1]] != 1

and

new_position not in visited

):
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

# Example usage: grid

=[

[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],

start = (0, 0) # Starting position goal

= (4, 4) # Goal position

# Call the heuristic_search function with the provided grid, start, and goal heuristic_search(grid,

start, goal)

Output:-
Sample Viva voice
Questions

1. What is a heuristic function in heuristic search?


2. How does A search combine breadth-first and greedy best-first search techniques?
3. Under what conditions is A search optimal and complete?
4. What is the time complexity of A search?
5. Can A search be used in unweighted graphs?
Experiment-10
Aim:- Python script for tokenizing text data.
Objective:- Create a Python script to tokenize text data, breaking it down into individual tokens (words
or subwords), which is essential for various natural language processing tasks such as text analysis,
language modeling, and information retrieval.
Software Used:- Anaconda(Jupyter), Google Colab
Theory:- Tokenization is the process of dividing a string of text into meaningful units, called tokens. These
tokens could be words, phrases, symbols, or other elements, depending on the specific task and language.
Tokenization is the first step in text preprocessing and is crucial for converting unstructured text data into a
format that is suitable for further analysis or modeling. Common techniques for tokenization include splitting
text based on whitespace, punctuation, or specific patterns (e.g., regular expressions). Tokenization helps in
standardizing and normalizing text data, making it easier to handle and process in subsequent steps of a natural
language processing pipeline.
Program/Code:-

pip install nltk

import nltk from nltk.tokenize import word_tokenize,

sent_tokenize

nltk.download('punkt')

def tokenize_sentences(text):

# Tokenize text into sentences

sentences = sent_tokenize(text)

return sentences

def tokenize_words(sentence):

# Tokenize a sentence into words

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)

print("Sentences:") for idx, sentence in

enumerate(sentences, start=1):

print(f" Sentence {idx}: {sentence}")

print("\nTokenized Words:") for idx, sentence

in enumerate(sentences, start=1):

words = tokenize_words(sentence)

print(f" Sentence {idx}: {words}")

if _name_ == " main ":

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

Aim:- Extracting the frequency of terms using a Bag of Words model

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

Software Used:- Anaconda(Jupyter), Google Colab

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:

1. Tokenization: Break down each document into individual words or tokens.

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:-

# Import the Counter class from the collections module

from collections import Counter

# Import the regular expression module import

re

# Define a function to tokenize a text def

tokenize(text):

# Tokenize the text by splitting on whitespace and removing punctuation


# Use regular expression to replace any character that is not a word character (\w) or whitespace
(\s) with an empty string text

= re.sub(r'[^\w\s]', '', text)

# Convert the text to lowercase and split it into individual words (tokens)

tokens = text.lower().split()
# Return the list of tokens

return tokens

# Define a function to calculate term frequency

def get_term_frequency(text): # Tokenize

the input text tokens = tokenize(text)


# Use the Counter class to count the frequency of each term (word)

term_frequency = Counter(tokens)

# Return a dictionary where keys are terms and values are their frequencies

return term_frequency

# Define the main

function def main(): #

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 "

# Calculate term frequency using the get_term_frequency function

term_frequency = get_term_frequency(text)

# Display the frequency of each term

print("Term Frequency:")

# Iterate over the items in the term_frequency

dictionary for term, frequency in term_frequency.items():

# Print each term and its frequency print(f"{term}:

{frequency}")

# Check if the script is being run as the main program if

_name_ == " main ":

# If it is, execute the main function

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:-

pip install nltk import nltk

nltk.download('punkt')

nltk.download("vader_lexicon")

import nltk

from nltk.sentiment.vader import SentimentIntensityAnalyzer

# Download VADER lexicon and initialize the sentiment analyzer

nltk.download('vader_lexicon') analyzer =

SentimentIntensityAnalyzer()

# Function to analyze sentiment def

analyze_sentiment(text): sentiment_scores =

analyzer.polarity_scores(text) compound_score

= sentiment_scores['compound']

if compound_score >=

0.05: return "Positive"

elif
compound_score <= -0.05:

return "Negative"

else:

return "Neutral"

# Input from the user

input_text = input("Enter a piece of text: ")

# Analyze sentiment

sentiment = analyze_sentiment(input_text)

# Display the sentiment

print(f"The sentiment of the input text is: {sentiment}")

# I am abc. I am Studying MCA -> Neutral

# I like tea and coffee -> Positive

# I am very sad today -> Negative


Sample Viva voice
Questions

1. What is text classification, and why is it important?


2. What are some common applications of text classification?
3. What are the steps involved in building a text classification model?
4. How do you handle class imbalance in text classification?
5. What are some popular algorithms used for text classification?
Experiment-13
Aim:- Python code for visualizing audio speech signal
Objective:- Create a Python script to visualize audio speech signals, providing insights into the waveform,
spectrogram, or other representations of audio data. Visualization helps in understanding the characteristics of
audio signals and is useful for tasks like speech processing, audio classification, and quality assessment.
Software Used:- Anaconda(Jupyter), Google Colab
Theory:- Audio visualization involves representing audio signals in graphical form to analyze their temporal
and frequency characteristics:
1. Waveform: A waveform visualizes audio as a plot of amplitude over time, showing how the
signal varies.
2. Spectrogram: A spectrogram is a 2D representation of audio signals, showing how the frequency
content of the signal changes over time. It's created by computing the Short-Time Fourier Transform
(STFT) of the signal.
3. Mel-Frequency Cepstral Coefficients (MFCC): MFCCs are widely used in speech and audio
processing to represent the short-term power spectrum of a sound. They are derived from the STFT and
are useful for tasks like speech recognition and speaker identification.
Program/Code:-

pip install matplotlib librosa

import librosa import

librosa.display import

matplotlib.pyplot as plt

# Load the audio file


audio_path = "/content/Ill Be Waiting Kabhi Jo Baadal -(Mr-Jatt.com).mp3" # Replace with the path to
your audio file

audio, sr = librosa.load(audio_path, sr=None)

# Get the audio duration

audio_duration = librosa.get_duration(y=audio, sr=sr)

# Calculate the number of audio samples


num_samples= len(audio)
# Plot the waveform

plt.figure(figsize=(12, 6)) plt.subplot(2,

1, 1)

librosa.display.waveshow(audio, sr=sr)

plt.title("Audio Waveform") plt.xlabel("Time

(s)") plt.ylabel("Amplitude")

# Display audio information plt.subplot(2,

1, 2)

info_text = f"File Path: {audio_path}\nSample Rate: {sr} Hz\nDuration: {audio_duration:.2f} seconds\


nNumber of Samples: {num_samples}"
plt.text(0.5, 0.5, info_text, horizontalalignment="center", verticalalignment="center",
transform=plt.gca().transAxes) plt.axis("off")

plt.tight_layout() plt.show()
Sample Viva voice
Questions

1. What is a waveform, and how is it useful in audio signal analysis?


2. What is a spectrogram, and how does it differ from a waveform?
3. What is the Short-Time Fourier Transform (STFT), and why is it used in
spectrogram computation?
4. How do Mel-Frequency Cepstral Coefficients (MFCC) contribute to speech processing tasks?
5. What are some challenges in visualizing and analyzing audio signals?
Experiment-14
Aim:- Python code for generating audio signals
Objective:- Create a Python script to generate audio signals programmatically, allowing for the creation of
synthetic audio data for testing, simulation, or artistic purposes.
Software Used:- Anaconda(Jupyter), Google Colab
Theory:- Generating audio signals involves creating waveforms that represent sound waves. Sound waves
are typically represented as variations in air pressure over time. Common waveforms include sine waves,
square waves, triangle waves, and sawtooth waves, each with distinct harmonic characteristics. To generate
audio signals:
1. Waveform Generation: Choose a waveform type and specify parameters such as
frequency, amplitude, and duration.
2. Sampling: Convert the continuous waveform into discrete samples at a specified sampling rate
(e.g., 44.1 kHz for CD-quality audio).
3. Playback: Optionally, play or save the generated audio signal using appropriate libraries or tools.
Program/Code:-
import numpy as np import matplotlib.pyplot as plt

# Function to generate an audio signal

def

generate_audio_signal(frequency, duration, amplitude):

# Generate a time array

t = np.linspace(0, duration, int(frequency * duration),

endpoint=False)

# Generate the audio signal (sine wave in this case)

audio_signal = amplitude * np.sin(2 * np.pi * frequency * t)

return t,
audio_signal

# Parameters for audio signals

frequencies = [440, 880, 220, 660] # Frequencies in Hz durations

= [1, 2, 3, 4] # Durations in seconds amplitudes = [0.5, 0.7, 0.8,

0.6] # Amplitudes (ranges from -1 to 1)


# Create and plot audio signals plt.figure(figsize=(12,

8))
for i in range(len(frequencies)): t, audio_signal = generate_audio_signal(frequencies[i],

durations[i], amplitudes[i]) plt.subplot(len(frequencies), 1, i + 1) plt.plot(t, audio_signal)

plt.title(f"Frequency: {frequencies[i]} Hz, Duration: {durations[i]} s, Amplitude:

{amplitudes[i]}") plt.xlabel("Time (s)") plt.tight_layout() plt.show()


Sample Viva voice
Questions

1. What are the fundamental components of an audio signal?


2. How does sampling rate affect audio signal quality?
3. What are some commonly used waveforms in audio signal generation?
4. How can you simulate complex sounds using basic waveforms?
5. What are some applications of programmatically generated audio signals?
Experiment-15
Aim:- Python code for Synthesizing tones to generate music

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

def generate_sine_wave(duration, frequency, sampling_rate=44100):

"""

Generate a sine wave with specified parameters.

Parameters:

- duration: Duration of the generated wave in seconds.

- frequency: Frequency of the sine wave in Hz.

- sampling_rate: Sampling rate of the wave in samples per second.

Returns:

- numpy array representing the generated sine

wave. """

t = np.linspace(0, duration, int(sampling_rate * duration),

endpoint=False) wave = np.sin(2 * np.pi * frequency * t) return wave


def plot_waveform(waveform, sampling_rate=44100):

"""

Plot the waveform.

Parameters:

- waveform: numpy array representing the waveform.

- sampling_rate: Sampling rate of the

waveform. """

duration = len(waveform) / sampling_rate

time = np.linspace(0, duration, len(waveform))

plt.plot(time, waveform) plt.xlabel('Time

(s)')

plt.ylabel('Amplitude')

plt.title('Generated Waveform')

plt.show()

# Example usage duration

= 1 # 1 second

frequency = 440 # A4 note frequency in Hz sampling_rate

= 44100 # CD quality sampling rate

sine_wave = generate_sine_wave(duration, frequency, sampling_rate) plot_waveform(sine_wave,

sampling_rate)
Sample Viva voice Questions

1. How can you synthesize musical tones programmatically?


2. What are the advantages of programmatically generating music compared to using pre-recorded
samples?
3. What are some challenges in simulating realistic musical instruments through tone synthesis?
4. How can you extend basic tone synthesis to create more complex musical compositions?
5. What role does sampling rate play in synthesizing high-quality audio signals?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy