FACULTY OF ENGINEERING AND TECHNOLOGY
BACHELOR OF TECHNOLOGY
Artificial Intelligence Laboratory
(303105308)
SEMESTER V
Computer Science & Engineering
Department
CERTIFICATE
This is to certify that
Mr./Miss ___________ with Enrollment No. _____________________
has successfully completed his/her laboratory experiments in the
Artificial Intelligence Lab (303105308) from the department of
Computer Science and Engineering during the academic year 2025-
2026.
Date of Submission ….…………… Staff In charge …..……………
Head of Department………….……
TABLE OF CONTENTS
SR.NO Experiment Page No Date of Date of Marks Sign
Title Perfomance Submission
From To
1 Develop an AI-based medical diagnosis system using
expert systems architecture and knowledge
representation techniques.
2 Build an intelligent agent for optimizing e-commerce
inventory management using search algorithms like hill
climbing and best-first search.
3 Implement a constraint satisfaction algorithm to solve
scheduling problems in healthcare facilities
4 Create a recommendation system for personalized
learning using means-end analysis and heuristic search
techniques.
5 Develop a problem-solving agent for optimizing
resource allocation in logistics using A* and AO*
algorithms.
6 Develop a fuzzy logic-based system for predicting
stock market trends considering uncertain market
conditions.
7 Write a program to implement BFS (Water Jug
problem or any AI search problem).
Write a program to implement DFS (Water Jug
problem or any AI search problem).
8 Define a predicate brother(X,Y) which holds iff X and
Y are brothers.
Define a predicate cousin(X,Y) which holds iff X and
Y are cousins.
Define a predicate grandson(X,Y) which holds iff X is
a grandson of Y.
Define a predicate descendent(X,Y) which holds iff X
is a descendent of Y.
Consider the following genealogical tree:
father(a,b).
father(a,c).
father(b,d).
father(b,e).
father(c,f).
Say which answers, and in which order, are generated
by your definitions for the following queries in Prolog:
?- brother(X,Y).
?- cousin(X,Y).
?- grandson(X,Y).
?- descendent(X,Y).
9 Write a program to implement Tic-Tac-Toe game using
python.
10 Create a spell-checking application utilizing natural
language processing (NLP) techniques, including
syntactic and semantic analysis.
11 Design a neural network architecture for pattern
recognition in medical imaging for disease diagnosis.
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 01
Aim: Develop an AI-based medical diagnosis system using expert systems architecture and
knowledge representation techniques.
Program:
% Define symptoms
symptom(fever).
symptom(cough).
symptom(headache).
symptom(sore_throat).
symptom(body_aches).
% Define diseases along with their symptoms
disease(flu, [fever, cough, body_aches]).
disease(cold, [fever, cough, sore_throat]).
disease(tension_headache, [headache]).
% Rules to check if a patient has a particular disease
has_disease(PatientSymptoms, Disease) :-
disease(Disease, DiseaseSymptoms),
subset(DiseaseSymptoms, PatientSymptoms).
% Rules to collect symptoms from the patient
collect_symptoms(Symptoms) :-
write('Enter symptoms (in a list, e.g., [fever, cough]): '),
read(Symptoms),
validate_symptoms(Symptoms).
% Validate the input symptoms to ensure they are known symptoms
validate_symptoms([]).
validate_symptoms([Symptom|Rest]) :-
symptom(Symptom),
validate_symptoms(Rest).
% Predicate to check if a list is a subset of another list
1|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
subset([], _).
subset([X|XS], List) :-
member(X, List),
subset(XS, List).
% Predicate to make diagnosis
diagnose :-
collect_symptoms(PatientSymptoms),
( has_disease(PatientSymptoms, Disease)
-> format('The patient may have: ~w.~n', [Disease])
; write('Unable to diagnose the disease based on provided symptoms.')
).
Output:
2|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 02
Aim: Build an intelligent agent for optimizing e-commerce inventory management using
search algorithms like hill climbing and best-first search.
Program:
% Initial prices and demand function
initial_prices([100, 150, 200, 250]).
% Demand function
demand(Price, Demand) :-
Demand is 1000 - 5 * Price.
% Calculate revenue for a list of prices
calculate_revenue([], 0).
calculate_revenue([Price|Rest], Revenue) :-
demand(Price, Demand),
calculate_revenue(Rest, RestRevenue),
Revenue is Price * Demand + RestRevenue.
% Generate neighbors by adjusting prices by ±10
get_neighbors(Prices, Neighbors) :-
findall(NewPrices, (member(Price, Prices), select(Price, Prices, Rest), member(Change, [-10,
10]), NewPrice is Price + Change, append(Rest, [NewPrice], NewPrices)), Neighbors).
% Hill climbing algorithm
hill_climb(Prices, OptimalPrices, MaxRevenue) :-
calculate_revenue(Prices, CurrentRevenue),
hill_climb_helper(Prices, CurrentRevenue, OptimalPrices, MaxRevenue).
hill_climb_helper(CurrentSolution, CurrentRevenue, OptimalPrices, MaxRevenue) :-
get_neighbors(CurrentSolution, Neighbors),
find_best_neighbor(Neighbors, CurrentSolution, CurrentRevenue, BestNeighbor,
BestNeighborRevenue),
(
BestNeighborRevenue > CurrentRevenue
-> hill_climb_helper(BestNeighbor, BestNeighborRevenue, OptimalPrices, MaxRevenue)
; OptimalPrices = CurrentSolution, MaxRevenue = CurrentRevenue
).
% Find the best neighbor
find_best_neighbor([], BestNeighbor, BestRevenue, BestNeighbor, BestRevenue).
find_best_neighbor([Neighbor|Rest], CurrentBest, CurrentBestRevenue, BestNeighbor,
BestRevenue) :-
calculate_revenue(Neighbor, NeighborRevenue),
3|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
(
NeighborRevenue > CurrentBestRevenue
-> find_best_neighbor(Rest, Neighbor, NeighborRevenue, BestNeighbor, BestRevenue)
; find_best_neighbor(Rest, CurrentBest, CurrentBestRevenue, BestNeighbor, BestRevenue)
).
% Run the hill climbing algorithm
run_hill_climb :-
initial_prices(Prices),
hill_climb(Prices, OptimalPrices, MaxRevenue),
write('Optimal prices: '), write(OptimalPrices), nl,
write('Maximum revenue: '), write(MaxRevenue), nl.
Output:
4|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 03
Aim: Implement a constraint satisfaction algorithm to solve scheduling problems in
Healthcare facilities
Program:
% Define the availability of each doctor for different shifts
availability('Dr. Kunj', 'Morning').
availability('Dr. Kunj', 'Afternoon').
availability('Dr. Dhairya', 'Afternoon').
availability('Dr. Dhairya', 'Night').
availability('Dr. Jitesh', 'Morning').
availability('Dr. Jitesh', 'Night').
availability('Dr. Naitik', 'Night').
availability('Dr. Naitik', 'mid-evening').
% Define the constraint that all shifts must be assigned to different doctors
all_different([Morning, Afternoon, Night, MidEvening]) :-
Morning \= Afternoon,
Morning \= Night,
Morning \= MidEvening,
Afternoon \= Night,
Afternoon \= MidEvening,
Night \= MidEvening.
% Define the solution predicate
schedule(Solution) :-
Solution = [morning(Morning), afternoon(Afternoon), night(Night), mid_evening(MidEvening)],
availability(Morning, 'Morning'),
availability(Afternoon, 'Afternoon'),
availability(Night, 'Night'),
availability(MidEvening, 'mid-evening'),
all_different([Morning, Afternoon, Night, MidEvening]).
% Query to find the solution
?- schedule(Solution), writeln(Solution).
Output:
5|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 04
Aim: Create a recommendation system for personalized learning using means-end analysis
and heuristic search techniques.
Program:
% Define the facts and rules for the recommender system
% Rules for user interests
likes_tech(User) :- interest(User, tech).
likes_books(User) :- interest(User, books).
likes_workout(User) :- interest(User, workout).
% Rules for user age
age_under_30(User) :- age(User, Age), Age < 30.
% Rules for user location
lives_in_usa(User) :- location(User, usa).
lives_in_india(User) :- location(User, india).
lives_in_germany(User) :- location(User, germany).
% Recommendations based on conditions
recommend(User, 'Smartphone') :- likes_tech(User).
recommend(User, 'Laptop') :- likes_tech(User).
recommend(User, 'E-Reader') :- likes_books(User).
recommend(User, 'Kindle') :- likes_books(User).
recommend(User, 'Gaming Console') :- age_under_30(User).
recommend(User, 'Amazon Prime Membership') :- lives_in_usa(User).
recommend(User, 'Netflix Membership') :- lives_in_india(User).
recommend(User, 'Disney+ Membership') :- lives_in_germany(User).
recommend(User, 'Gym') :- likes_workout(User).
% Example users
interest(kunj, tech).
interest(kunj,workout).
age(kunj, 19).
location(kunj, india).
interest(jitesh, books).
interest(jitesh, travel).
age(jitesh, 21).
location(jitesh, usa).
6|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
interest(dhairya,tech).
interest(dhairya, travel).
age(dhairya, 18).
location(dhairya, germany).
% Get recommendations for a user
get_recommendations(User, Recommendations) :-
findall(Recommendation, recommend(User, Recommendation), Recommendations).
% Query examples
% To get recommendations for kunj:
% ?- get_recommendations(kunj, Recommendations).
% To get recommendations for jitesh:
% ?- get_recommendations(jitesh, Recommendations).
% To get recommendations for dhairya:
% ?- get_recommendations(dhairya, Recommendations).
Output:
7|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 05
Aim: Develop a problem-solving agent for optimizing resource allocation in logistics using A*
and AO* algorithms.
Program:
% state(Name, CostFromStart, HeuristicCost)
state(a, 0, 5).
state(b, 1, 4).
state(c, 2, 2).
state(d, 3, 1).
state(e, 4, 0).
% actions(State, Successor, Cost)
action(a, b, 1).
action(b, c, 1).
action(c, d, 1).
action(d, e, 1).
action(a, c, 2).
action(b, d, 2).
action(c, e, 2).
% a_star(Start, Goal, Path, Cost)
a_star(Start, Goal, Path, Cost) :-
heuristic(Start, HCost),
a_star_search([node(Start, 0, HCost, [])], Goal, RevPath, Cost),
reverse(RevPath, Path).
% a_star_search(OpenList, Goal, Path, Cost)
a_star_search([node(State, G, _, Path) | _], State, [State | Path], G).
a_star_search([node(State, G, _, Path) | Rest], Goal, FinalPath, FinalCost) :-
findall(node(S, G1, H1, [State | Path]),
(action(State, S, C), G1 is G + C, heuristic(S, H1)),
Successors),
append(Rest, Successors, NewOpenList),
sort(3, @=<, NewOpenList, SortedOpenList),
a_star_search(SortedOpenList, Goal, FinalPath, FinalCost).
8|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
% heuristic(State, HCost)
heuristic(e, 0).
heuristic(d, 1).
heuristic(c, 2).
heuristic(b, 4).
heuristic(a, 5).
% Example usage:
% ?- a_star(a, e, Path, Cost).
Output:
9|Page
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 06
Aim: Develop a fuzzy logic-based system for predicting stock market trends considering
uncertain market conditions.
Program:
% Define fuzzy values for market sentiment, volume, and volatility
sentiment(positive, 0.7).
sentiment(neutral, 0.5).
sentiment(negative, 0.3).
volume(high, 0.8).
volume(medium, 0.5).
volume(low, 0.2).
volatility(high, 0.7).
volatility(medium, 0.5).
volatility(low, 0.3).
% Define fuzzy rules for predicting market trends
rule(bullish, S, V, Vol) :-
sentiment(S, SentScore),
volume(V, VolScore),
volatility(Vol, VolatScore),
OverallScore is (SentScore + VolScore + VolatScore) / 3,
OverallScore > 0.6.
rule(bearish, S, V, Vol) :-
sentiment(S, SentScore),
volume(V, VolScore),
volatility(Vol, VolatScore),
OverallScore is (SentScore + VolScore + VolatScore) / 3,
OverallScore < 0.4.
rule(neutral, S, V, Vol) :-
sentiment(S, SentScore),
volume(V, VolScore),
volatility(Vol, VolatScore),
OverallScore is (SentScore + VolScore + VolatScore) / 3,
OverallScore =< 0.6,
OverallScore >= 0.4.
10 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
% Predict market trend based on sentiment, volume, and volatility
predict_trend(Sentiment, Volume, Volatility, Trend) :-
rule(Trend, Sentiment, Volume, Volatility).
Output:
11 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 07
Aim:
- Write a program to implement BFS (Water Jug problem or any AI search problem).
- Write a program to implement DFS (Water Jug problem or any AI search problem).
Program:
BFS (Water Jug problem):
% Define the initial state (both jugs are empty).
initial_state((0, 0)).
% Define the goal state (Jug1 has 2 liters).
goal((2, _)).
% Define possible capacities of jugs.
capacity(4, 3). % Jug1 can hold 4 liters, Jug2 can hold 3 liters.
% Main BFS function to find the solution path.
bfs :-
initial_state(Start),
bfs_solve([(Start, [])], Solution),
reverse(Solution, Path),
write('Path: '), nl,
print_path(Path).
% BFS solver function.
bfs_solve([(State, Path) | _], [State | Path]) :-
goal(State).
bfs_solve([(State, Path) | Rest], Solution) :-
findall((NextState, [State | Path]),
(move(State, NextState), \+ member((NextState, _), [(State, Path) | Rest])),
NextStates),
append(Rest, NextStates, NewQueue),
bfs_solve(NewQueue, Solution).
% Possible moves between states.
move((X, Y), (4, Y)) :- X < 4. % Fill Jug1.
move((X, Y), (X, 3)) :- Y < 3. % Fill Jug2.
move((X, Y), (0, Y)) :- X > 0. % Empty Jug1.
move((X, Y), (X, 0)) :- Y > 0. % Empty Jug2.
move((X, Y), (NewX, 0)) :- X + Y =< 4, NewX is X + Y. % Pour Jug2 into Jug1 until Jug2 is
empty.
move((X, Y), (4, NewY)) :- X + Y > 4, NewY is Y - (4 - X). % Pour Jug2 into Jug1 until Jug1 is
12 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
full.
move((X, Y), (0, NewY)) :- X + Y =< 3, NewY is X + Y. % Pour Jug1 into Jug2 until Jug1 is
empty.
move((X, Y), (NewX, 3)) :- X + Y > 3, NewX is X - (3 - Y). % Pour Jug1 into Jug2 until Jug2 is
full.
% Helper to print the path.
print_path([]).
print_path([H|T]) :-
write(H), nl,
print_path(T).
Output:
13 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
DFS (Water Jug problem):
% Define the initial state (both jugs are empty).
initial_state((0, 0)).
% Define the goal state (Jug1 has 2 liters).
goal((2, _)).
% Define possible capacities of jugs.
capacity(4, 3). % Jug1 can hold 4 liters, Jug2 can hold 3 liters.
% Main DFS function to find the solution path.
dfs :-
initial_state(Start),
dfs_solve(Start, [], Solution),
reverse(Solution, Path),
write('Path: '), nl,
print_path(Path).
% DFS solver function.
dfs_solve(State, Path, [State | Path]) :-
goal(State).
dfs_solve(State, Path, Solution) :-
move(State, NextState),
\+ member(NextState, Path),
dfs_solve(NextState, [State | Path], Solution).
% Possible moves between states.
move((X, Y), (4, Y)) :- X < 4. % Fill Jug1.
move((X, Y), (X, 3)) :- Y < 3. % Fill Jug2.
move((X, Y), (0, Y)) :- X > 0. % Empty Jug1.
move((X, Y), (X, 0)) :- Y > 0. % Empty Jug2.
move((X, Y), (NewX, 0)) :- X + Y =< 4, NewX is X + Y. % Pour Jug2 into Jug1 until Jug2 is
empty.
move((X, Y), (4, NewY)) :- X + Y > 4, NewY is Y - (4 - X). % Pour Jug2 into Jug1 until Jug1 is
full.
move((X, Y), (0, NewY)) :- X + Y =< 3, NewY is X + Y. % Pour Jug1 into Jug2 until Jug1 is
empty.
move((X, Y), (NewX, 3)) :- X + Y > 3, NewX is X - (3 - Y). % Pour Jug1 into Jug2 until Jug2 is
full.
14 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
% Helper to print the path.
print_path([]).
print_path([H|T]) :-
write(H), nl,
print_path(T).
Output:
15 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 08
Aim:
Given the following Prolog facts:
- father(a, b).
- father(a, c).
- father(b, d).
- father(b, e).
- father(c, f).
-
Define the following predicates:
1. brother(X, Y): X and Y are brothers.
2. cousin(X, Y): X and Y are cousins.
3. grandson(X, Y): X is a grandson of Y.
4. descendent(X, Y): X is a descendant of Y.
For each query, provide the results and their order:
1. ?- brother(X, Y).
2. ?- cousin(X, Y).
3. ?- grandson(X, Y).
4. ?- descendent(X, Y).
Program:
% Define the father relationships
father(a, b).
father(a, c).
father(b, d).
father(b, e).
father(c, f).
% Define the brother predicate
brother(X, Y) :-
father(F, X),
father(F, Y),
X \= Y.
% Define the cousin predicate
cousin(X, Y) :-
father(F1, X),
father(F2, Y),
brother(F1, F2).
16 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
% Define the grandson predicate
grandson(X, Y) :-
father(Y, P),
father(P, X).
% Define the descendant predicate
descendant(X, Y) :-
father(Y, X).
descendant(X, Y) :-
father(Y, P),
descendant(X, P).
Output:
17 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 09
Aim: Write a program to implement Tic-Tac-Toe game using python.
Program:
# Tic-Tac-Toe Game in Python
# Function to print the board
def print_board(board):
print("\n")
print(" " + board[0] + " | " + board[1] + " | " + board[2])
print("---|---|---")
print(" " + board[3] + " | " + board[4] + " | " + board[5])
print("---|---|---")
print(" " + board[6] + " | " + board[7] + " | " + board[8])
print("\n")
# Function to check if there is a winner
def check_winner(board, player):
# Winning combinations
win_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
# Check if any winning combination is achieved by the player
for combo in win_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] == player:
return True
return False
# Function to check if the board is full
def check_draw(board):
return ' ' not in board
# Function to get the player's move
def player_move(board, player):
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if move < 0 or move > 8:
print("Invalid move. Please enter a number between 1 and 9.")
elif board[move] != ' ':
print("This spot is already taken. Choose another spot.")
else:
18 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
board[move] = player
break
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
# Main function to run the game
def tic_tac_toe():
board = [' ' for _ in range(9)] # Initialize empty board
current_player = 'X' # X always starts first
while True:
print_board(board)
player_move(board, current_player)
# Check if the current player has won
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
# Check for a draw
if check_draw(board):
print_board(board)
print("The game is a draw!")
break
# Switch players
current_player = 'O' if current_player == 'X' else 'X'
# Run the game
if __name__ == "__main__":
tic_tac_toe()
19 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
Output:
20 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 10
Aim: Create a spell-checking application utilizing natural language processing (NLP) techniques,
including syntactic and semantic analysis.
Program:
# Install necessary libraries
!pip install nltk
!pip install textblob
# Import required modules
import nltk
from textblob import TextBlob
from nltk.tokenize import word_tokenize
from nltk.corpus import words
# Download necessary NLTK datasets
nltk.download('punkt')
nltk.download('words')
# Initialize NLTK words list
word_list = set(words.words())
# Function to check if a word is spelled correctly
def is_correctly_spelled(word):
return word.lower() in word_list
# Function to suggest corrections using TextBlob
def suggest_corrections(word):
blob = TextBlob(word)
return str(blob.correct())
# Function to check and suggest corrections for the sentence
def spell_check(text):
tokens = word_tokenize(text)
corrections = {}
for word in tokens:
if not is_correctly_spelled(word) and word.isalpha(): # Ensure it's a word
suggestions = suggest_corrections(word)
corrections[word] = suggestions
return corrections
# Main program
user_input = input("Enter a sentence to check for spelling errors: ")
corrections = spell_check(user_input)
21 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
if corrections:
for misspelled, suggestion in corrections.items():
print(f"Misspelled word: '{misspelled}' -> Suggested correction: '{suggestion}'")
else:
print("No spelling errors found.")
Output:
22 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
PRACTICAL: 11
Aim: Design a neural network architecture for pattern recognition in medical imaging for
disease diagnosis.
Program:
# Import necessary libraries
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
# Project Contributors: Kunj, Jitesh, Dhairya
train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_generator = train_datagen.flow_from_directory(
'/content/medical_images', # Update this with your dataset path
target_size=(128, 128),
batch_size=32,
class_mode='binary', # Change to 'categorical' if multi-class
subset='training')
validation_generator = train_datagen.flow_from_directory(
'/content/medical_images',
target_size=(128, 128),
batch_size=32,
class_mode='binary',
subset='validation')
# Build the CNN model
model = models.Sequential()
# 1st Convolutional Block
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)))
model.add(layers.MaxPooling2D((2, 2)))
# 2nd Convolutional Block
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
23 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
# 3rd Convolutional Block
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
# 4th Convolutional Block
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
# Flatten and Dense layers
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dropout(0.5)) # Prevent overfitting
model.add(layers.Dense(1, activation='sigmoid')) # For binary classification
# Compile the model
model.compile(optimizer='adam',
loss='binary_crossentropy', # Use 'categorical_crossentropy' for multi-class
metrics=['accuracy'])
# Summary of the model
model.summary()
# Train the model
history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // train_generator.batch_size,
epochs=20, # You can increase the number of epochs
validation_data=validation_generator,
validation_steps=validation_generator.samples // validation_generator.batch_size
)
# Plot training & validation accuracy and loss
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.figure(figsize=(12, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
24 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
# Evaluate the model on the validation set
test_loss, test_acc = model.evaluate(validation_generator, steps=validation_generator.samples //
validation_generator.batch_size)
print(f"Test Accuracy: {test_acc:.2f}")
25 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
B.Tech - CSE 3rd Year 5th Semester
Output:
26 | P a g e