0% found this document useful (0 votes)
19 views50 pages

BATCH 2 AIML RECORD 1 Vignesh

Uploaded by

211001120
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)
19 views50 pages

BATCH 2 AIML RECORD 1 Vignesh

Uploaded by

211001120
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/ 50

IT19643 – ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

RECORD NOTEBOOK

NAME :

YEAR/BRANCH/SECTION :

ROLL NUMBER :

SEMESTER :

ACADEMIC YEAR :
IT19642 – OPERATING SYSTEM DESIGN LABORATORY

RECORD NOTEBOOK

NAME :

YEAR/BRANCH/SECTIO :
N

ROLL NUMBER :

SEMESTER :

ACADEMIC YEAR :
INDEX
PAGE
EXP. NO DATE EXPERIMENT NAME SIGNATURE
NO

1 01.02.2024 Study of Prolog 1

01.02.2024 a. Food table 11

08.02.2024 b. Student-Professor Relation table 12

15.02.2024 c. Family tree 13


2
22.02.2024 d. Arithmetic Expression 15

29.02.2024 e. Own pet and Love table 18

29.02.2024 f. Car Table 19

07.03.2024 a. Family Relationship 20

3 07.03.2024 b. Simple Facts and Queries 21

14.03.2024 c. Convert Centigrade to Fahrenheit 23

4 21.03.2024 Monkey Banana Problem 24

5 28.03.2024 Medical Diagnosis 26

6 04.04.2024 N-Queens Problem 32

7 04.04.2024 Travelling Salesman Problem 35

8 18.04.2024 Water Jug Problem 37

9 18.04.2024 Implementation of Linear Regression 39

10 25.04.2024 Implementation of Classification 41

11 25.04.2024 Implementation of Neural Networks 46

0
Roll No :211001120

Exp. No: 1
Study of Prolog
Date: 01.02.2024

Aim:
To study the prolog tool installation and overview and perform knowledge-based
program.
Prolog:
PROgraming in LOGic
• PROLOG is declarative- specify facts and logical relationships
• Non-procedural: & quot; what& quot;, not "how".
(We specify the problem but not the solution)
• Data base language with automated search and the ability to follow general rules.
Symbolic - symbols are used to represent objects
High level - contains a built-in problem solving mechanism
• PROLOG Programming (When we program in Prolog we need to provide
following three things declaring some facts about objects and their
relationships.
• Defining some rules about objects and their relationships.
• Asking questions about objects and their relationships.
Prolog Syntax
Terms:
The central data structure in PROLOG is that of a term.
There are terms of four kinds:
• atoms,
• numbers,
• variables, and
• Compound terms.
Atoms and numbers are sometimes grouped together and called atomic terms.
Atomic Terms:
Atomic terms are usually strings made up of lower- and uppercase letters, digits, and
the underscore, starting with a lowercase letter.
The following are all valid PROLOG atoms:

1
Roll No :211001120

• elephant,
• b,
• abcXYZ,
• x_123,
• another_print_for_me_please
Compound Terms:
• Compound terms are made up of a PROLOG atom and a number of
arguments (PROLOG terms, i.e., atoms, numbers, variables, or other
compound terms) enclosed in parentheses and separated by commas.
• The following are some examples for compound terms:
o is_bigger(horse, X), f(g(X, _), 7),
• The sets of compound terms and atoms together form the set of PROLOG
predicates.
• A term that doesn’t contain any variables is called a ground term.
Variables:
Variables are strings of letters, digits, and the underscore, starting with a capital
letter or an underscore.
Examples:
• X,
• Elephant,
• _4711,
• X_1_2,
• MyVariable,
Facts:
A fact is a predicate followed by a dot.
Examples:
• bigger_animal(whale).
• life_is_beautiful.
• The intuitive meaning of a fact is that we define a certain instance of a relation
as being true.
Rules:
• A rule consists of a head (a predicate) and a body (a sequence of predicates

2
Roll No :211001120

separated by commas).
• Head and body are separated by the sign :- and, like every PROLOG
expression, a rule has to be terminated by a dot.
Examples:
is_smaller(X, Y) :- is_bigger(Y, X).
aunt(Aunt, Child) :- sister(Aunt, Parent),parent(Parent, Child).
• The intuitive meaning of a rule is that the goal expressed by its head is true, if
we (or rather the PROLOG system) can show that all of the expressions
(subgoals) in the rule’s body are true.
Syntax of rule:
:-
Read :- as if.
->likes(john,X) :- likes(X,cricket).
~ “John likes X if X likes cricket”.
i.e., “John likes anyone who likes cricket“.
• Rules always end with’.’
Programs and Queries:
Programs : A PROLOG program is a sequence of clauses.
Queries –
• After compilation a PROLOG program is run by submitting queries to the
interpreter.
• A query has the same structure as the body of a rule, i.e. it is a sequence of
predicates separated by commas and terminated by a dot.
• They can be entered at the PROLOG prompt, which in most implementations
looks something like this: ?-.
• When writing about queries we often include the ?.
• Examples:
?- is_bigger(elephant, donkey).
?- small(X), green(X), slimy(X).
• Intuitively, when submitting a query like the last example, we ask PROLOG
whether all its predicates are probably true, or in other words whether there
is an X such that small(X), green(X), and slimy(X) are all true.

3
Roll No :211001120

There are two types of queries:


1) Ground Query
• edge(a,h)
• This query is called a ground query because it consists only of value
identifier as parameter to the predicate.
• A ground query is posed we expect a yes/no answer.
2) Non-Ground Query
They have variables as parameters
• edge(a,X)
Variables:
• Always begin with a capital letter
• ?- likes (john,X).
• ?- likes (john, Something).
• But not
• ?- likes (john,something)
Install SWI-Prolog:
Steps to Compile:
1. Open Notepad.
2. Write your Facts and Rules and save the file with .pl extension.
3. To open the desired file
File -> Edit -> Go to the location-> select file ->Open
4. To check the syntax
In file editor Compile ->make
If no error it will compile
5. To fire query
In PROLOG editor
File -> consult -> select the file name
Write the query, do not forget to put full stop (.) If there is more than one answer to
get use (;)
Exercises:
KB1
woman(mia).

4
Roll No :211001120

woman(jody).
woman(yolanda).
playsAirGuitar(jody).
party.
QUERY:
?-woman(mia).
?-playsAirGuitar(mia).
?-party.
?-concert.
KB2
happy(yolanda).
listens2music(mia).
listens2music(yolanda) :- happy(yolanda).
playsAirGuitar(mia) :- listens2music(mia).
playsAirGuitar(Yolanda) :-
listens2music(yolanda).
QUERY:
?-playsAirGuitar(mia).
?-playsAirGuitar(yolanda)
KB 3
likes(dan,sally).
likes(sally,dan).
likes(john,brittney).
married(X,Y) :- likes(X,Y) , likes(Y,X).
friends(X,Y) :- likes(X,Y) ; likes(Y,X).
QUERY:
?-likes(dan,X).
?-married(dan,sally).
?-married(john,brittney).
KB 4
bigger(elephant, horse).
bigger(horse, donkey).

5
Roll No :211001120

bigger(donkey, dog).
bigger(donkey, monkey).
RULES:
is_bigger(X, Y) :- bigger(X, Y).
is_bigger(X, Y) :- bigger(X, Z), is_bigger(Z, Y).
QUERIES:
?- bigger(donkey, dog).
?- bigger(monkey, elephant).
?- bigger(elephant, monkey).
KB 5
male(ram).
male(shyam).
female(gita).
female(sita).
parents(syam,gita,ram).
parents(sita,gita,ram).
sister_of (X,Y): -female (X),parents (X,M,F),parents (Y,M,F).
QUERIES:
?- sister_of(sita, shyam).
?- sister_of(sita,x)
KB 6
Facts:
male(jack).
male(oliver).
male(ali).
male(james).
male(simon).
male(harry).
female(helen).
female(sophie).
female(jess).
female(lily).

6
Roll No :211001120

parent_of(jack,jess).
parent_of(jack,lily).
parent_of(helen, jess).
parent_of(helen, lily).
parent_of(oliver,james).
parent_of(sophie, james).
parent_of(jess, simon).
parent_of(ali, simon).
parent_of(lily, harry).
parent_of(james, harry).
RULES:
father_of(X,Y):- male(X),
parent_of(X,Y).
mother_of(X,Y):- female(X),
parent_of(X,Y).
grandfather_of(X,Y):- male(X),
parent_of(X,Z),
parent_of(Z,Y).
grandmother_of(X,Y):- female(X),
parent_of(X,Z),
parent_of(Z,Y).
sister_of(X,Y):- %(X,Y or Y,X)%
female(X),
father_of(F, Y), father_of(F,X),X \= Y.
sister_of(X,Y):- female(X),
mother_of(M, Y), mother_of(M,X),X \= Y.
aunt_of(X,Y):- female(X),
parent_of(Z,Y), sister_of(Z,X),!.
brother_of(X,Y):- %(X,Y or Y,X)%
male(X),
father_of(F, Y), father_of(F,X),X \= Y.
brother_of(X,Y):- male(X),

7
Roll No :211001120

mother_of(M, Y), mother_of(M,X),X \= Y.


uncle_of(X,Y):-
parent_of(Z,Y), brother_of(Z,X).
ancestor_of(X,Y):- parent_of(X,Y).
ancestor_of(X,Y):- parent_of(X,Z),
ancestor_of(Z,Y).
QUERIES:
?-mother_of(jess,helen).
?-brother_of(james,simon).
?-ancestor_of(jack,simon).
?-parent_of(lily, harry).
?-ancestor_of(X,Y).
?-aunt_of(X,Y).
?-father_of(jack,lily).
?-grandfather_of(james,jess).
?-grandmother_of(sophie,james).
?-grandmother_of(X,Y).
?-parent_of(jess, simon).
Output:
KB1:

8
Roll No :211001120

KB2:

KB3:

KB4:

KB5:

9
Roll No :211001120

KB6:

Result:
Thus prolog tool installation and overview is studied and knowledge based program is
performed successfully.

10
Roll No :211001120

Exp. No: 2a
Food Table
Date: 01.02.2024
Aim:
To write facts, rules and queries for food table and perform the program.
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules , save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
food(burger).
food(sandwich).
food(pizza).
lunch(sandwich).
dinner(pizza).
Rules:
meal(X) :- food(X).
Queries / Goals:
?- food(pizza).
?- meal(X), lunch(X).
?- dinner(sandwich).
Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

11
Roll No :211001120

Exp. No: 2b
Student – Professor Relation Table
Date: 08.02.2024

Aim:
To write facts, rules and queries for student-professor table and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules , save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
studies(charlie, csc135).
studies(olivia, csc135).
studies(jack, csc131).
studies(arthur, csc134).
teaches(kirke, csc135).
teaches(collins, csc131).
teaches(collins, csc171).
teaches(juniper, csc134).
Rules:
professor(X, Y) :-
teaches(X, C), studies(Y, C).
Queries / Goals :
?- studies(charlie, What).
?- professor(kirke, Students).
Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

12
Roll No :211001120

Exp. No: 2c
Family Tree
Date: 15.02.2024

Aim:
To write facts, rules and queries for Family tree and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules, save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
father_of(joe,paul).
father_of(joe,mary).
father_of(joe,hope).
mother_of(jane,paul).
mother_of(jane,mary).
mother_of(jane,hope).
male(paul).
male(joe).
male(ralph).
male(X) :- father_of(X,Y).
female(mary).
female(jane).
female(hope).
son_of(X,Y) :- father_of(Y,X),male(X).
son_of(X,Y) :- mother_of(Y,X),male(X).
daughter_of(X,Y) :- father_of(Y,X),female(X).
daughter_of(X,Y) :- mother_of(Y,X),female(X).
sibling_of(X,Y) :- !,father_of(Z,X),father_of(Z,Y),X\=Y.
sibling_of(X,Y) :- !,mother_of(Z,X),mother_of(Z,Y),X\=Y.

13
Roll No :211001120

Queries:
?- sibling_of(paul,mary).
?- father_of (X, Y).
?-son_of (paul, joe).
?- son_of(joe, hope).
?- daughter of (X,Y).

Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

14
Roll No :211001120

Exp. No: 2d
Arithmetic Expression
Date: 22.02.2024

Aim:
To write facts, rules and queries for arithmetic expression and perform the program
Algorithm:
Step 1: Open Prolog Query prompt
Step 2: Enter the necessary queries
Step 3: Perform the arithmetic operations
Step 4: Display the results.
Queries:
?- X is 3+2.
?- 3+2 is X.
?- X = 3+2.
?- 3+2 = X.
?- X is +(3,2).
?- 5 is 3+2.
?- 3+2 is 5.
?- X is 3*2.
?- X is 3-2.
?- X is -(2,3).
?- X is 5-3-1.
?- X is -(5,3,1).
?- X is -(-(5,3),1).
?- X is 5-3-1.
?- X is 3/5.
?- X is 3 mod 5.
?- X is 5 mod 3.
?- X is 5^3.
?- X is (5^3)^2.
?- X = (5^3)^2.
?- 25 is 5^2.

15
Roll No :211001120

?- Y is 3+2*4-1.
?- Y is (3+2)*(4)-(1).
?- Y is -(*(+(3,2),4),1).
?- X is 3*2, Y is X*2.
?- 3<5.
?- 4<2.
?- 6>5.
?- 12<=12.
?- 12 =<12.
?- 3+4 =< 7.
?- 5=\=5.
?- 5=\=4.
?- 5=\=(3+2).
?- 8=8.
?- 8=:=8.
?- 8=:=9.
?- (2+1)*10 = 30.
?- (2+1)*10 =:= 30.
?- X=2, X<3.
?- X=4, X<3.
?- *(2,3) = 2*3.
?- X = Z.
?-(X>3)=(4>3).
?- X = 3, C is X*X*X.
?- X = 3, X*X*X is C.
?- is(Y,^(2,2)).

16
Roll No :211001120

Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

17
Roll No :211001120

Exp. No: 2e
Own Pet and love table
Date: 29.02.2024

Aim:
To write facts, rules and queries for own pet and love table and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
cat(fubby).
black_spots(fubby).
dog(figaro).
white_spots(figaro).
Rules:
owns(mary, Pet):- cat(Pet), black_spots(Pet).
loves(Who, What):-owns(Who, What).
Queries / Goals:
?- loves(Who, What).
?- owns(mary, _).
Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

18
Roll No :211001120

Exp. No: 2f
Car Table
Date: 29.02.2024

Aim:
To write facts, rules and queries for Car table and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules and save the file with extension .pl
Step 3: Run the file and enter the queries
Step 4: Display the result
Facts:
owns(jack, car(bmw)).
owns(john, car(chevy)).
owns(olivia, car(civic)).
owns(jane, car(chevy)).
sedan(car(bmw)).
sedan(car(civic)).
truck(car(chevy)).
Queries:
?- owns(john, X).
?- owns(john, _ ).
?- owns(Who, car(chevy)).
?- owns(jane, X), sedan(X).
?- owns(jane, X), truck(X).
Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

19
Roll No :211001120

Exp. No: 3a
Family Relationship
Date: 07.03.2024

Aim:
To write facts, rules and queries for Family Relationship and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
sister( sue,bill).
parent( ann.sam).
male(jo).
female( riya).
Rules:
grand father( X)
parent(X,Y)
parent( Y,Z)
male(X)
Queries:
?-parent(X,sam).
?grandfather(X,Y).
Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

20
Roll No :211001120

Exp. No: 3b
Simple facts and Queries
Date: 07.03.2024

Aim:
To write facts, rules and queries and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
Ram likes mango.
Seema is a girl.
Bill likes Cindy.
Rose is red.
John owns gold.

Clauses:
likes(ram ,mango).
girl(seema).
red(rose).
likes(bill ,cindy).
owns(john ,gold).

Queries:
?-likes(ram,What).
?-likes(Who,cindy).
?-red(What).
?-owns(Who,What).

21
Roll No :211001120

Output:

Result:
Thus, the facts and queries are entered and the program is performed successfully.

22
Roll No :211001120

Exp. No: 3c
Convert Centigrade to Fahrenheit
Date: 14.03.2024

Aim:
To write facts, rules and queries and perform the program
Algorithm:
Step 1: Open notepad
Step 2: Enter the necessary facts and rules, save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Facts:
f is c * 9 / 5 +32.
f <=32 .
Rules:
c_to_f(C,F) :-
F is C * 9 / 5 + 32.
freezing(F) :-
F =< 32.
Queries:
?- c_to_f(100,X).
?- freezing(15).
?- freezing(45).
Output:

Result:
Thus, the facts, rules and queries are entered and the program is performed successfully.

23
Roll No :211001120

Exp. No: 4
Monkey Banana Problem
Date: 21.03.2024

Aim:
To write a prolog program to solve monkey banana problem
Algorithm:
Step 1: Open notepad
Step 2: Enter the clauses and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result

Program:
move(state(middle,onbox,middle,hasnot),
grasp,
state(middle,onbox,middle,has)).
move(state(P,onfloor,P,H),
climb,
state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),
drag(P1,P2),
state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),
walk(P1,P2),
state(P2,onfloor,B,H)).
canget(state(_,_,_,has)).
canget(State1) :-
move(State1,_,State2),
canget(State2).

24
Roll No :211001120

Output:

Result:
Thus, the program is executed and the output is verified successfully.

25
Roll No :211001120

Exp. No: 5
Medical Diagnosis
Date: 28.03.2024

Aim:
To write a prolog program for medical diagnosis and show the advantage and
disadvantage of green and red cuts.
Algorithm:
Step 1: Open notepad
Step 2: Enter the clauses and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Program:
go:-
hypothesis(Disease),
write('˜It is suggested that the patient has'),
write(Disease),
nl,
undo;
write('˜Sorry, the system is unable to identify the diseaes'),nl,undo.
hypothesis(cold) :-
symptom(headache),
symptom(runny_nose),
symptom(sneezing),
symptom(sore_throat),
nl,
write('Advices and Sugestions'),
nl,
write('1: Tylenol'),
nl,
write('2: Panadol'),
nl,

26
Roll No :211001120

write('˜3: Nasa spray'),


nl,
write('Please wear warm cloths because'),
nl,!.
hypothesis(influenza) :-
symptom(sore_throat),
symptom(fever),
symptom(headache),
symptom(chills),
symptom(body_ache),
nl,
write('˜Advices and Sugestions'),
nl,
write('1: Tamiflu'),
nl,
write('2: Panadol'),
nl,
write('3: Zanamivir'),
nl,
write('Please take a warm bath and do salt gargling because'),
nl,!.
hypothesis(typhoid) :-
symptom(headache),
symptom(abdominal_pain),
symptom(poor_appetite),
symptom(fever),
nl,
write('˜Advices and Sugestions'),
nl,
write('1: Chloramphenicol'),
nl,
write('˜2: Amoxicillin'),

27
Roll No :211001120

nl,
write('3: Ciprofloxacin'),
nl,
write('4: Azithromycin'),
nl,
write('Please do complete bed rest and take soft diet because'),
nl,!.
hypothesis(chicken_pox) :-
symptom(rash),
symptom(body_ache),
symptom(fever),
nl,
write('Advices and Sugestions:'),
nl,
write('1: Varicella vaccine'),
nl,
write('2: Immunoglobulin'),
nl,
write('3: Acetomenaphin'),
nl,
write('4: Acyclovir'),
nl,
write('Please do have oatmeal bath and stay at home because'),
nl.
hypothesis(measles) :-
symptom(fever),
symptom(runny_nose),
symptom(rash),
symptom(conjunctivitis),
nl,
write('Advices and Sugestions:'),
nl,

28
Roll No :211001120

write('1: Tylenol'),
nl,
write('2: Aleve'),
nl,
write('3: Advil'),
nl,
write('4: Vitamin A'),
nl,
write('Please get rest and use more liquid because'),
nl,!.
hypothesis(malaria) :-
symptom(fever),
symptom(sweating),
symptom(headache),
symptom(nausea),
symptom(vomiting),
symptom(diarrhea),
nl,
write('˜Advices and Sugestions'),
nl,
write('1: Aralen'),
nl,
write('˜2: Qualaquin'),
nl,
write('˜3: Plaquen'),
nl,
write('˜4: Mefloquin'),
nl,
write('˜Please do not sleep in open air and cover your full skin becaue'),
nl,!.
hypothesis(malaria):-
symptom(fever),

29
Roll No :211001120

symptom(sweating),
symptom(headache),
symptom(nausea),
symptom(vomiting),
symptom(diarrhea),
nl,
write('Advices and Sugestions:'),
nl,
write('1: Aralen'),
nl,
write('2: Qualaquin'),
nl,
write('3: Plaquenil'),
nl,
write('4: Mefloquine'),
nl,
write('Please do not sleep in open air and cover your full skin because'),
nl,!.
ask(Question) :-
write('Does the patient has the symptom'),
write(Question),
write('? : '),
read(Response),
nl,
( (Response == yes ; Response == y)
->
assert(yes(Question)) ;
assert(no(Question)), fail).
:- dynamic yes/1,no/1.
symptom(S) :-
(yes(S)
->

30
Roll No :211001120

true ;
(no(S)
->
fail ;
ask(S))).
undo :- retract(yes()),fail. undo :- retract(no()),fail.
undo.
Output:

Result:
Thus, the program is executed and the output is verified successfully.

31
Roll No :211001120

Exp. No: 6
N-Queen Problem
Date: 04.04.2024

Aim:
To write a prolog program to solve 4-Queen problem.
Algorithm:
Step 1: Open notepad
Step 2: Enter the clauses and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Program:
commands :-
write("List of commands:"), nl, nl,
write("print_coordinates"), nl,
write("print_board"), nl,
nl.
print_coordinates :-
solution(A),
display_coordinates(A, 1).
print_board :-
solution(A),
print_boundry,
print_columns(A, 1),
print_column_letters,
nl.
print_square :- write("| ").
print_queen :- write("|Q").
print_end_quare :- write("|"), nl.
print_boundry :- write(" ------------- "), nl.
print_column_letters :- write(" h g f e d c b a "), nl.
print_columns([], _).

32
Roll No :211001120

print_columns([H|T], C) :-
write(C), write(" "),
print_row(H, 1),
C1 is C + 1,
print_columns(T, C1).
print_row(_, 9) :-
print_end_quare,
print_boundry, !.
print_row(X, Col) :-
X is Col, print_queen,
Col1 is Col + 1, print_row(X, Col1).
print_row(X, Col) :-
X =\= Col, print_square,
Col1 is Col + 1, print_row(X, Col1).
solution(Queens) :-
permutation([1,2,3,4,5,6,7,8], Queens),
safe(Queens).
permutation([],[]).
permutation([H|T], P) :-
permutation(T, P1),
mydelete(H, P, P1).
mydelete(X, [X|L], L).
mydelete(X, [Y|L], [Y|L1]) :-
mydelete(X, L, L1).
safe([]).
safe([Queen|Others]) :-
safe(Others),
noattack(Queen,Others,1).
noattack(_,[],_).
noattack(Y, [Y1|L], X1) :-
Y1 - Y =\= X1,
Y - Y1 =\= X1,

33
Roll No :211001120

X2 is X1 + 1,
noattack(Y, L, X2).
display_coordinates([], 9).
display_coordinates([H|T], Y) :-
nth1(H, [h,g,f,e,d,c,b,a], X),
write("["), write(X),
write(Y), write("]"), nl,
Y1 is Y + 1,
display_coordinates(T, Y1).
Output:

Result:
Thus, the program is executed and the output is verified successfully.

34
Roll No :211001120

Exp. No: 7
Travelling Salesman Problem
Date: 04.04.2024

Aim:
To write a prolog program to solve Travelling salesman problem
Algorithm:
Step 1: Open notepad
Step 2: Enter the clauses and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Program:
road(birmingham,bristol, 9).
road(london,birmingham, 3).
road(london,bristol, 6).
road(london,plymouth, 5).
road(plymouth,london, 5).
road(portsmouth,london, 4).
road(portsmouth,plymouth, 8).
get_road(Start, End, Visited, Result) :-
get_road(Start, End, [Start], 0, Visited, Result).
get_road(Start, End, Waypoints, DistanceAcc, Visited, TotalDistance) :-
road(Start, End, Distance),
reverse([End|Waypoints], Visited),
TotalDistance is DistanceAcc + Distance.
get_road(Start, End, Waypoints, DistanceAcc, Visited, TotalDistance) :-
road(Start, Waypoint, Distance),
\+ member(Waypoint, Waypoints),
NewDistanceAcc is DistanceAcc + Distance,
get_road(Waypoint, End, [Waypoint|Waypoints], NewDistanceAcc, Visited,
TotalDistance).

35
Roll No :211001120

Output:

Result:
Thus, the program is executed and the output is verified successfully.

36
Roll No :211001120

Exp. No: 8
Water Jug Problem
Date: 18.04.2024

Aim:
To write a prolog program to solve water jug problem.
Algorithm:
Step 1: Open notepad
Step 2: Enter the clauses and save the file with extension .pl
Step 3: Open prolog prompt and compile the file
Step 4: Run the file and enter the queries
Step 5: Display the result
Program:
min(X,Y,X):-X0,Y
min(_,Y,Y).
rev(L,R):-revacc(L,[],R).
revacc([],R,R):-!.
revacc([H|T],A,R):-revacc(T,[H|A],R).
%Solve water jug problem using DFS
%X,Y are initial contents, Nx,Ny are final contents of jug1 of capacity _ and jug2 of
capacity My respectively after pouring from jug1 into jug2
chk(_,X,My,Y,Nx,Ny):- X>0,Y<My,Ey is My-Y,min(X,Ey,P),
Nx is X-P,Ny is Y+P.
%Given 3 jugs of capacities Mx,My,Mz and filled with X,Y,Z units of a liquid
respectively,give steps so that finally they contain Fx,Fy,Fz units of the liquid
respectively.
jug(Mx,My,Mz,X,Y,Z,Fx,Fy,Fz):-jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,[],['Initially']).
jug(_,Fx,_,Fy,_,Fz,Fx,Fy,Fz,T,R):-
!,rev([[Fx,Fy,Fz],[Fx,Fy,Fz]|T],TR),rev(['Finally'|R],RR),display(TR,RR).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-
chk(Mx,X,My,Y,Nx,Ny),not(member([Nx,Ny,Z],T))
,jug(Mx,Nx,My,Ny,Mz,Z,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug1 into jug2'|R]).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-
chk(Mx,X,Mz,Z,Nx,Nz),not(member([Nx,Y,Nz],T))

37
Roll No :211001120

jug(Mx,Nx,My,Y,Mz,Nz,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug1 into jug3'|R]).


jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-
chk(My,Y,Mz,Z,Ny,Nz),not(member([X,Ny,Nz],T))
,jug(Mx,X,My,Ny,Mz,Nz,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug2 into jug3'|R]).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-
chk(My,Y,Mx,X,Ny,Nx),not(member([Nx,Ny,Z],T))
,jug(Mx,Nx,My,Ny,Mz,Z,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug2 into jug1'|R]).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-

chk(Mz,Z,Mx,X,Nz,Nx),not(member([Nx,Y,Nz],T))
,jug(Mx,Nx,My,Y,Mz,Nz,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug3 into jug1'|R]).
jug(Mx,X,My,Y,Mz,Z,Fx,Fy,Fz,T,R):-
chk(Mz,Z,My,Y,Nz,Ny),not(member([X,Ny,Nz],T))
,jug(Mx,X,My,Ny,Mz,Nz,Fx,Fy,Fz,[[X,Y,Z]|T],['Pour liquid from jug3 into jug2'|R]).
display([],[]):-!.
display([T1|T],[R1|R]):-write(R1),write(' : '),write(T1),nl,display(T,R).

Output:

Result:
Thus, the program is executed and the output is verified successfully.

38
Roll No :211001120

Exp. No: 9
Implementations of Linear Regression
Date: 18.04.2024

Aim:
To Write a python program to implement linear regression.
Algorithm:
Step 1: Open Python notebook
Step 2: import the necessary packages
Step 3: perform different operations and view the dataset by importing it
Step 4: to perform linear regression, import the model
Step 5: Display the result
Program:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dataset = pd.read_csv('/content/student_scores.csv')
dataset.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
print(regressor.intercept_)
print(regressor.coef_)
y_pred = regressor.predict(X_test)

39
Roll No :211001120

df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})

Output:

Result:
Thus, the program is executed and the output is verified successfully.

40
Roll No :211001120

Exp. No: 10
Implementations of Classification
Date: 25.04.2024

Aim:
To write a python program to implement different classification with the dataset.
Algorithm:
Step 1: Open Python notebook
Step 2: Import the necessary packages
Step 3: Perform different operations and view the dataset by importing it
Step 4: Perform necessary classification techniques by importing it
Step 5: Display the result
Program:
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_excel('C:\\Users\\Lenovo\\Desktop\\fruits.xlsx')
fruits.head()
print(fruits.shape)
print(fruits['fruit_name'].unique())
print(fruits.groupby('fruit_name').size())
import seaborn as sns
sns.countplot(fruits['fruit_name'],label="Count")
plt.show()
fruits.drop('fruit_label', axis=1).plot(kind='box', subplots=True, layout=(2,2),
sharex=False, sharey=False, figsize=(9,9),
title='Box Plot for each input variable')
plt.savefig('fruits_box')
plt.show()
import pylab as pl
fruits.drop('fruit_label' ,axis=1).hist(bins=30, figsize=(9,9))
pl.suptitle("Histogram for each numeric input variable")
plt.savefig('fruits_hist')
plt.show()

41
Roll No :211001120

feature_names = ['mass', 'width', 'height', 'color_score']


X = fruits[feature_names]
y = fruits['fruit_label']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print('Accuracy of Logistic regression classifier on training set: {:.2f}'
.format(logreg.score(X_train, y_train)))
print('Accuracy of Logistic regression classifier on test set: {:.2f}'
.format(logreg.score(X_test, y_test)))
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier().fit(X_train, y_train)
print('Accuracy of Decision Tree classifier on training set: {:.2f}'
.format(clf.score(X_train, y_train)))
print('Accuracy of Decision Tree classifier on test set: {:.2f}'
.format(clf.score(X_test, y_test)))
clf2 = DecisionTreeClassifier(max_depth=3).fit(X_train, y_train)
print('Accuracy of Decision Tree classifier on training set: {:.2f}'
.format(clf2.score(X_train, y_train)))
print('Accuracy of Decision Tree classifier on test set: {:.2f}'
.format(clf2.score(X_test, y_test)))
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
print('Accuracy of K-NN classifier on training set: {:.2f}'
.format(knn.score(X_train, y_train)))

42
Roll No :211001120

print('Accuracy of K-NN classifier on test set: {:.2f}'


.format(knn.score(X_test, y_test)))
from sklearn.svm import SVC
svm = SVC()
svm.fit(X_train, y_train)
print('Accuracy of SVM classifier on training set: {:.2f}'
.format(svm.score(X_train, y_train)))
print('Accuracy of SVM classifier on test set: {:.2f}'
.format(svm.score(X_test, y_test)))
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
pred = knn.predict(X_test)
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred))
k_range = range(1, 20)
scores = []
for k in k_range:
knn = KNeighborsClassifier(n_neighbors = k)
knn.fit(X_train, y_train)
scores.append(knn.score(X_test, y_test))
plt.figure()
plt.xlabel('k')
plt.ylabel('accuracy')
plt.scatter(k_range, scores)
plt.xticks([0,5,10,15,20])

43
Roll No :211001120

Output:

44
Roll No :211001120

Result:
Thus, the program is executed and the output is verified successfully.

45
Roll No :211001120

Exp. No:11
Implementations of Neural Networks
Date: 25.04.2024

Aim:
To Write a python program to implement a simple Neural Network.
Algorithm:
Step 1: Open Python notebook
Step 2: import the necessary packages
Step 3: perform different operations and view the dataset by importing it
Step 4: perform necessary classification techniques by importing it
Step 5: Display the result
Program:
import numpy as np
from scipy.special import expit as activation_function
from scipy.stats import truncnorm
def truncated_normal(mean=0, sd=1, low=0, upp=10):
return truncnorm(
(low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)
class Nnetwork:
def init (self,
no_of_in_nodes,
no_of_out_nodes,
no_of_hidden_nodes,
learning_rate):
self.no_of_in_nodes = no_of_in_nodes
self.no_of_out_nodes = no_of_out_nodes
self.no_of_hidden_nodes = no_of_hidden_nodes
self.learning_rate = learning_rate
self.create_weight_matrices()
def create_weight_matrices(self):
""" A method to initialize the weight matrices of the neural network"""
rad = 1 / np.sqrt(self.no_of_in_nodes)

46
Roll No :211001120

X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)


self.weights_in_hidden = X.rvs((self.no_of_hidden_nodes,
self.no_of_in_nodes))
rad = 1 / np.sqrt(self.no_of_hidden_nodes)
X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
self.weights_hidden_out = X.rvs((self.no_of_out_nodes,
self.no_of_hidden_nodes))
def train(self, input_vector, target_vector):
pass # More work is needed to train the network
def run(self, input_vector):
"""running the network with an input vector 'input_vector'.
'input_vector' can be tuple, list or ndarray"""
input_vector = np.array(input_vector, ndmin=2).T
input_hidden = activation_function(self.weights_in_hidden @ input_vector)
output_vector = activation_function(self.weights_hidden_out @ input_hidden)
return output_vector
simple_network = Nnetwork(no_of_in_nodes=2,
no_of_out_nodes=2,
no_of_hidden_nodes=4,
learning_rate=0.6)
simple_network.run([(3, 4)])
Output:

Result:
Thus, the program is executed and the output is verified successfully.

47

You might also like