You are on page 1of 23

HMR INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Hamidpur, Delhi-110036
(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi)

Submitted in partial fulfilment of the requirements


For the award of degree of
Bachelor of Technology
In
Computer Science and Engineering
2021-2025
ARTIFICIAL INTELLIGENCE
Lab File
Code: CIE-374 (P)
SUBMITTED TO: SUBMITTED
BY:
Mr. Karmbir Khatri Name
Assistant Professor 000000
CSE Department CSE 6B
INDEX

S. Name of Program Date Of Submission Signature


No Practical Date /
Remarks
1. Study of PROLOG.

2. Write sample fact for the statements


using PROLOG
a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.
3. Write predicates, one converts
Centigrade temperature to Fahrenheit,
the other checks if a temperature is
below freezing using PROLOG.
4. Write a program to implement Breadth
First Search Traversal.

5. Write a program to implement Water


Jug Problem.

6. Write a program to remove stop words


for a given passage from a text file
using NLTK.
7. Write a program to implement
streaming for a given sentence using
NLTK.
8. Write a program to POS (part of speech)
tagging for the given sentence using
NLTK.

9. Write a program to implement


Lemmatization using NLTK.
10. Write a program for text classification
for the given sentence using NLTK.

PRACTICAL 1
AIM: Study of PROLOG.

PROLOG-PROGRAMMING IN LOGIC
PROLOG stands for Programming, In Logic — an idea that emerged in the early 1970’s to use
logic as programming language. The early developers of this idea included Robert Kowaiski at
Edinburgh (on the theoretical side), Marrten van Emden at Edinburgh (experimental
demonstration) and Alian Colmerauer at Marseilles (implementation).
David D.H. Warren’s efficient implementation at Edinburgh in the mid -1970’s greatly
contributed to the popularity of PROLOG. PROLOG is a programming language centred around
a small set of basic mechanisms, including pattern matching, tree based data structuring and
automatic backtracking. This Small set constitutes a surprisingly powerful and flexible
programming framework. PROLOG is especially well suited for problems that involve objects-
in particular, structured objects- and relations between them.

SYMBOLIC LANGUAGE
PROLOG is a programming language for symbolic, non-numeric computation. It is especially
well suited for solving problems that involve objects and relations between objects. For example,
it is an easy exercise in prolog to express spatial relationship between objects, such as the blue
sphere is behind the green one. It is also easy to state a more general rule: if object X is closer to
the observer than object Y. and object Y is closer than Z, then X must be closer than Z.
PROLOG can reason about the spatial relationships and their consistency with respect to the
general rule. Features like this make PROLOG a powerful language for Artificial Language and
non- numerical programming.
There are well-known examples of symbolic computation whose implementation in other
standard languages took tens of pages of indigestible code, when the same algorithms were
implemented in PROLOG, the result was a crystal-clear program easily fitting on one page.

FACTS, RULES, AND QUERIES


Programming in PROLOG is accomplished by creating a database of facts and rules about
objects, their properties, and their relationships to other objects. Queries then can be posed about
the objects and valid conclusions will be determined and returned by the program Responses to
user queries are determined through a form of inference control known as resolution.
FOR EXAIPLE:
a) FACTS:
Some facts about family relationships could be written as:
sister( sue,bill)
parent( ann.sam)
male(jo)
female( riya)

b) RULES:
To represent the general rule for grandfather, we write: grandfather(X, Z)
parent(X,Y)
parent( Y,Z)
male(X)
c) QUERIES:

Given a database of facts and rules such as that above, we may make queries by typing after a
query a symbol’?’ statements such as:
?-parent(X,sam) X=ann
?grandfather(X,Y) X=jo, Y=sam

PROLOG IN DISGINING EXPERT SYSTEMS


An expert system is a set of programs that manipulates encoded knowledge to solve problems in
a specialized domain that normally requires human expertise. An expert system’s knowledge is
obtained from expert sources such as texts, journal articles. databases etc and encoded in a form
suitable for the system to use in its inference or reasoning processes. Once a sufficient body of
expert knowledge has been acquired, it must be encoded in some form, loaded into knowledge
base, then tested, and refined continually throughout the life of the system PROLOG serves as a
powerful language in designing expert systems because of its following features.
● Use of knowledge rather than data
● Modification of the knowledge base without recompilation of the control programs.
● Capable of explaining conclusion.
● Symbolic computations resembling manipulations of natural language.
● Reason with meta-knowledge.

META PROGRAMMING
A meta-program is a program that takes other programs as data. Interpreters and compilers are
examples of meta-programs. Meta-interpreter is a particular kind of meta-program: an interpreter
for a language written in that language. So a PROLOG interpreter is an interpreter for PROLOG,
itself written in PROLOG. Due to its symbol- manipulation capabilities, PROLOG is a powerful
language for meta-programming. Therefore, it is often used as an implementation language for
other languages. PROLOG is particularly suitable as a language for rapid prototyping where we
are interested in implementing new ideas quickly. New ideas are rapidly implemented and
experimented with.

OUTCOME: Students will get the basic idea of how to program in PROLOG and its working
environment.
PRACTICAL 2
AIM: Write simple fact for following:
a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.

PROGRAM:

Clauses
likes(ram ,mango).
girl(seema). red(rose).
likes(bill ,cindy).
owns(john ,gold).
OUTPUT:
PRACTICAL 3
AIM: Write predicates One converts centigrade temperatures to Fahrenheit, the other checks if a
temperature is below freezing.

PROGRAM:

% Production rules:

c_to_f
f is c * 9 / 5 + 32
freezing f < = 32

% Rules:

c_to_f(C,F) :-
F is C * 9 / 5 + 32.

freezing(F) :-
F =< 32.
OUTPUT:

Queries:
?- c_to_f(100,X). X = 212
Yes
?- freezing(15)
.Yes
?- freezing(45). No
PRACTICAL 4
AIM: Write a program to implement Breath First Search Traversal.
PROGRAM:
% Predicate to find a path using BFS and print visited nodes
bfs(Start, Goal, Visited) :-
bfs_iterative([[Start]], Goal, Visited).

% Base case: goal node is reached, print visited nodes


bfs_iterative([[Goal|Path]|_], Goal, Visited) :-
append([Goal], Path, Visited). % Append goal node for completeness

% Iterative BFS, exploring neighbors and printing visited nodes


bfs_iterative([[Node|Path]|Paths], Goal, Visited) :-
findall([NextNode, Node|Path],
(edge(Node, NextNode), \+ member(NextNode, [Node|Path])),
NewPaths),
append(Paths, NewPaths, UpdatedPaths),
% Print visited node before recursive call (breadth-first order)
write(Node), write(' -> '),
bfs_iterative(UpdatedPaths, Goal, Visited).

% Define your graph edges here (example)


edge(a, b).
edge(a, c).
edge(b, d).
edge(c, e).
edge(d, f).
edge(e, g).
OUTPUT:
PRACTICAL 5
AIM: Write a program to implement Water Jug Problem.
PROGRAM:
initial_state(start, (0, 0)).
goal_state(end1, (2, 0)).
goal_state(end2, (0, 2)).
next_state((X, Y), (4, Y)) :-
X < 4.
next_state((X, Y),(X, 3)) :-
Y < 3.
next_state((X, Y), (4, Z)) :-
Y > 0, X < 4,
Aux is X + Y, Aux >= 4,
Z is Y - (4 - X).
next_state((X, Y), (Z, 3)) :-
X > 0, Y < 3,
Aux is X + Y, Aux >= 3,
Z is X - (3 - Y).
next_state((X, Y),(Z, 0)) :-
Y > 0,
Aux is X + Y, Aux =< 4,
Z is Y + X.
next_state((X, Y),(0, Z)) :-
X > 0,
Aux is X + Y, Aux =< 3,
Z is Y + X.
next_state((X, Y), (0, Y)) :-
X > 0.
next_state((X, Y), (X, 0)) :-
Y > 0.
print_state((X, Y)) :-
write('4-gallon jug: '), write(X), nl, write('3-gallon jug: '), write(Y), nl, nl.
OUTPUT:
PRACTICAL 6
AIM: Write a program to remove stop words for a given passage from a text file using NLTK.
PROGRAM:
import nltk
from nltk.corpus import stopwords

def remove_stopwords(text):
stop_words = set(stopwords.words('english'))
word_tokens = nltk.word_tokenize(text)
filtered_text = [word for word in word_tokens if word.lower() not in stop_words]
return ' '.join(filtered_text)

if __name__ == "__main__":
with open('passage.txt', 'r') as file:
passage = file.read()
cleaned_text = remove_stopwords(passage)
print(cleaned_text)
OUTPUT:
PRACTICAL 7
AIM: Write a program to implement stemming for a given sentence using NLTK.
PROGRAM:
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from functools import reduce

ps = PorterStemmer()

sentence = "Stemming is the process of reducing words to their base form."


words = word_tokenize(sentence)

# using reduce to apply stemmer to each word and join them back into a string
stemmed_sentence = reduce(lambda x, y: x + " " + ps.stem(y), words, "")

print(stemmed_sentence)
OUTPUT:
PRACTICAL 8
AIM: Write a program to POS (part of speech) tagging for the give sentence using NLTK.
PROGRAM:
mport nltk
from nltk.tokenize import word_tokenize

def pos_tagging(sentence):
# Tokenize the sentence into words
words = word_tokenize(sentence)

# Perform POS tagging


tagged_words = nltk.pos_tag(words)

return tagged_words

# Example usage
if __name__ == "__main__":
sentence = "This is an example of POS tagging using NLTK in Python."
tagged_words = pos_tagging(sentence)
print("Original Sentence:", sentence)
print("POS Tagged Words:", tagged_words)
OUTPUT:
PRACTICAL 9
AIM: Write a program to implement Lemmatization using NLTK.
PROGRAM:
import spacy

# Load the spaCy English model


nlp = spacy.load('en_core_web_sm')

# Define a sample text


text = "The quick brown foxes are jumping over the lazy dogs."

# Process the text using spaCy


doc = nlp(text)

# Extract lemmatized tokens


lemmatized_tokens = [token.lemma_ for token in doc]

# Join the lemmatized tokens into a sentence


lemmatized_text = ' '.join(lemmatized_tokens)

# Print the original and lemmatized text


print("Original Text:", text)
print("Lemmatized Text:", lemmatized_text)
OUTPUT:
PRACTICAL 10
AIM: Write a program for Text Classification for the given sentence using NLTK.
PROGRAM:
import nltk
import random
from nltk.corpus import movie_reviews

# Load movie reviews dataset from NLTK


documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]

# Shuffle the documents to ensure randomness


random.shuffle(documents)

# Define a feature extractor function


def document_features(document):
words = set(document)
features = {}
for word in word_features:
features['contains({})'.format(word)] = (word in words)
return features

# Get the most frequent words as features


all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = list(all_words)[:2000]

# Extract features from the documents


featuresets = [(document_features(d), c) for (d,c) in documents]

# Split the dataset into training and testing sets


train_set, test_set = featuresets[:1500], featuresets[1500:]

# Train a Naive Bayes classifier


classifier = nltk.NaiveBayesClassifier.train(train_set)

# Evaluate the classifier on the test set


accuracy = nltk.classify.accuracy(classifier, test_set)
print("Accuracy:", accuracy)

# Example usage
sentence = "omg that is horrible!"
features = document_features(sentence.split())
classification = classifier.classify(features)
print("Sentence Classification:", classification)
OUTPUT:

You might also like