0% found this document useful (0 votes)
23 views44 pages

Lab Manual

Uploaded by

Muhammad Junaid
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)
23 views44 pages

Lab Manual

Uploaded by

Muhammad Junaid
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/ 44

National University of Modern Languages

Department of Computer Science and Software


Engineering

Subject Artificial intelligence

Topic Lab Manual

Submitted to Mam Sehrish

Student Name M.Junaid Akbar

Student Roll No FSD-FL-114


Lab: 1:
Tasks:
1. Python and PyCharm Installation
2. Download Anaconda: https://anaconda.org/
3. Pycharm: https://www.guru99.comhow-to-install-python.html
4. Google Colab: https://colab.research.google.com/

Python:
Step 1: Open google chrome and search ‘python’ and in first link click on
downloads

Step 2: Now on this page of website click on ‘Download Python 3.12.2

Step 3: After the completion of download process, the setup file will be present in
your ‘downloads’ folder. You have to double click on it.
Step 4: Now a setup window will pop up and there, you have to click on ‘Install
Now’.

Step 5: Setup will install python on your computer automatically. After installation
click on ‘close’.
2. PyCharm:
Step 1: Open google chrome and search ‘PyCharm’ and in first link click on
‘download’

Step 2: Now on this page of website click on ‘Download’.


Step 3: After the completion of download process, the setup file will be present in
your ‘downloads’ folder. You have to double click on it.

Step 4: Click ‘Next’.


Step 5: Again, Click ‘Next’.

Step 6: mark the check boxes according to your need and click ‘Next’.
Step 7: Now click ‘Install’.

Step 8: Setup will install python on your computer automatically. After installation
click on ‘close’.
Anaconda:
Step 1: Open google chrome and search ‘Anaconda’ and in first link click on ‘Free
Download’.

Step 2: Now on this page of website click on ‘Download’.


Step 3: After the completion of download process, the setup file will be present in
your ‘downloads’ folder. You have to double click on it.

Step 4: Click on ‘Next’.


Step 5: Click on ‘I Agree’.

Step 6: Click on ‘Next’


Step 7: Click on ‘Next’

Step 8: Click on ‘Install’. Now anaconda will be installed in your computer in few
minutes.
Step 9: After installation, Click on ‘Next’

Step 10: Click on ‘Finish


Lab: 2:
TASK 1:
Write a program that first displays a simple cafe menu (see example below), asks
the user to enter the number of a choice, and either prints the appropriate action OR
prints an error message that their choice was not valid.
Example output:
1. Soup and salad
2. Pasta with meat sauce
3. Chef's special
Which number would you like to order? 2 One Pasta with meat sauce coming right
up! Another example
output:
1. Soup and salad
2. Pasta with meat sauce
3. Chef's special
Which number would you like to order? 5 Sorry, that is not a valid choice.
Code:
import os
def clear_screen():
# Clear the screen based on the operating system
os.system('cls' if os.name == 'nt' else 'clear')
def display_menu():
print("Cafe Menu:")
print("1. Soup and salad")
print("2. Pasta with meat sauce")
print("3. Chef's special")

def get_order():
while True:
display_menu()
choice = input("Which number would you like to order? ")

if choice == '1':
print("One Soup and salad coming right up!")
elif choice == '2':
print("One Pasta with meat sauce coming right up!")
elif choice == '3':
print("One Chef's special coming right up!")
else:
print("Sorry, that is not a valid choice.")
continue # Continue to the next iteration to show the menu again
input("\nPress Enter to continue...") # Wait for user input before
clearing the screen
clear_screen()
get_order()

Output:

TASK 2:
Once upon a time in Apple land, John had three apples, Mary had five apples, and
Adam had six apples.
They were all very happy and lived for a long time. End of story.
Your task is to:
• Create the variables: john, mary, and adam;
• Assign values to the variables. The values must be equal to the numbers of fruit
possessed by John, Mary, and Adam respectively;
• Having stored the numbers in the variables, print the variables on one line, and
separate each of them with a comma;
• Now create a new variable named total Apples equal to addition of the three former
variables.
• Print the value stored in total Apples to the console
• Check if the totalApples is greater, smaller or equal to 10
Code:
# Step 1: Create the variables and assign values
john = 3
mary = 5
adam = 6

# Step 2: Print the variables on one line, separated by commas


print(john, mary, adam, sep=', ')

# Step 3: Create a new variable named total_apples


total_apples = john + mary + adam

# Step 4: Print the value stored in total_apples to the console


print("Total Apples:", total_apples)

# Step 5: Check if total_apples is greater, smaller, or equal to 10


if total_apples > 10:
print("Total Apples is greater than 10.")
elif total_apples < 10:
print("Total Apples is smaller than 10.")
else:
print("Total Apples is equal to 10.")

Output:
Lab: 3:
TASK 1:
Write a program to find the largest of ten numbers provided by user, using functions.
Code:
def find_largest(numbers):

"""Function to find the largest number in a list."""


largest = numbers[0] # Assume the first number is the largest
for num in numbers:
if num > largest:
largest = num # Update largest if current number is greater
return largest

def main():
"""Main function to get user input and find the largest number."""
numbers = [] # array
print("Please enter 10 numbers:")
for i in range(10):
while True:
try:
num = float(input(f"Enter number {i + 1}: ))
numbers.append(num)
break # Exit
except ValueError:
print("Invalid input. Please enter a valid number.")
# Find the largest number
largest_number = find_largest(numbers)

# Print the largest number


print(f"The largest number among the entered numbers is: {largest_number}")
if __name__ == "__main__":
main()

Output:

TASK 2:
Create a class name basic_calc with following attributes and methods; Two integers
(values are passed with instance creation). Different methods such as addition,
subtraction, division, multiplication.
Code:
class BasicCalc:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def addition(self):
return self.num1 + self.num2
def subtraction(self):
return self.num1 - self.num2
def multiplication(self):
return self.num1 * self.num2
def division(self):
if self.num2 == 0:
return "Error: Division by zero is undefined."
return self.num1 / self.num2
def main():
while True:
try:
# Take user input for two integers
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
break # Exit the loop if input is valid
except ValueError:
print("Invalid input. Please enter valid integers.")
calc = BasicCalc(num1, num2)
print("Addition:", calc.addition())
print("Subtraction:", calc.subtraction())
print("Multiplication:", calc.multiplication())
print("Division:", calc.division())
if __name__ == "__main__":
main()

Output:
Lab: 4:
TASK 1:
Write Python Program to Calculate the Length of a String Without Using Built-In
len() Function.
Code:
def calculate_length(input_string):
count = 0 # Initialize count to 0
for char in input_string:
count += 1 # Increment count for each character
return count

def main():
user_input = input("Enter a string: ") # Get input from the user
length = calculate_length(user_input) # Calculate the length
print(f"The length of the string is: {length}")
if __name__ == "__main__":
main()

Output:
Task 2:
Write a program that creates a list of 10 random integers. Then create two lists by
name odd_list and even_list that have all odd and even values of the list
respectively.

Code:
import random
def create_random_list(size, lower_bound, upper_bound):
return [random.randint(lower_bound, upper_bound) for _ in range(size)]

def separate_odd_even(random_list):
odd_list = []
even_list = []

for number in random_list:


if number % 2 == 0:
even_list.append(number)
else:
odd_list.append(number)
return odd_list, even_list

def main():
random_list = create_random_list(10, 1, 100)
# Separate the list
odd_list, even_list = separate_odd_even(random_list)

print("Random List:", random_list)


print("Odd List:", odd_list)
print("Even List:", even_list)
if __name__ == "__main__":
main()

Output:
Lab: 5:
TASK 1:

 Can you name few model-based reflex agents?


 Write a program for model-based reflex agent of your own choice.
This particular world has just two locations: squares A and B. The vacuum agent
perceives which square it is in and whether there is dirt in the square. It can choose
to move left, move right, suck up the dirt, or do nothing. One very simple agent
function is the following: if the current square is dirty, then suck, otherwise move to
the other square.
Write a simple reflex agent for the vacuum cleaner. (Hint: Agent has no initial states
knowledge) If the current square is dirty, then suck; otherwise, move to the other
square. Pseudocode to the task is as follows;
function Reflex-Vacuum-Agent( [location,status]) returns an action
if status = Dirty then return Suck
else if location = A then return Right
else if location = B then return Left

Model-Based Reflex Agents:


Model-based reflex agents maintain an internal state that reflects the unobservable aspects of the
environment. They use this internal state to help them make decisions based on their perceptions.
Here are a few examples of model-based reflex agents:
 Self-Driving Cars:
They use sensors to perceive their surroundings and maintain an internal model of the road,
obstacles, and traffic conditions.
 Robotic Vacuum Cleaners:
They maintain a map of the area they have cleaned and the locations of obstacles to
navigate effectively.
 Game AI:
In video games, AI characters may maintain a model of the game world, including the
positions and states of other characters and objects.
 Smart Home Systems:
These systems can adjust settings based on the time of day, occupancy, and previous user
behavior.

Program for a Model-Based Reflex Agent (Vacuum Cleaner):


Code:
class VacuumCleanerAgent:
def __init__(self):
# Initial state
self.location = 'A'
self.dirt_status = {'A': False, 'B': False}

def perceive(self, location, status):


self.location = location
self.dirt_status[location] = status == 'Dirty'

def reflex_vacuum_agent(self):
if self.dirt_status[self.location]:
return 'Suck'
if self.location == 'A':
return 'Right' # Move to B
elif self.location == 'B':
return 'Left' # Move to A
def simulate_agent():
agent = VacuumCleanerAgent()
perceptions = [
('A', 'Dirty'), # Perception at A, it's dirty
('A', 'Clean'), # Perception at A, it's clean
('B', 'Dirty'), # Perception at B, it's dirty
('B', 'Clean') # Perception at B, it's clean
]
for location, status in perceptions:
agent.perceive(location, status) # Update agent's perception
action = agent.reflex_vacuum_agent()
print(f"Location: {location}, Status: {status} => Action: {action}")
simulate_agent()

Output:
Lab: 6:
TASK 1:
Consider the following:

Use BFS to find the shortest path between A and F. (Hint: the distance between any
consecutive vertices. is 1, i.e. distance between A and D is 2 ((A to B=1) + (B to D=1) = 2) )
Answer:
The shortest path between A and F using BFS is:
A -> B -> C -> F
Distance: 2

Task 2:

Using DFS, check if there is any path exists between any two nodes? Also the return
the path. e.g. If user two vertices i.e. 2 and 1; the program should return : Yes the
paths exist, which are [2,1],[2,0,1].
Code:
def dfs(graph, start, end, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path.append(start)
if start == end:
return True, path
for neighbor in graph[start]:
if neighbor not in visited:
if dfs(graph, neighbor, end, visited, path):
return True, path
path.pop()
return False, path
graph = {
0: [1],
1: [3],
2: [0, 1, 3],
3: [3]
}

start_node = 2
end_node = 1

path_exists, path = dfs(graph, start_node, end_node)

if path_exists:
print(f"Yes, paths exist: {path}")
else:
print("No paths exist between the given nodes.")

Output:
Lab: 7:
TASK 1:
Write a NumPy program to create a random 10x4 array and extract the first five
rows of the array and store them into a variable.
Code:
import numpy as np
random_array = np.random.randint(0, 100, size=(10, 4))

first_five_rows = random_array[:5]

print("Original 10x4 Random Array (Integers):")


print(random_array)
print("\nFirst Five Rows (Integers):")
print(first_five_rows)

Output:
Task 2:
Write a Pandas program to select the rows where the number of attempts in the
examination is greater than 2.
Code:
import pandas as pd
data = {
'Student': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Attempts': [1, 3, 2, 4, 1],
'Score': [85, 78, 90, 88, 92]
}
# DataFrame
df = pd.DataFrame(data)

filtered_df = df[df['Attempts'] > 2]


print("Original DataFrame:")
print(df)
print("\nFiltered DataFrame (Attempts > 2):")
print(filtered_df)
Output:
TASKS 3:
From the sample data given in TASK 2; write a program to calculate the average of
the scores. The program should be able to ignore NaN values.
Code:
import pandas as pd
import numpy as np

# Sample data
data = {
'Student': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Attempts': [1, 3, 2, 4, 1],
'Score': [85, np.nan, 90, 88, np.nan]
}
# DataFrame
df = pd.DataFrame(data)
average_score = np.nanmean(df['Score'])
print("Average Score (ignoring NaN values):", average_score)

Output:

Lab: 8:
Task 1: Difference between Supervised Machine Learning and Unsupervised
Machine Learning
1. Supervised Machine Learning:
 Definition: Supervised machine learning involves training a model on
a labeled dataset, meaning each training example is paired with an
output label.
 Goal: The goal is to learn a mapping from inputs to outputs so the
model can predict the output for new, unseen inputs.
 Applications: Examples include classification (e.g., spam detection in
emails) and regression (e.g., predicting house prices).
2. Unsupervised Machine Learning:
 Definition: Unsupervised machine learning involves training a model
on a dataset without labeled responses. The model tries to learn the
underlying structure of the data.
 Goal: The goal is to identify patterns, groupings, or features in the data.
 Applications: Examples include clustering (e.g., customer
segmentation) and association (e.g., market basket analysis).
Task 2: Difference between Classification Problem and Regression Problem
1. Classification Problem:
 Definition: Classification is a type of supervised learning where the
output variable is a category (e.g., classifying emails as spam or not
spam).
 Output: The output is discrete, meaning the predictions are categorical
labels.
 Examples: Email spam detection, image recognition (e.g., identifying
animals in pictures), medical diagnosis.
2. Regression Problem:
 Definition: Regression is a type of supervised learning where the
output variable is a real value (e.g., predicting the price of a house).
 Output: The output is continuous, meaning the predictions are real
numbers.
 Examples: Predicting stock prices, forecasting temperature, estimating
the amount of rainfall.
Task 3: Difference between Machine Learning and Deep Learning
1. Machine Learning:
 Definition: Machine learning is a subset of artificial intelligence that
includes a variety of algorithms (e.g., decision trees, support vector
machines) for learning from data.
 Model Structure: Traditional machine learning models often require
manual feature extraction and selection.
 Complexity: Typically used for simpler tasks and can perform well on
smaller datasets.
 Examples: Linear regression, k-nearest neighbors, decision trees.
2. Deep Learning:
 Definition: Deep learning is a subset of machine learning that uses
neural networks with many layers (deep neural networks) to model
complex patterns in data.
 Model Structure: Deep learning models automatically perform feature
extraction and can handle raw data (e.g., images, text).
 Complexity: Used for more complex tasks and requires large amounts
of data and computational power.
 Examples: Convolutional neural networks (CNNs) for image
recognition, recurrent neural networks (RNNs) for sequence prediction.
Task 4: Difference between Keras and TensorFlow Frameworks
1. Keras:
 Definition: Keras is an open-source deep learning API written in
Python, designed for human usability and rapid experimentation.
 Ease of Use: Known for its user-friendly, simple, and clean interface.
It allows for easy and fast prototyping.
 Backend: Initially, Keras could run on top of multiple backends (e.g.,
TensorFlow, Theano). Since TensorFlow 2.0, it has been integrated into
TensorFlow and acts as its official high-level API.
 Flexibility: Higher-level and less flexible than TensorFlow in terms of
lower-level operations.
2. TensorFlow:
 Definition: TensorFlow is an open-source machine learning library
developed by Google. It is more comprehensive and flexible for
machine learning tasks.
 Ease of Use: Offers both high-level APIs (like Keras) and low-level
APIs for more control and customization.
 Capabilities: Can handle a broader range of machine learning and deep
learning tasks, including but not limited to neural networks.
 Flexibility: Provides more flexibility for building complex models and
performing low-level operations, making it suitable for research and
production.

Lab: 9:
Task no 1: Implement K-NN Classifier:
The data set contains 3 classes of 50 instances each, where each class refers to a type
of iris plant.
Attribute Information:
1. sepal length in cm
2. sepal width in cm
3. petal length in cm
4. petal width in cm
5. class:
 Iris Setosa
 Iris Versicolour
 Iris Virginica
Output:
Task no 2: Implement support vector machine for the same classification problem
Lab: 10:
Task 1: Implement Linear Regression

Output:
Task 2: Implement Linear and Non-Linear Regression on a Dataset of Choice
1. Linear Regression

Output:
2. Non-Linear Regression

Output:

Lab: 11:

Task no 1:
Use sepal_length and sepal_width as features from the iris_dataset discussed
in previous labs and apply K-mean clustering algorithm.
Attach the code and graph.
Output:
Lab: 12:
Task no 1:
Change the number of the layers and neurons in neural network and observe if the
score improves or not. Share the graphs
Lab: 13:
Lab Task:
Implement this code:
from sklearn.metrics import accuracy_score,
confusion_matrix,
roc_auc_score,plot_roc_curve,
classification_report cm=confusion_matrix(y_test,result)
tn=cm[0,0] fp=cm[0,1] print(confusion_matrix(y_test,result))
print('auc: ',roc_auc_score(y_test,result)) plot_roc_curve(classifier,x_test,y_test)
plt.show()
print(classification_report(y_test,result)) print(accuracy_score(y_test,result))

import matplotlib.pyplot as plt


from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score,
plot_roc_curve, classification_report

# Assuming y_test and result are already defined (predicted and actual values)
cm = confusion_matrix(y_test, result)

# Extracting individual elements of the confusion matrix


tn = cm[0, 0]
fp = cm[0, 1]
fn = cm[1, 0]
tp = cm[1, 1]
# Printing confusion matrix and other evaluation metrics
print("Confusion Matrix:")
print(cm)
# AUC (Area Under the Curve) score
print('AUC:', roc_auc_score(y_test, result))

# Plotting the ROC curve


plot_roc_curve(classifier, x_test, y_test)
plt.show()

# Classification report (precision, recall, f1-score)


print("Classification Report:")
print(classification_report(y_test, result))

# Accuracy score
print("Accuracy:", accuracy_score(y_test, result))
Lab: 15:
Reinforcement learning:
It is a part of machine learning where an agent put in an enviroument and he learn to have this
enviroument by performing retain action and observingrewards which get from those actions.
Sub-tasks:
Game AI...skill equisition...learning task ...robot navigation...realtime decisions

Supervised learning:
Algorithms
 Linear regression
 Logistic regression
 Dicision trees
 Random forest
 K-Nearest neighbour
 SVM (sport vector machine)
A) classification (important): E.g: Email spam
1. Image classification
2. Customer retension
3. Identity fraud detection
4. Dygnostic system
B)regression (important): E.g: Stock market price prediction
 Advertising popularity prediction
 Whether forcasting
 Market forcasting
 Estimating life expectency
 Population growth prediction

Types of unsupervised learning:


Algorithms:
 Apriori algorithm
 K-means clustring (important)
 Similar value decomposition
 Principle component analysis
 Independent component analysis
A) dimensionaly reduction:
1. Big data visualization
2. Meaningful compression
3. Structure dicovery
4. Feature elisation
B) Clustring(important): E.g: Fraud detection
1. Targeted marketing
2. Recommended system
3. Customer submention

Supervised learning Unsupervised Reinforcement


learning learning

Definition Use machine learning Unlabelled data An agent ineracts


By using labelled without any guidance with its enviroument
data by producing actions
& discovers errors or
rewards
Types of problems Regression & Association & Reward based
classification Clustring

Types of data Labelled data Unlabelled data No pre defined data

Training External supervison No supervision No supervision

Approach Map labelled input to Understand patterns Folow trial & error
know output & discovers output method

Popular algorithm Linear regression k-means,C-means, Q-learning,


logistic regression etc. SARSA,etc.
support vector
machine , KNN etc.

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