Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Artificial Intelligence

CSL-325
Lab Journal 2-3

Department of Computer Science, Bahria University,


Islamabad, Campus

Submitted To: Prof. Usama Imtiaz


Submitted By: Nosheela Khalid (01-134202-054)
Lab Journal 2-C
1. Write a Pandas program to compute the Euclidean distance between two given series.
The Euclidean distance or Euclidean metric is the "ordinary" straight-line distance
between two points in Euclidean space. With this distance, Euclidean space becomes
a metric space.
Series-1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Series-2: [11, 8, 7, 5, 6, 5, 3, 4, 7, 1]

Program:
import pandas as pd
import math

series = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])


series = pd.Series([11, 8, 7, 5, 6, 5, 3, 4, 7, 1])
# Computing the Euclidean
squared_sum = 0
for i in range(len(series1)):
squared_sum=squared_sum + (series1[i] - series2[i]) ** 2
Euclidean_dist = math.sqrt(squared_sum)
print("The Euclidean distance between two series is: ", Euclidean_dist)

Analysis:
The Euclidean distance can be calculated by the formula d =√ [(x2 – x1)2 + (y2 – y1)2].
So, in this program first we find the squared sun and then take the square root of that squared sum.

2. Import onlineretail.csv dataset (https://www.kaggle.com/vijayuv/onlineretail )


• display data.
df=pd.read_csv("onlineretail.csv",encoding="unicode_escape")
df

• display summary of numerical fields


print("\nSummary of numerical fields:")
df.describe()

• display first and last column.


print("\nFirst and last column:")
df.iloc[:, [0, -1]]
• Find which columns have null/Nan values in them and fill those null/Nan with the
mean of that column. (Do not drop the rows with Nan/Null you have to fill them)
import numpy as np
num_cols = df.select_dtypes(include=[np.number]).columns
df[num_cols] = df[num_cols].fillna(df[num_cols].mean())
df
• Find out which countries contribute the most to the online retailer's sales revenue.
country_sales = df.groupby("Country")["UnitPrice"].sum().reset_index()
print("\nCountries contributing most to sales revenue:")
print(country_sales.sort_values("UnitPrice", ascending=False).head(15))

• Analyze data by plotting histogram.


import matplotlib.pyplot as plt
plt.show()
df.plot(kind='hist')
df.plot.hist()

Lab Journal 3
1. Develop a medical diagnosis system, designed as a Simple reflex agent that diagnose
the disease based on provided symptoms and test reports. Symptoms and test reports
should be taken from the user as percepts and agent must display the diagnosed
disease as its action.
Acute appendicitis:
Symptoms: Fever, Pain in Abdomen especially ILIAC FOSSA, vomiting,
Test: Blood CP with ESR… TLC (Total leucocyte count) will be high, DLC (Differential
leucocyte count) Neutrophils will be high , ESR high
Treatment: Surgery
Pneumonia:
Symptoms: Fever, Cough (with sputum), Pain in chest Blood CP with ESR… TLC (Total
leucocyte count) will be high, DLC (Differential leucocyte count) Neutrophils will be high,
ESR high
X-ray chest: pneumonic patch (sometimes)
Treatment: Antibiotics
Acute Tonsilitis:
Symptoms: Fever, Cough Test: Examine throat: (Red enlarged tonsils, pus in tonsils)
Treatment: anti-allergic, paracetamol. If not gone, add antibiotics orally. If not gone, add
antibiotics IV
Program:
# Define rules for each disease
def diagnose(percepts):
symptoms, test_results = percepts
if "fever" in symptoms and "pain in abdomen" in symptoms and "vomiting" in symptoms and
"high ESR…" in test_results and "high TLC" in test_results:
return "Acute Appendicitis"
elif "fever" in symptoms and "cough" in symptoms and "pain in chest" in symptoms and "high
ESR" in test_results:
return "Pneumonia"
elif "fever" in symptoms and "cough" in symptoms and "red enlarged tonsils" in test_results:
return "Acute Tonsilitis"
else:
return "No diagnosis could be made."

# Take input from the user


symptoms = input("Enter the symptoms (comma-separated): ").lower().split(", ")
test_results = input("Enter the test results (comma-separated): ").lower().split(", ")

# Call the diagnose function with the input


disease = diagnose((symptoms, test_results))

# Output the diagnosed disease


print("Diagnosed disease:", disease)

Analysis:

Using Dictionaries:
diseases={
"Acute appendicitis":{
"Symptoms": ["Fever", "Pain in Abdomen especially ILIAC FOSSA", "vomiting"],
"Test": ["TLC high", "high DLC" , "high ESR"],
"Treatment": "Surgery"
},
"Pneumonia": {
"Symptoms":["Fever", "Cough", "chest pain"],
"Test":["TLC high", "high DLC" , "high ESR" ,"pneumonic patch"],
"Treatment": ["Antibiotics"] },
"Acute Tonsilitis": {
"Symptoms": ["Fever", "Cough"],
"Test": ["Red enlarged tonsils"],
"Treatment": ["anti-allergic", "paracetamol", "antibiotics IV"]}
}

Symptoms=input("Enter your symptoms: ").lower().split(", ")


Test=input("Enter your test report: ").lower().split(", ")

for disease, details in diseases.items():


if set(details["Symptoms"]).issubset(set(Symptoms)) and
set(details["Test"]).issubset(set(Test)):
print("you may have ",disease + ".")
print("Treatment: ",details["Treatment"])
break
else:
print("sorry, we could not diaganose your diseases")

2. Develop a model based agent for the wumpus world shown in the image below. The
agent has to find the gold while updating the state of the world after every action.
Consider the wumpus world as deterministic and partially observable.
Goal: To find the gold and then to go back safely (avoiding pit and wumpus) to its starting
location.
Percepts: pit, gold, empty, wumpus (can have percept of just one block ahead)
Actions: Grab gold, move left, move right, move up, move down, and do nothing.
You will need a class for Agent. It might be useful to define a list of nested lists depicting
which blocks are adjacent to each block (in order to limit percepts to one block ahead in each
adjacent direction) and update states accordingly.
First agent will check state, find out which block he's in.
If block has gold, agent gets the current Action 'Grab gold', then Grabs Gold, then returns to
starting position.
Otherwise, then agent will look at one block ahead (either up, down, left, right) and get percept.
Then agent will update state according to that block & percepts and decide action Repeat steps
until agent gets to gold or exhausts maximum steps =50
When looking for gold, if action is DO NOTHING then return failure and stop execution (this
means that all adjacent blocks have either Wumpus or pits.)
Return success if and only if agent finds gold, grabs gold, AND returns to starting position
successfully. Print current position of agent as well as state after each repetition. You may find
it useful to use input () function to prompt user after every repetition so that the output doesn‘t
flash by too fast and can be viewed by us.
At some stage, if needed, you may also use the built-in random module to randomize the order
in which you access adjacent block percepts. The random. Shuffle (list_as_an_argument)
function might come in handy.

Program:
Wumpus_Map = [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]]
rows = cols = 0
Initial_Status = [rows][cols]
Perceptions = ['pit', 'gold', 'empty', 'wumpus']
Acts = ['Grab gold', 'move left', 'move right', 'move up', 'move down']
class ModelBasedReflexAgent():
actions = []
Percept = []
agent_Status = 0
gold_Status = 0
def __init__(Self, actns, percpt ):
Self.actions = actns
Self.Percept = percpt
gold_Status = 0
def UpdateState(Self, percpt):
Self.agent_Status = percpt
print(f"agent Currently on box {Self.agent_Status}")
return Self.Choose_Action()

def Choose_Action(Self):

if Self.Percept[Self.agent_Status] == 'gold':
print("gathered!")
Self.gold_Status += 2
Self.Percept.pop(Self.agent_Status)
Self.Percept.insert(Self.agent_Status, "none")
if Self.Percept.count('gold')== 0 and Self.Percept.count('pit') == 0:
return 1
elif Self.Percept[Self.agent_Status] == 'pit':
print("ignored!")
if Self.gold_Status >= 0:
Self.gold_Status -= 1
Self.Percept.pop(Self.agent_Status)
Self.Percept.insert(Self.agent_Status, "none")
if Self.Percept.count('gold')== 0 and Self.Percept.count('pit') == 0:
return 1
elif Self.Percept[Self.gold_Status] == 'wumpus':
if Self.gold_Status == 0:
print('Encountered')
return 0
else:
if Self.gold_Status >= 0:
Self.gold_Status -= 1
else:
pass

agent = ModelBasedReflexAgent(Acts, Perceptions)


while(True):
if(cols - 1 >= 0):
print(f"Press 1 to move left to box{Wumpus_Map[rows][cols-1]}")
if(cols + 1 < 4):
print(f"Press 2 to move right to box {Wumpus_Map[rows][cols+1]}")
if(rows - 1 >= 0):
print(f"Press 3 to move up to box {Wumpus_Map[rows - 1][cols]}")
if(rows + 1 < 4):
print(f"Press 4 to move down to box {Wumpus_Map[rows + 1][cols]}")
Entered_number = int(input("Enter from the given choices: "))
if( Entered_number == 1):
cols-=1
result = agent.UpdateState(Wumpus_Map[rows][cols])
if(result == 0):
print("over!")
break
elif(result == 1):
print('You have done.')
break
else:
pass
elif( Entered_number == 2):
cols+=1
result = agent.UpdateState(Wumpus_Map[rows][cols])
if(result == 0):
print("over!")
break
elif(result == 1):
print('you have done.')
break
else:
pass
elif( Entered_number == 3):
rows -=1
result = agent.UpdateState(Wumpus_Map[rows][cols])
if(result == 0):
print("over!")
break
elif(result == 1):
print('You have done.')
break
else:
pass

elif( Entered_number == 4):


rows +=1
result = agent.UpdateState(Wumpus_Map[rows][cols])
if(result == 0):
print("over!")
break
elif(result == 1):
print('you have done.')
break
else:
pass
else:
pass

Analysis:
3. Given a simple pacman game in figure below that consisting of 4*4 grid. The starting
point of pacman is cell 0 and its goal is to consume/eat maximum food pallets, while
considering following given limitations.
• Pacman can move up, down, left right (keeping in view walls).
• Pacman can eat power pallets, i.e., cherries to keep ghost scared such that if pacman
enters the ghost cell it is not destroyed.
• Pacman keeps moving until all the power pallets and food are consumed. You need to
devise a model/goal-based agent for the above given problem.

Program:
Pacman_Map = [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]]
rows = cols = 0
Current_Status = [rows][cols]
Perceptions = ['Start', 'cherry', 'food', 'cherry', 'food', 'ghost', 'food', 'cherry', 'cherry', 'food', 'cherry',
'ghost', 'cherry', 'food', 'ghost', 'food']
Acts = ['Move Up', 'Move Right', 'Move Down', 'Move Left']
class ModelBasedReflexAgent():
actions = []
Percept = []
Pacman_Status = 0
Cherry_Status = 0
def __init__(Self, actns, percpt ):
Self.actions = actns
Self.Percept = percpt
Cherry_Status = 0
def UpdateState(Self, percpt):
Self.Pacman_Status = percpt
print(f"Pacman Currently on tile {Self.Pacman_Status}")
return Self.Choose_Action()

def Choose_Action(Self):

if Self.Percept[Self.Pacman_Status] == 'cherry':
print("Cherry Consumed!")
Self.Cherry_Status += 2
Self.Percept.pop(Self.Pacman_Status)
Self.Percept.insert(Self.Pacman_Status, "none")
if Self.Percept.count('cherry')== 0 and Self.Percept.count('food') == 0:
return 1
elif Self.Percept[Self.Pacman_Status] == 'food':
print("Food Consumed!")
if Self.Cherry_Status >= 0:
Self.Cherry_Status -= 1
Self.Percept.pop(Self.Pacman_Status)
Self.Percept.insert(Self.Pacman_Status, "none")
if Self.Percept.count('cherry')== 0 and Self.Percept.count('food') == 0:
return 1
elif Self.Percept[Self.Pacman_Status] == 'ghost':
if Self.Cherry_Status == 0:
print('Ghost Encountered')
return 0
else:
if Self.Cherry_Status >= 0:
Self.Cherry_Status -= 1
else:
pass

agent = ModelBasedReflexAgent(Acts, Perceptions)


while(True):
if(cols - 1 >= 0):
print(f"Press 1 to move left to tile {Pacman_Map[rows][cols-1]}")
if(cols + 1 < 4):
print(f"Press 2 to move right to tile {Pacman_Map[rows][cols+1]}")
if(rows - 1 >= 0):
print(f"Press 3 to move up to tile {Pacman_Map[rows - 1][cols]}")
if(rows + 1 < 4):
print(f"Press 4 to move down to tile {Pacman_Map[rows + 1][cols]}")

Entered_number = int(input("Enter from the given choices: "))


if( Entered_number == 1):
cols-=1
result = agent.UpdateState(Pacman_Map[rows][cols])
if(result == 0):
print("Game over!")
break
elif(result == 1):
print('Congratulations.....! You have won the Game.')
break
else:
pass
elif( Entered_number == 2):
cols+=1
result = agent.UpdateState(Pacman_Map[rows][cols])
if(result == 0):
print("Game over!")
break
elif(result == 1):
print('Congratulations......! You have won the Game.')
break
else:
pass
elif( Entered_number == 3):
rows -=1
result = agent.UpdateState(Pacman_Map[rows][cols])
if(result == 0):
print("Game over!")
break
elif(result == 1):
print('Congratulations......! You have won the Game.')
break
else:
pass

elif( Entered_number == 4):


rows +=1
result = agent.UpdateState(Pacman_Map[rows][cols])
if(result == 0):
print("Game over!")
break
elif(result == 1):
print('Congratulations.....! You have won the Game.')
break
else:
pass
else:
pass

Analysis:

You might also like