0% found this document useful (0 votes)
4 views19 pages

Ai Programs

The document outlines a practical list of experiments for a BCA 6th semester course on Artificial Intelligence at Malout Institute. It includes various Python programming tasks such as logic programming, implementing classifiers, fuzzy control systems, and search techniques. Each program is designed to teach fundamental AI concepts through hands-on coding exercises.
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)
4 views19 pages

Ai Programs

The document outlines a practical list of experiments for a BCA 6th semester course on Artificial Intelligence at Malout Institute. It includes various Python programming tasks such as logic programming, implementing classifiers, fuzzy control systems, and search techniques. Each program is designed to teach fundamental AI concepts through hands-on coding exercises.
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/ 19

MALOUT INSTITUTE OF MANAGEMENT AND

INFORMATION TECHNOLOGY, MALOUT


BCA 6th Semester
Artificial Intelligence Practical Experiments

Presented By: Ms. Gaganpreet Kaur


PRACTICAL LIST FOR ARTIFICIAL INTELLIGENCE
1. Learn the building blocks of Logic programming in Python
2. Python Script for comparing mathematical expression and finding the
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
Program 1: Learn the building blocks of logic programming in Python

Python is a computer programming language often used to build websites


and software, automate tasks, and conduct data analysis. Python is a
general-purpose programming language that means it can be used to
create a variety of different programs.
Python is an interpreted, interactive, object-oriented programming
language, it incorporates modules dynamically.
Building blocks of Python:
Python put emphasis on code readability with its notable use of significant
white spaces. Most modern programming language have a set of similar
building blocks:
• Receiving input from the user and showing output to the user.
• Ability to store value in variables of different kinds such as integer,
floating points, and character.
• A string of character where you can store names, address, or any
other kind of text.
• Some advanced data types such as arrays, which can store a series
of regular variables such as a series of integers.
• Ability to loop your code in the sense, suppose you want the user to
enter ten names so you have to enter the same code ten times to
make that possible, but loops allow you to write the code only once
then loops it for ten times to get ten names from the user.
• Ability to execute statement of code conditionally. For Example: We
can make a program that pass the students if the marks are more
than or equal to 40 else fail them.
• You can put your code in functions.
• Advanced data types are formed through a combination of one or
more data types such as structure and classes.
• You can read a file from a CD and save the file to CD.
• Ability to comment on your code so you can understand it when you
revisit it sometimes later.
Program 2: Python script for comparing mathematical expression and
finding out unknown values.
def evaluate_expression(expression: str, variable: str, value: int):
try:
return eval(expression.replace(variable, str(value)))
except:
return None

def solve_equation(expression1, expression2, variable):


for i in range(-156, 157):
result1 = evaluate_expression(expression1, variable, i)
result2 = evaluate_expression(expression2, variable, i)
if result1 is not None and result2 is not None and result1
== result2:
return i
return None
expression1='2*x+5'
expression2='x+8'
variable = 'x'
print(solve_equation(expression1, expression2, variable))

Output:
Program 3: Use Logic programming in Python to check for prime numbers.
def primechecker(num):
if num == 1:
print("Not a prime number")
elif num > 1:
prime = True
for i in range(2, num):
if num % i == 0:
print("Not a prime number")
prime = False
break
if prime:
print("Prime number")
else:
print("Not a prime number")

num = int(input("Enter number: "))


primechecker(num)

Output:
Program 4: Use logic programming in Python parse a family tree and infer
the relationships between the family members.
family_tree = {
"John": ["William", "David", "Adam"],
"William": ["Chris"],
"David": ["Wayne", "Tiffany", "Julie"],
# ... and so on
}

def is_parent(parent, child):


return child in family_tree.get(parent, [])

def is_grandparent(grandparent, grandchild):


for parent in family_tree.get(grandchild, []):
if is_parent(grandparent, parent):
return True
return False

def are_siblings(person1, person2):


if person1 == person2:
return False
parent = set(family_tree.get(person1, [])).intersection(
family_tree.get(person2, [])
)
return bool(parent)

# Examples
print("Is John the grandparent of Wayne?", is_grandparent("John",
"Wayne"))
print("Are Chris and Julie siblings?", are_siblings("Chris",
"Julie"))

Output:
Program 5: Python Script for building a puzzle solver

def solve_sudoku(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if all(num != board[row][i] for i in range(9)) \
and all(num != board[i][col] for i in range(9)) \
and all(num != board[row // 3 * 3 + i // 3][col //
3 * 3 + i % 3] for i in range(9)):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0
return False
return True
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
print("Original puzzle:")
for row in puzzle:
print(" ".join(map(str, row)))

print("\nSolving...")
if solve_sudoku(puzzle):
print("\nSolution:")
for row in puzzle:
print(" ".join(map(str, row)))
else:
print("No solution exists")

Output:
Program 6: Implementation of Naïve Bayes classifier, computing its accuracy and
visualizing its performance.

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, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt

iris = load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)

print("X_train shape:", X_train.shape)


print("y_train shape:", y_train.shape)
print("X_test shape:", X_test.shape)
print("y_test shape:", y_test.shape)

nb_classifier = GaussianNB()

nb_classifier.fit(X_train, y_train)
y_pred = nb_classifier.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)


print("Accuracy:", accuracy)

conf_mat = confusion_matrix(y_test, y_pred)


print("Confusion matrix:\n", conf_mat)

plt.figure(figsize=(8, 6))
sns.heatmap(conf_mat, annot=True, cmap='Blues', fmt='d',
xticklabels=iris.target_names, yticklabels=iris.target_names)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()

Output:
Program 7: Creation of a fuzzy control system which models how you might choose to
tip at a restaurant.

import numpy as np
def trimf(x, params):
a, b, c = params
result = np.zeros_like(x)
mask_ab = np.logical_and(a < x, x < b)
mask_bc = np.logical_and(b < x, x < c)
result[mask_ab] = (x[mask_ab] - a) / (b - a)
result[mask_bc] = (c - x[mask_bc]) / (c - b)
return np.maximum(0, np.minimum(result, 1))
service_quality_universe = np.arange(0, 11, 1)
food_quality_universe = np.arange(0, 11, 1)
tip_universe = np.arange(0, 26, 1)
service_quality_poor = trimf(service_quality_universe, [0, 0, 5])
service_quality_average = trimf(service_quality_universe, [0, 5, 10])
service_quality_good = trimf(service_quality_universe, [5, 10, 10])

food_quality_poor = trimf(food_quality_universe, [0, 0, 5])


food_quality_average = trimf(food_quality_universe, [0, 5, 10])
food_quality_good = trimf(food_quality_universe, [5, 10, 10])
tip_low = trimf(tip_universe, [0, 0, 13])
tip_medium = trimf(tip_universe, [0, 13, 25])
tip_high = trimf(tip_universe, [13, 25, 25])
def evaluate_rules(service_quality, food_quality):
rules = []
if service_quality == 'poor' or food_quality == 'poor':
rules.append(tip_low)
if service_quality == 'average':
rules.append(tip_medium)
if service_quality == 'good' or food_quality == 'good':
rules.append(tip_high)
return np.max(np.vstack(rules), axis=0)
def defuzzify(output_mf, universe):
if np.sum(output_mf) == 0:
return np.mean(universe)
else:
return np.sum(output_mf * universe) / np.sum(output_mf)
service_quality_input = 7
food_quality_input = 9
aggregated_output_mf = evaluate_rules('good', 'good')

# Defuzzify output
tip_output = defuzzify(aggregated_output_mf, tip_universe)

print("Recommended tip:", tip_output)

Output:
Program 8: Implementation of uninformed search techniques in python

from collections import deque

class Graph:
def __init__(self, graph):
self.graph = graph

def bfs(self, start, goal):


queue = deque([(start, [start])])
while queue:
node, path = queue.popleft()
if node == goal:
return path
queue.extend((neighbor, path + [neighbor]) for neighbor in
self.graph[node])

def dfs(self, start, goal):


stack = [(start, [start])]
while stack:
node, path = stack.pop()
if node == goal:
return path
stack.extend((neighbor, path + [neighbor]) for neighbor in
self.graph[node])

def ucs(self, start, goal):


queue = [(0, start, [start])]
while queue:
cost, node, path = queue.pop(0)
if node == goal:
return path
queue.extend((cost + neighbor_cost, neighbor, path + [neighbor])
for neighbor, neighbor_cost in self.graph[node].items())
queue.sort()
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'D': 3},
'C': {'A': 4, 'D': 2},
'D': {'B': 3, 'C': 2, 'E': 5},
'E': {'D': 5}
}
g = Graph(graph)
print("BFS:", g.bfs('A', 'E')) #BFS
print("DFS:", g.dfs('A', 'E')) #DFS
print("UCS:", g.ucs('A', 'E')) #UCS

Output:
Program 9: Implementation of heuristic search techniques in python

import heapq

class Graph:
def __init__(self, graph):
self.graph = graph

def astar(self, start, goal):


open_list = [(0, start, [start])]
closed_set = set()

while open_list:
_, current, path = heapq.heappop(open_list)
if current == goal:
return path
if current in closed_set:
continue
closed_set.add(current)
for neighbor, cost in self.graph[current].items():
if neighbor not in closed_set:
heapq.heappush(open_list, (len(path) + cost, neighbor,
path + [neighbor]))

return None

# Example graph
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'D': 3},
'C': {'A': 4, 'D': 2},
'D': {'B': 3, 'C': 2, 'E': 5},
'E': {'D': 5}
}

# Create Graph object


g = Graph(graph)

# Test A*
print("A*:", g.astar('A', 'E'))

Output:
Program 10: Python Script for Tokenizing Text Data

import re

def tokenize_text(text):
pattern = r'\b\w+\b'

words = re.findall(pattern, text)

return words

# Example text data


text_data = "This is a sample sentence for tokenization. We will tokenize this
into words."

# Tokenize the text into words


tokenized_words = tokenize_text(text_data)

# Print the tokenized words


print("Tokenized words:", tokenized_words)

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

from sklearn.feature_extraction.text import CountVectorizer

# Example corpus
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]

# Create a CountVectorizer object


vectorizer = CountVectorizer()

# Learn the vocabulary and transform the documents into a term-document matrix
bow_matrix = vectorizer.fit_transform(corpus)

# Get the vocabulary (terms)


vocabulary = vectorizer.get_feature_names_out()

# Print the term frequency for each term in the vocabulary


for i, term in enumerate(vocabulary):
print(f'Term: {term}, Frequency: {bow_matrix[:, i].sum()}')

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

from sklearn.feature_extraction.text import CountVectorizer


from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

# Example training data


train_texts = ["This is a positive review",
"Negative review: do not buy this product",
"Great experience, highly recommended",
"Terrible service, would not come back",
"Expectations were not that high",
"Nice"]

# Example labels for the training data


train_labels = ["Positive", "Negative", "Positive", "Negative", "Positive",
"Positive"]

# Create a pipeline combining a bag-of-words vectorizer with a Naive Bayes


classifier
model = make_pipeline(CountVectorizer(), MultinomialNB())

# Train the model


model.fit(train_texts, train_labels)

# Example text to predict its category


text_to_predict = "This product exceeded my expectations"

# Predict the category for the given text


predicted_category = model.predict([text_to_predict])[0]

# Print the predicted category


print("Predicted category:", predicted_category)

Output:
Program 13: Python code for visualizing audio speech signal

import pyaudio
import speech_recognition as sr
import numpy as np
import matplotlib.pyplot as plt

def record_audio(seconds=5, sample_rate=44100, chunk_size=1024):


audio = pyaudio.PyAudio()
stream = audio.open(format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True,
frames_per_buffer=chunk_size)

print("Recording...")
frames = []
for i in range(0, int(sample_rate / chunk_size * seconds)):
data = stream.read(chunk_size)
frames.append(data)

print("Recording finished.")
stream.stop_stream()
stream.close()
audio.terminate()

return np.frombuffer(b''.join(frames), dtype=np.int16)


def plot_sound_wave(audio_data, sample_rate):
time = np.linspace(0, len(audio_data) / sample_rate, num=len(audio_data))
plt.plot(time, audio_data)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Sound Wave')
plt.show()

def transcribe_speech(audio_data, sample_rate):


recognizer = sr.Recognizer()
audio_source = sr.AudioData(audio_data.tobytes(), sample_rate, 2)

try:
text = recognizer.recognize_google(audio_source)
print("Transcription:", text)
except sr.UnknownValueError:
print("Speech Recognition could not understand audio.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition
service; {0}".format(e))

if __name__ == "__main__":
# Record audio
audio_data = record_audio()

# Plot sound wave


plot_sound_wave(audio_data, sample_rate=44100)

# Transcribe speech
transcribe_speech(audio_data, sample_rate=44100)

Output:
Program 14: Python code for Generating audio signals

import numpy as np
import scipy.io.wavfile as wav

# Parameters
duration = 3 # seconds
sampling_freq = 44100 # Hz
frequency = 440 # Hz (frequency of the sine wave)

# Generate time vector


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

# Generate sine wave


signal = np.sin(2 * np.pi * frequency * t)

# Scale to 16-bit range


signal *= 32767

# Convert to 16-bit integers


signal = np.int16(signal)

# Write the audio signal to a file


wav.write('sine_wave.wav', sampling_freq, signal)

Output:

sine_wave.wav
Program 15: Python code for synthesizing tones to generate music

import numpy as np
import sounddevice as sd

# Parameters
duration = 0.5 # seconds
sampling_freq = 44100 # Hz
notes_freq = {'C': 261.63, 'D': 293.66, 'E': 329.63, 'F': 349.23, 'G': 392.00,
'A': 440.00, 'B': 493.88}

def generate_sine_wave(freq, duration, sampling_freq):


t = np.linspace(0, duration, int(sampling_freq * duration),
endpoint=False)
return np.sin(2 * np.pi * freq * t)

def generate_melody(notes, duration, sampling_freq):


melody = []
for note in notes:
freq = notes_freq.get(note, 0)
if freq:
melody.extend(generate_sine_wave(freq, duration, sampling_freq))
else:
melody.extend(np.zeros(int(duration * sampling_freq)))
return np.array(melody)

melody_notes = "CDEFGABC"
melody = generate_melody(melody_notes, duration, sampling_freq)

# Play the melody


sd.play(melody, sampling_freq)
sd.wait()

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