Lab Manual
Lab Manual
Python:
Step 1: Open google chrome and search ‘python’ and in first link click on
downloads
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 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 8: Click on ‘Install’. Now anaconda will be installed in your computer in few
minutes.
Step 9: After installation, Click on ‘Next’
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
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):
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)
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 = []
def main():
random_list = create_random_list(10, 1, 100)
# Separate the list
odd_list, even_list = separate_odd_even(random_list)
Output:
Lab: 5:
TASK 1:
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
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]
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)
# 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))
# Assuming y_test and result are already defined (predicted and actual values)
cm = confusion_matrix(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
Approach Map labelled input to Understand patterns Folow trial & error
know output & discovers output method