0% found this document useful (0 votes)
48 views30 pages

Aifile

Uploaded by

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

Aifile

Uploaded by

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

INDEX

Sr. No. Program Page No. Remarks


1. Learn the building blocks of Logic Programming in 1
Python.
2. Python script for comparing mathematical expressions and 2
finding out unknown values.
3. Use logic programming in Python to check for prime 3
numbers.
4. Use logic programming in Python parse a family tree and 4
infer the relationships between the family members.
5. Python script for building a puzzle solver. 5
6. Implementation of Naïve Bayes classifier, computing its 6-7
accuracy and visualizing its performance.
7. Creation of a fuzzy control system which models how you 8-9
might choose to tip at a restaurant.
8. Implementation of uninformed search techniques in 10-14
Python.
9. Implementation of heuristic search techniques in Python. 15-18
10. Python script for tokenizing text data. 19-20
11. Extracting the frequency of terms using a Bag of Words 21
model.
12. Predict the category to which a given piece of text 22-23
belongs.
13. Python code for visualizing audio speech signal. 24-26
14. Python code for Generating audio signals. 27
15. Python code for Synthesizing tones to generate music. 28
Practical-1
Learn the building blocks of logic programming in python.
There are some low-level conceptual patterns that we use to construct programs. These constructs are not
just for Python programs, they are part of every programming language from machine language up to the
high-level languages.

 Input
Get data from the “outside world”. This might be reading data from a file, or even some kind of sensor like a
microphone or GPS. In our initial programs, our input will come from the user typing data on the keyboard.

 Output
Display the results of the program on a screen or store them in a file or perhaps write them to a device like a
speaker to play music or speak text.

 Sequential execution
Perform statements one after another in the order they are encountered in the script.

 Conditional execution
Check for certain conditions and then execute or skip a sequence of statements.

 Repeated execution
Perform some set of statements repeatedly, usually with some variation.

 Reuse
Write a set of instructions once and give them a name and then reuse those instructions as needed
throughout your program.

1
Practical-2
.Python script for comparing mathematical expressions and finding out unknown
values

x = 40

y = 12

add= x+y sub = x – y

pro=x* y div = x / y

print(add)

print(sub)

print(pro)

print(div)

Output:-

2
Practical-3
Use logic programming in python to check for prime number.

num= 29
#To take input from the user
#num=int(input("Enter a number:"))

# define a flag variable


flag=False

#prime numbers are greater than 1

if num> 1:
#check for factors
For i in range(2, num):
if(num%i)== 0:
#if factor is found,
set flag to True flag = True
#breakout of loop break

#check if flag is True

if flag:
print(num,"is not a prime number")
else:

Output3:-

3
Practical-4
Use logic programming in python parse a family tree and infer the relationships
between the family members.

class Tree:
def init (self, val=None):
if val is not None:
self.val = val
else:
self.val = None
self.left = None
self.right = None

# Create tree nodes


tree = Tree(20)
tree.left = Tree(18)
tree.right = Tree(22)

# Print values
print(tree.left.val)
print(tree.right.val)

Output:-

4
Practical-5
Python script for building a Puzzle Solver.

def test(nums):
return nums.count(19) == 2 and nums.count(5) >= 3

# Test case 1
nums = [19, 19, 15, 5, 3, 5, 5, 2]
print("Original list:")
print(nums)
print("Check two occurrences of nineteen and at least three
occurrences of five in the said list:")
print(test(nums))

# Test case 2
nums = [19, 15, 15, 5, 3, 3, 5, 2]
print("\nOriginal list:")
print(nums)
print("Check two occurrences of nineteen and at least three
occurrences of five in the said list:")
print(test(nums))

# Test case 3
nums = [19, 19, 5, 5, 5, 5, 5]
print("\nOriginal list:")
print(nums)
print("Check two occurrences of nineteen and at least three
occurrences of five in the said list:")

Output:-

5
Practical-6

Implementation of Naïve Bayes classifier, computing its accuracy and visualizing

its performance.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report,
confusion_matrix

# Load the dataset


iris = load_iris()
X, y = iris.data, iris.target
class_names = iris.target_names

# Split dataset into training and test sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Create and train the Naive Bayes model


model = GaussianNB()
model.fit(X_train, y_train)

# Predict on the test data


y_pred = model.predict(X_test)

# Compute accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

# Classification Report
print("\nClassification Report:")
print(classification_report(y_test,y_pred,
target_names=class_names))

6
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)

# Visualize Confusion Matrix


plt.figure(figsize=(6, 4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=class_names, yticklabels=class_names)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Naïve Bayes Classifier -
Confusion Matrix')
plt.tight_layout()
plt.show()

Output:-

7
Practical-7

Creation of a fuzzy control system which models how you might choose to tip at a

restaurant.

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt

# Define fuzzy variables


food = ctrl.Antecedent(np.arange(0, 11, 1), 'food')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

# Membership functions
food.automf(3) # poor, average, good
service.automf(3) # poor, average, good

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

# Fuzzy rules
rule1 = ctrl.Rule(service['poor'] | food['poor'], tip['low'])
rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] & food['good'], tip['high'])

# Control system
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)

# Input values
tipping.input['food'] = 6.5
tipping.input['service'] = 9.8

# Compute result
tipping.compute()
print(f"Recommended tip: {tipping.output['tip']:.2f}%")

8
# Visualize output
tip.view(sim=tipping)
plt.show()

Output:-

9
Practical-8

Implementation of uninformed search techniques in python


Uninformed Search Algorithms:

The search algorithms in this section have no additional information on the goal node other than the one
provided in the problem definition. The plans to reach the goal state from the start state differ only by the
order and/or length of actions. Uninformed search is also called Blind search.

The following uninformed search algorithms are discussed in this section.

1. Depth First Search

2. Breadth First Search

3. Uniform Cost Search

Eachofthese algorithmswill have:

• A problem graph, containing the start node S and the goal node G.
• A strategy, describing the manner in which the graph will be traversed to get to G
• A fringe, which is a data structure used to store all the possible states(nodes) thatyou can
go from the current states.
• A tree, that results while traversing to the goal node.
• A solution plan, which these quence of nodes from S to G.

➢ Depth-first search(DFS):-

Is an algorithm for tree traversal on graph or tree data structures. It can be implemented easily using
recursion and data structures like dictionaries and sets.

➢ The Algorithm

1. Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.

2. Repeat until all the nodes are visited, or the node to be searched is found.

Implementation

Consider this graph, implemented in the code below:

10
Program:
# Using a Python dictionary to act as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

visited = set() # Set to keep track of visited nodes

def dfs(visited, graph, node):


if node not in visited:
print(node)
visited.add(node)
for neighbor in graph[node]:
dfs(visited, graph, neighbor)

# Start DFS from node 'A'


dfs(visited, graph, 'A')

Output:

11
Breadth-first search(BFS):
IT is an algorithm used for tree traversal on graphs or tree data structures. BFS can be easily implemented
using recursion and data structures like dictionaries and lists.

The Algorithm

1. Pick any node, visit the adjacent unvisited vertex, mark it as visited, display it, and insert it in a

queue.

2. If there are no remaining adjacent vertices left, remove the first vertex from the queue.

3. Repeat step1 and step2 until the queue is empty or the desired node is

found.

Implementation

Consider the graph, which is implemented in the code below:

12
Program:-
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

visited = [] # List to keep track of visited nodes


queue = [] # Initialize a queue

def bfs(visited, graph, node):


visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print(s, end=" ")

for neighbour in graph[s]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Call the BFS function starting from 'A'


bfs(visited, graph, 'A')

Output:

13
Uniform-cost Search Algorithm:

Uniform-cost search is a searching algorithm used for traversing a weighted tree or graph. This algorithm
comes in top lay when a different cost is available for each edge. The primary goal of the uniform-cost
search is to find a path to the goal node which has the lowest cumulative cost. Uniform-cost search expands
nodes according to their pathcostsformtherootnode.Itcanbeusedtosolveanygraph/treewheretheoptimal cost is
in demand. A uniform-cost search algorithm is implemented by the priority queue. It gives maximum
priority to the lowest cumulative cost. Uniform cost search is equivalent to BFS algorithm if the path cost of
all edges is the same.

Advantages:
Uniform cost search is optimal because at every state the path with the least costis chosen.

Disadvantages:
It does not care about the number of steps involve in searching and only concerned about path cost. Due to
which this algorithm may be stuck in an infinite loop.

Example

14
Practical-9
Implementation of heuristic search techniques in Python.

What is Heuristics?

A heuristic is a technique that is used to solve a problem faster than the classic methods. These techniques
are used to find the approximate solution of a problem when classical methods do not. Heuristics are said to
be the problem solving techniques that result in practical and quick solutions .Heuristics are strategies that
are derived from past experience with similar problems. Heuristics use practical methods and shortcuts used
to produce the solutions that may or may not be optimal, but those solutions are sufficient in a given limited
timeframe.

Heuristic search techniques in AI(Artificial Intelligence)

What is the hill-climbing algorithm?


The hill-climbing algorithm is a local search algorithm used in mathematical optimization. An important
property of local search algorithms is that the path to the goal does not matter, only the goal itself matters.
Because of this, we do not need to worry about which path we took in order to reach a certain goal state, all
that matters is that we reached it. The basic principle behind the algorithm is moving across neighbouring
states according to elevation or increase in value. This working principle also causes the algorithm to be
susceptible to local maximums.

15
Program:
import numpy as np

def find_neighbours(state, landscape):


neighbours = []
dim = landscape.shape

# Cardinal directions
if state[0] != 0:
neighbours.append((state[0] - 1, state[1])) # left
if state[0] != dim[0] - 1:
neighbours.append((state[0] + 1, state[1])) # right
if state[1] != 0:
neighbours.append((state[0], state[1] - 1)) # top
if state[1] != dim[1] - 1:
neighbours.append((state[0], state[1] + 1)) # bottom

# Diagonals
if state[0] != 0 and state[1] != 0:
neighbours.append((state[0] - 1, state[1] - 1)) # top-left
if state[0] != 0 and state[1] != dim[1] - 1:
neighbours.append((state[0] - 1, state[1] + 1)) # bottom-left
if state[0] != dim[0] - 1 and state[1] != 0:
neighbours.append((state[0] + 1, state[1] - 1)) # top-right
if state[0] != dim[0] - 1 and state[1] != dim[1] - 1:
neighbours.append((state[0] + 1, state[1] + 1)) # bottom-right

return neighbours

def hill_climb(curr_state, landscape):


neighbours = find_neighbours(curr_state, landscape)
ascended = False
next_state = curr_state

for neighbour in neighbours:


if landscape[neighbour[0]][neighbour[1]] >
landscape[next_state[0]][next_state[1]]:
next_state = neighbour
ascended = True

return ascended, next_state

def main():
landscape = np.random.randint(1, high=50, size=(10, 10))
print("Landscape:\n", landscape)

16
start_state = (3, 6)
current_state = start_state
count = 1
ascending = True

while ascending:
print(f"\nStep #{count}")
print("Current State:", current_state)
print("Value:", landscape[current_state])
ascending, current_state = hill_climb(current_state, landscape)
count += 1

print("\nReached local/global maximum at", current_state, "with


value", landscape[current_state])

if name == " main ":


main()

Output:

17
Best first search(BFS)
This algorithm always chooses the path which appears best at that moment. It is the combination of depth-
first search and breadth-first search algorithms. It lets us to take the benefit of both algorithms. It uses the
heuristic function and search. With the help of the best-first search, at each step, we can choose the most
promising node.

Best First Search Algorithm – Steps

Step 1:
Place the starting node into the OPEN list (priority queue based on h(n)).

Step 2:
If the OPEN list is empty, stop and return failure.

Step 3:
Remove the node n from the OPEN list that has the lowest value of h(n), and place it into the CLOSED
list.

Step 4:
Expand node n, generating all its successors.

Step 5:
For each successor of node n, check whether it is a goal node:

 If yes, return success and stop the search.


 If not, continue to the next step.

Step 6:
For each successor:

 Evaluate the function f(n) = h(n).


 If the node is not in OPEN or CLOSED, add it to the OPEN list.

Step 7:
Go back to Step 2.

18
Practical-10
Python script for tokenizing text data.

Understanding Tokenization:-Tokenization is said to be dividing a large quantity of text into smaller


fragments known as Tokens. These fragments or Tokens are pretty useful to find the patterns and are
deliberated as the foundation step for stemming and lemmatization.

Tokenization so supports in substitution of sensitive data elements with non-sensitive ones.

Natural Language Processing(NLP) is utilized to create applications like Text Classification, Sentimental
Analysis, Intelligent Chat bot, Language Translation, and many more. Thus, it becomes important to
understand the text pattern to achieve the purpose stated above.

Token Types:
The kind field: It contains one of the following integer constants, which are defined under the TOK class.

The txt field: It contains the original text, and in some cases, it is noticed that the tokenizer auto-corrects the
source text. It is seen to convert the single and double quotes to the Icelandic ones.

The val field: This field contains auxiliary information according to the corresponding token.

Methods to Perform Tokenization in Python

Below are listed the number of methods to perform Tokenization:

• Python’s split function


• Using Regular Expressions with NLTK

Python’s split function: This is the most basic one, and it returns a list of strings after splitting the string
based on a specific separator. The separators can be changed as needed. Sentence Tokenization: Here, the
structure of the sentence is analyzed. As we know, a sentence ends with a period(.); therefore, it can be used
as a separator.

Program:-
my_text="""Let'splayagame,WouldYouRather!It'ssimple,youhavetopickoneortheother.Let'sgetstarted.Would
yourathertryVanillaIceCreamorChocolateone?Wouldyouratherbeabirdorabat?Wouldyouratherexplorespaceo
rtheocean?WouldyouratherliveonMarsorontheMoon?Wouldyouratherhavemanygoodfriendsoroneverybestfri
end?Isn'titeasythough?Whenwehavelesschoices,it'seasiertodecide.Butwhatiftheoptionswouldbecomplicated?
Iguess,youprettymuchnotunderstandmypoint,neitherdidI,atfirstplaceandthatledmetoaBadDecision."""

print(my_text.split())

Output:

19
Using Regular Expressions with NLTK: Regular expression is basically a character sequence that helps us
search for the matching patterns in the text we have. The library used in Python for Regular expression is re,
and it comes pre-installed with the Python package. Example: We have imported re library use \w+ for
picking up specific words from the expression.

Program:-
Import re

my_text="""TheAdvertisementwastelecastednationwide,andtheproductwassol d in around 30 states


ofAmerica.Theproductbecamesosuccessfulamongthepeoplethattheproductionwasincreased.Twonewplantsite
swerefinalized,andtheconstruction was started. Now,The Cloud Enterprise became one ofAmerica's biggest
firms and the mass producer in all major sectors, from transportation to personal car e. Director of The
Cloud Enterprise, Ryan Cloud, was now started gettinginterviewe d over his success stories. Many popular
magazines were started publishing Critique s about him."""

my_sentences=re.compile('[.!?]').split(my_text)
print(my_sentences)

Output:

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

Bag of words(BoW) model in NLP


Natural Language Processing technique of text modeling known as Bag of Words model. Whenever we
apply any algorithm in NLP, it works on numbers. We cannot directly feed our text into that algorithm.
Hence, Bag of Words model is used to preprocess the text by converting it into a bag of words, which keeps
a count of the total occurrences of most frequently used words. This model can be visualized using a table,
which contains the count of words corresponding to the word itself.

The steps involved in creating the BOW model for a piece of text are as follows:

1. Tokenize the text and store the tokens in a list.

2. Create a vocabulary out of the tokens.

3. Count the number of occurrences of tokens in each sentence and store the count.

4. Create a bag of words model by converting the text into vectors with count of each word from the
vocabulary.

Program:-
from keras.preprocessing.text import Tokenizer

# Text corpus

text = [
'Therewasaman',

'Themanhadadog',

'Thedogandthemanwalked',

# Using tokenizer

model = Tokenizer()

model.fit_on_texts(text)

# Print keys (vocabulary)

print(f'Key: {list(model.word_index.keys())}')

# Create bag-of-words representation

rep = model.texts_to_matrix(text, mode='count')

print(rep)

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

1. Text Preprocessing
 Clean the text (remove punctuation, lowercase, etc.)
 Tokenize it
 Convert it to numerical features (using Bag of Words, TF-IDF, or embeddings)

2. Train a Classifier
You'll need a labeled dataset where each text has a known category. Then you train a model like:

 Naive Bayes
 Logistic Regression
 SVM
 or Deep Learning models (LSTM, BERT, etc.)

3. Make Predictions
Once the model is trained, you can predict the category for new/unseen text.

Program:
from sklearn.feature_extraction.text import CountVectorizer

from sklearn.naive_bayes import MultinomialNB

# Sample data

texts = ['I love pizza', 'This is a great movie', 'Politics is


complicated', 'Elections are coming soon']

labels = ['food', 'entertainment', 'politics', 'politics']

# Preprocess & vectorize

vectorizer = CountVectorizer()

X = vectorizer.fit_transform(texts)

# Train model

model = MultinomialNB()

model.fit(X, labels)

22
# Predict category of a new text

new_text = ['I watched a fun movie']

X_new = vectorizer.transform(new_text)

prediction = model.predict(X_new)

print(f'Predicted category: {prediction[0]}')

Output:

23
Practical-13

Python code for visualizing audio speech signal.

import PySimpleGUI as sg
import numpy as np

# GLOBAL VARS
_VARS = {
'xData': False,
'yData': False,
'animate': False
}

# CONSTS
dataSize = 100
dataRangeMin = 0
dataRangeMax = 100

# GUI Setup
sg.theme('LightBrown11')
AppFont = 'Any 16'

layout = [
[sg.Graph(
canvas_size=(600, 600),
graph_bottom_left=(-20, -20),
graph_top_right=(110, 110),
background_color='#F1D7AB',
key='graph')],
[sg.Button('StartStop', font=AppFont),
sg.Button('Exit', font=AppFont)]
]

window = sg.Window('Update Random Points', layout, grab_anywhere=True,


finalize=True)
graph = window['graph']

24
# --- METHODS ---

def makeSynthData():
_VARS['xData'] = np.random.randint(dataRangeMin, dataRangeMax,
size=dataSize)
_VARS['yData'] = np.linspace(dataRangeMin, dataRangeMax,
num=dataSize, dtype=int)

def drawAxis():
graph.DrawLine((dataRangeMin, 0), (dataRangeMax, 0))
graph.DrawLine((0, dataRangeMin), (0, dataRangeMax))

def drawTicks(step):
for x in range(dataRangeMin, dataRangeMax + 1, step):
graph.DrawLine((x, -3), (x, 3))
if x != 0:
graph.DrawText(x, (x, -10), color='black')
for y in range(dataRangeMin, dataRangeMax + 1, step):
graph.DrawLine((-3, y), (3, y))
if y != 0:
graph.DrawText(y, (-10, y), color='black')

def drawPlot():
for i, y in enumerate(_VARS['yData']):
xCoord = _VARS['xData'][i]
yCoord = y
graph.DrawCircle((xCoord, yCoord), radius=1.5,
fill_color='black')

# --- MAIN LOOP ---


drawAxis()
drawTicks(10)

while True:
event, values = window.read(timeout=100)

if event in (sg.WINDOW_CLOSED, 'Exit'):


break

elif event == 'StartStop':


_VARS['animate'] = not _VARS['animate']
if _VARS['animate']:

25
makeSynthData()
graph.Erase()
drawAxis()
drawTicks(10)
drawPlot()

window.close()

Output:

26
Practical-14

Python code for Generating audio signals.

import numpy as np
import sounddevice as sd

# Parameters
duration = 2.0 # seconds
frequency = 440.0 # A4 note in Hz
sample_rate = 44100 # samples per second

# Generate time values


t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)

# Generate sine wave


audio = 0.5 * np.sin(2 * np.pi * frequency * t)

# Play the audio


sd.play(audio, samplerate=sample_rate)
sd.wait() # Wait until the sound has finished playing

What Happens:
 A sine wave tone of 440 Hz (A4 pitch) plays through your default speaker or headphones.
 The tone lasts for 2 seconds.
 The waveform is smooth and continuous, like a musical tuning fork tone.
 Output is audible only, not visible (you don’t get a printed result in the terminal).

What You Hear:


 A clean beep/tone at 440 Hz — the standard tuning pitch (concert A).

27
Practical-15
Python code for Synthesizing tones to generate music.

from scipy.io.wavfile import write


from numpy import linspace, sin, pi, int16
from pylab import plot, show, axis

# Tone synthesis function


def note(freq, length, amp=1, rate=44100):
t = linspace(0, length, int(length * rate)) # Time array
data = sin(2 * pi * freq * t) * amp
return data.astype(int16) # Convert to 16-bit PCM

# A 440 Hz tone (A4), 2 seconds long


tone = note(440, 2, amp=10000)

# Save to WAV file


write('440hzAtone.wav', 44100, tone)

# Plot the waveform


plot(linspace(0, 2, 2 * 44100), tone)
axis([0, 0.01, -15000, 15000]) # Zoom in to see the wave cycles
show()

Output:

28
29

You might also like